Decorator

is a special function that do nothting on its own but can be used to change the behavior of other function.

——

e.g.,

from django.contrib.auth.decorators import login_required

def delete_bookmark(request, card_id):

# func definition

delete_bookmark = login_required(delete_bookmark)

card=Card.objects.get(name=query)

may result in exception Card.DoesNotExist

so,

card=get_object_or_404(Card,name-query)

will

1. use the same get() lookup

2. catch the DoesNotExist exception

3. trigger django.http.Http404, which will turn it into an HTTP 404 response.

def func(*args, **kwargs):

Python functions and methods can pass and receive arguments in two forms:

1. positional argument (the order is important)

2. keyword argument(names along with the values)

In Python, list and dictionary types are used for positional and keyword arguments respectively.

Passing a list as an argument and prefixing it with a single asterisk(*) will cause each item of the list in order. This will be used as a separate positional argument.

Passing a dictionary and prefixing it two asterisks(**) will cause the keys of the dictionary to be used as names for separate keyword arugments and the dictionary’s values to become the values of these arguments.

in urls.py

r(‘^card/(?P<year>\d{4})/(?P<month>\w{3})(?P<day>\d{2})/(?P<slug>[-\w]+)/$’, ‘card_detail’),

in views.py

def card_detail(request, year, month, day, slug):

# do render

————-

will return dictionary with keys are bracketed names and the values are the parts of the text that matched.

{{card.body|safe}}

Django template automatically “escapes” the contents of variables to prevent cross-site scripting attacks.

The safe filter lets you tell Django that you trust a variable and it doesn’t need a escaping.

other example of filter

{{card.body_html|truncatedwords_html:”50″|safe}}

{{card.pub_date|date:”F j, Y”}}

class Meta:

order = ['name']

——-

class Meta:

ordering=['-pub_date']

——-

class Meta:

ordering=['+pub_date']

——-

Django will retrieve list of objects in order, by name, descending or ascending pub_date etc.

1. constants or list of choices

2. full list of fields

3. Meta class

4. __unicode__() method

5. save()

6. get_absolute_url()

7. any additional custom methods

lower()

is a Python string method to return a string converted to lowercase

—-

e.g.,

def get_absolute_url(self):

return “/card/%s/%s/” % (self.pub_date.strftime(“%Y/%b/%d”).lower(), self.slug)

The subclass needs a way to access parent class.

super

is the parent class.

—-

def save(self):

# do something specific customized actions for the model

super(Card, self).save()  #perform parent class’s save

——-

editable=False

tells Django not to display the field when it automatically generate the form.

e.g.,

body_html=models.TextField(editable=False, blank=True)

© 2011 Web Oom Suffusion theme by Sayontan Sinha
Switch to our mobile site
Page 5 of 11« First...«34567»10...Last »Top Footer