Django Documentation - Read the Docs [PDF]

Tutorial: Part 1: Requests and responses | Part 2: Models and the admin site | Part 3: Views and templates |. Part 4: Fo

5 downloads 46 Views 6MB Size

Recommend Stories


Python Guide Documentation - Read the Docs [PDF]
del tipo de software que estás escribiendo; si eres principiante hay cosas más importantes por las que preocuparse. ... Si estas escribiendo código abierto Python y deseas alcanzar una amplia audiencia posible, apuntar a CPython es lo mejor. .....

Django Notify Documentation
When you do things from your soul, you feel a river moving in you, a joy. Rumi

Django Story Documentation
Seek knowledge from cradle to the grave. Prophet Muhammad (Peace be upon him)

Django Map Widgets Documentation
What you seek is seeking you. Rumi

django-rest-auth Documentation
Life is not meant to be easy, my child; but take courage: it can be delightful. George Bernard Shaw

django-rest-auth Documentation
I tried to make sense of the Four Books, until love arrived, and it all became a single syllable. Yunus

django-registration Documentation
Learning never exhausts the mind. Leonardo da Vinci

django-registration-redux Documentation
Sorrow prepares you for joy. It violently sweeps everything out of your house, so that new joy can find

django-osgeo-importer Documentation
Happiness doesn't result from what we get, but from what we give. Ben Carson

PdF Django Unleashed Read Book
Don’t grieve. Anything you lose comes round in another form. Rumi

Idea Transcript


Django Documentation Release 2.1.dev20171226153947

Django Software Foundation

December 26, 2017

Contents

1

2

3

Django documentation 1.1 Getting help . . . . . . . . . . . . . 1.2 How the documentation is organized 1.3 First steps . . . . . . . . . . . . . . . 1.4 The model layer . . . . . . . . . . . 1.5 The view layer . . . . . . . . . . . . 1.6 The template layer . . . . . . . . . . 1.7 Forms . . . . . . . . . . . . . . . . . 1.8 The development process . . . . . . 1.9 The admin . . . . . . . . . . . . . . 1.10 Security . . . . . . . . . . . . . . . . 1.11 Internationalization and localization . 1.12 Performance and optimization . . . . 1.13 Geographic framework . . . . . . . . 1.14 Common Web application tools . . . 1.15 Other core functionalities . . . . . . 1.16 The Django open-source project . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 4 5

Getting started 2.1 Django at a glance . . . . . . . . . . . . . . . 2.2 Quick install guide . . . . . . . . . . . . . . . 2.3 Writing your first Django app, part 1 . . . . . 2.4 Writing your first Django app, part 2 . . . . . 2.5 Writing your first Django app, part 3 . . . . . 2.6 Writing your first Django app, part 4 . . . . . 2.7 Writing your first Django app, part 5 . . . . . 2.8 Writing your first Django app, part 6 . . . . . 2.9 Writing your first Django app, part 7 . . . . . 2.10 Advanced tutorial: How to write reusable apps 2.11 What to read next . . . . . . . . . . . . . . . . 2.12 Writing your first patch for Django . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

7 7 12 13 18 31 37 41 51 53 62 67 70

Using Django 3.1 How to install Django . 3.2 Models and images/sitelogo.png" %}" alt="Logo" /> {% block content %}{% endblock %}

2.1. Django at a glance

11

Django Documentation, Release 2.1.dev20171226153947

Simplistically, it defines the look-and-feel of the site (with the site’s logo), and provides “holes” for child templates to fill. This makes a site redesign as easy as changing a single file – the base template. It also lets you create multiple versions of a site, with different base templates, while reusing child templates. Django’s creators have used this technique to create strikingly different mobile versions of sites – simply by creating a new base template. Note that you don’t have to use Django’s template system if you prefer another system. While Django’s template system is particularly well-integrated with Django’s model layer, nothing forces you to use it. For that matter, you don’t have to use Django’s , pub_date=timezone.now()) # Save the object into the >{{ question.question_text }} {% endfor %} {% else %}

No polls are available.

{% endif %}

Now let’s update our index view in polls/views.py to use the template: polls/views.py from django.http import HttpResponse from django.template import loader from .models import Question

2.5. Writing your first Django app, part 3

33

Django Documentation, Release 2.1.dev20171226153947

def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request))

That code loads the template called polls/index.html and passes it a context. The context is a dictionary mapping template variable names to Python objects. Load the page by pointing your browser at “/polls/”, and you should see a bulleted-list containing the “What’s up” question from Tutorial 2. The link points to the question’s detail page. A shortcut: render() It’s a very common idiom to load a template, fill a context and return an HttpResponse object with the result of the rendered template. Django provides a shortcut. Here’s the full index() view, rewritten: polls/views.py from django.shortcuts import render from .models import Question

def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context)

Note that once we’ve done this in all these views, we no longer need to import loader and HttpResponse (you’ll want to keep HttpResponse if you still have the stub methods for detail, results, and vote). The render() function takes the request object as its first argument, a template name as its second argument and a dictionary as its optional third argument. It returns an HttpResponse object of the given template rendered with the given context.

2.5.4 Raising a 404 error Now, let’s tackle the question detail view – the page that displays the question text for a given poll. Here’s the view: polls/views.py from django.http import Http404 from django.shortcuts import render from .models import Question # ... def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question})

The new concept here: The view raises the Http404 exception if a question with the requested ID doesn’t exist. We’ll discuss what you could put in that polls/detail.html template a bit later, but if you’d like to quickly get the above example working, a file containing just: 34

Chapter 2. Getting started

Django Documentation, Release 2.1.dev20171226153947

polls/templates/polls/detail.html {{ question }}

will get you started for now. A shortcut: get_object_or_404() It’s a very common idiom to use get() and raise Http404 if the object doesn’t exist. Django provides a shortcut. Here’s the detail() view, rewritten: polls/views.py from django.shortcuts import get_object_or_404, render from .models import Question # ... def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question})

The get_object_or_404() function takes a Django model as its first argument and an arbitrary number of keyword arguments, which it passes to the get() function of the model’s manager. It raises Http404 if the object doesn’t exist. Philosophy Why do we use a helper function get_object_or_404() instead of automatically catching the ObjectDoesNotExist exceptions at a higher level, or having the model API raise Http404 instead of ObjectDoesNotExist? Because that would couple the model layer to the view layer. One of the foremost design goals of Django is to maintain loose coupling. Some controlled coupling is introduced in the django.shortcuts module. There’s also a get_list_or_404() function, which works just as get_object_or_404() – except using filter() instead of get(). It raises Http404 if the list is empty.

2.5.5 Use the template system Back to the detail() view for our poll application. Given the context variable question, here’s what the polls/ detail.html template might look like: polls/templates/polls/detail.html {{ question.question_text }}
    {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }}
  • {% endfor %}


The template system uses dot-lookup syntax to access variable attributes. In the example of {{ question. question_text }}, first Django does a dictionary lookup on the object question. Failing that, it tries an attribute lookup – which works, in this case. If attribute lookup had failed, it would’ve tried a list-index lookup. Method-calling happens in the {% for %} loop: question.choice_set.all is interpreted as the Python code question.choice_set.all(), which returns an iterable of Choice objects and is suitable for use in the {% for %} tag.

2.5. Writing your first Django app, part 3

35

Django Documentation, Release 2.1.dev20171226153947

See the template guide for more about templates.

2.5.6 Removing hardcoded URLs in templates Remember, when we wrote the link to a question in the polls/index.html template, the link was partially hardcoded like this:
  • {{ question.question_text }}


  • The problem with this hardcoded, tightly-coupled approach is that it becomes challenging to change URLs on projects with a lot of templates. However, since you defined the name argument in the path() functions in the polls.urls module, you can remove a reliance on specific URL paths defined in your url configurations by using the {% url %} template tag:
  • {{ question.question_text }}


  • The way this works is by looking up the URL definition as specified in the polls.urls module. You can see exactly where the URL name of ‘detail’ is defined below: ... # the 'name' value as called by the {% url %} template tag path('/', views.detail, name='detail'), ...

    If you want to change the URL of the polls detail view to something else, perhaps to something like polls/ specifics/12/ instead of doing it in the template (or templates) you would change it in polls/urls.py: ... # added the word 'specifics' path('specifics//', views.detail, name='detail'), ...

    2.5.7 Namespacing URL names The tutorial project has just one app, polls. In real Django projects, there might be five, ten, twenty apps or more. How does Django differentiate the URL names between them? For example, the polls app has a detail view, and so might an app on the same project that is for a blog. How does one make it so that Django knows which app view to create for a url when using the {% url %} template tag? The answer is to add namespaces to your URLconf. In the polls/urls.py file, go ahead and add an app_name to set the application namespace: polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('/', views.detail, name='detail'), path('/results/', views.results, name='results'), path('/vote/', views.vote, name='vote'), ]

    36

    Chapter 2. Getting started

    Django Documentation, Release 2.1.dev20171226153947

    Now change your polls/index.html template from: polls/templates/polls/index.html
  • {{ question.question_text }}


  • to point at the namespaced detail view: polls/templates/polls/index.html
  • {{ question.question_text }}


  • When you’re comfortable with writing views, read part 4 of this tutorial to learn about simple form processing and generic views.

    2.6 Writing your first Django app, part 4 This tutorial begins where Tutorial 3 left off. We’re continuing the Web-poll application and will focus on simple form processing and cutting down our code.

    2.6.1 Write a simple form Let’s update our poll detail template (“polls/detail.html”) from the last tutorial, so that the template contains an HTML element: polls/templates/polls/detail.html {{ question.question_text }} {% if error_message %}

    {{ error_message }}

    {% endif %} {% csrf_token %} {% for choice in question.choice_set.all %} {{ choice.choice_text }}
    {% endfor %}

    A quick rundown: • The above template displays a radio button for each question choice. The value of each radio button is the associated question choice’s ID. The name of each radio button is "choice". That means, when somebody selects one of the radio buttons and submits the form, it’ll send the POST . Using method="post" (as opposed to method="get") is very important, because the act of submitting this form will alter . This tip isn’t specific to Django; it’s just good Web development practice. • forloop.counter indicates how many times the for tag has gone through its loop • Since we’re creating a POST form (which can have the effect of modifying >Vote again?

    Now, go to /polls/1/ in your browser and vote in the question. You should see a results page that gets updated each time you vote. If you submit the form without having chosen a choice, you should see the error message. Note: The code for our vote() view does have a small problem. It first gets the selected_choice object from the >What's up?\n ˓→ \n\n' >>> response.context['latest_question_list'] >> MyPerson.objects.get(first_name="foobar")

    You could also use a proxy model to define a different default ordering on a model. You might not always want to order the Person model, but regularly order by the last_name attribute when you use the proxy. This is easy: class OrderedPerson(Person): class Meta: ordering = ["last_name"] proxy = True

    100

    Chapter 3. Using Django

    Django Documentation, Release 2.1.dev20171226153947

    Now normal Person queries will be unordered and OrderedPerson queries will be ordered by last_name. Proxy models inherit Meta attributes in the same way as regular models. QuerySets still return the model that was requested There is no way to have Django return, say, a MyPerson object whenever you query for Person objects. A queryset for Person objects will return those types of objects. The whole point of proxy objects is that code relying on the original Person will use those and your own code can use the extensions you included (that no other code is relying on anyway). It is not a way to replace the Person (or any other) model everywhere with something of your own creation. Base class restrictions A proxy model must inherit from exactly one non-abstract model class. You can’t inherit from multiple non-abstract models as the proxy model doesn’t provide any connection between the rows in the different ) entry.blog = cheese_blog entry.save()

    Updating a ManyToManyField works a little differently – use the add() method on the field to add a record to the relation. This example adds the Author instance joe to the entry object: >>> from blog.models import Author >>> joe = Author.objects.create(name="Joe") >>> entry.authors.add(joe)

    To add multiple records to a ManyToManyField in one go, include multiple arguments in the call to add(), like this: >>> john = Author.objects.create(name="John") >>> paul = Author.objects.create(name="Paul") >>> george = Author.objects.create(name="George")

    3.2. Models and ) >>> entry.authors.add(john, paul, george, ringo)

    Django will complain if you try to assign or add an object of the wrong type. Retrieving objects To retrieve objects from your ) >>> q2 = q1.exclude(pub_date__gte=datetime.date.today()) >>> q3 = q1.filter(pub_date__gte=datetime.date.today())

    These three QuerySets are separate. The first is a base QuerySet containing all entries that contain a headline starting with “What”. The second is a subset of the first, with an additional criteria that excludes records whose pub_date is today or in the future. The third is a subset of the first, with an additional criteria that selects only the records whose pub_date is today or in the future. The initial QuerySet (q1) is unaffected by the refinement process. QuerySets are lazy QuerySets are lazy – the act of creating a QuerySet doesn’t involve any ) q = q.filter(pub_date__lte=datetime.date.today()) q = q.exclude(body_text__icontains="food") print(q)

    3.2. Models and )

    Would generate SQL along these lines: SELECT ... WHERE headline = 'Cat bites dog';

    If you don’t provide a lookup type – that is, if your keyword argument doesn’t contain a double underscore – the lookup type is assumed to be exact. For example, the following two statements are equivalent:

    3.2. Models and )

    Would match a Blog titled "Beatles Blog", "beatles blog", or even "BeAtlES blOG". contains Case-sensitive containment test. For example: Entry.objects.get(headline__contains='Lennon')

    Roughly translates to this SQL: SELECT ... WHERE headline LIKE '%Lennon%';

    Note this will match the headline 'Today Lennon honored' but not 'today lennon honored'. There’s also a case-insensitive version, icontains. startswith, endswith Starts-with and ends-with search, respectively. There are also case-insensitive versions called istartswith and iendswith. Again, this only scratches the surface. A complete reference can be found in the field lookup reference. Lookups that span relationships Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want. This example retrieves all Entry objects with a Blog whose name is 'Beatles Blog': >>> Entry.objects.filter(blog__name='Beatles Blog')

    This spanning can be as deep as you’d like. It works backwards, too. To refer to a “reverse” relationship, just use the lowercase name of the model. This example retrieves all Blog objects which have at least one Entry whose headline contains 'Lennon': >>> Blog.objects.filter(entry__headline__contains='Lennon')

    If you are filtering across multiple relationships and one of the intermediate models doesn’t have a value that meets the filter condition, Django will treat it as if there is an empty (all values are NULL), but valid, object there. All this means is that no error will be raised. For example, in this filter: Blog.objects.filter(entry__authors__name='Lennon')

    (if there was a related Author model), if there was no author associated with an entry, it would be treated as if there was also no name attached, rather than raising an error because of the missing author. Usually this is exactly what you want to have happen. The only case where it might be confusing is if you are using isnull. Thus: Blog.objects.filter(entry__authors__name__isnull=True)

    110

    Chapter 3. Using Django

    Django Documentation, Release 2.1.dev20171226153947

    will return Blog objects that have an empty name on the author and also those which have an empty author on the entry. If you don’t want those latter objects, you could write: Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)

    Spanning multi-valued relationships When you are filtering an object based on a ManyToManyField or a reverse ForeignKey, there are two different sorts of filter you may be interested in. Consider the Blog/Entry relationship (Blog to Entry is a one-to-many relation). We might be interested in finding blogs that have an entry which has both “Lennon” in the headline and was published in 2008. Or we might want to find blogs that have an entry with “Lennon” in the headline as well as an entry that was published in 2008. Since there are multiple entries associated with a single Blog, both of these queries are possible and make sense in some situations. The same type of situation arises with a ManyToManyField. For example, if an Entry has a ManyToManyField called tags, we might want to find entries linked to tags called “music” and “bands” or we might want an entry that contains a tag with a name of “music” and a status of “public”. To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call. That may sound a bit confusing, so hopefully an example will clarify. To select all blogs that contain entries with both “Lennon” in the headline and that were published in 2008 (the same entry satisfying both conditions), we would write: Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)

    To select all blogs that contain an entry with “Lennon” in the headline as well as an entry that was published in 2008, we would write: Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__ ˓→year=2008)

    Suppose there is only one blog that had both entries containing “Lennon” and entries from 2008, but that none of the entries from 2008 contained “Lennon”. The first query would not return any blogs, but the second query would return that one blog. In the second example, the first filter restricts the queryset to all those blogs linked to entries with “Lennon” in the headline. The second filter restricts the set of blogs further to those that are also linked to entries that were published in 2008. The entries selected by the second filter may or may not be the same as the entries in the first filter. We are filtering the Blog items with each filter statement, not the Entry items. Note: The behavior of filter() for queries that span multi-value relationships, as described above, is not implemented equivalently for exclude(). Instead, the conditions in a single exclude() call will not necessarily refer to the same item. For example, the following query would exclude blogs that contain both entries with “Lennon” in the headline and entries published in 2008: Blog.objects.exclude( entry__headline__contains='Lennon', entry__pub_date__year=2008, )

    3.2. Models and ).annotate(num_authors=Count('authors ˓→'))

    When used with an aggregate() clause, a filter has the effect of constraining the objects over which the aggregate is calculated. For example, you can generate the average price of all books with a title that starts with “Django” using the query: >>> Book.objects.filter(name__startswith="Django").aggregate(Avg('price'))

    3.2. Models and ) , db_tablespace="indexes") class Meta: db_tablespace = "tables" indexes = [models.Index(fields=['shortcut'], db_tablespace='other_indexes')]

    In this example, the tables generated by the TablespaceExample model (i.e. the model table and the manyto-many table) would be stored in the tables tablespace. The index for the name field and the indexes on the many-to-many table would be stored in the indexes tablespace. The )

    because id is indexed by the )

    First of all, headline is not indexed, which will make the underlying ) >>> Article.objects.filter(publications__title__startswith="Science").distinct()

    The count() function respects distinct() as well:

    3.2. Models and ).count() 2 >>> Article.objects.filter(publications__title__startswith="Science").distinct(). ˓→count() 1 >>> Article.objects.filter(publications__in=[1,2]).distinct() >>> Article.objects.filter(publications__in=[p1,p2]).distinct()

    Reverse m2m queries are supported (i.e., starting at the table that doesn’t have a ManyToManyField): >>> Publication.objects.filter(id=1) >>> Publication.objects.filter(pk=1) >>> Publication.objects.filter(article__headline__startswith="NASA") >>> Publication.objects.filter(article__id=1) >>> Publication.objects.filter(article__pk=1) >>> Publication.objects.filter(article=1) >>> Publication.objects.filter(article=a1) >>> Publication.objects.filter(article__in=[1,2]).distinct() >>> Publication.objects.filter(article__in=[a1,a2]).distinct()

    Excluding a related item works as you would expect, too (although the SQL involved is a little complex): >>> Article.objects.exclude(publications=p2)

    If we delete a Publication, its Articles won’t be able to access it: >>> p1.delete() >>> Publication.objects.all() >>> a1 = Article.objects.get(pk=1) >>> a1.publications.all()

    If we delete an Article, its Publications won’t be able to access it:

    176

    Chapter 3. Using Django

    Django Documentation, Release 2.1.dev20171226153947

    >>> a2.delete() >>> Article.objects.all() >>> p2.article_set.all()

    Adding via the ‘other’ end of an m2m: >>> a4 = Article(headline='NASA finds intelligent life on Earth') >>> a4.save() >>> p2.article_set.add(a4) >>> p2.article_set.all() >>> a4.publications.all()

    Adding via the other end using keywords: >>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders') >>> p2.article_set.all() >>> a5 = p2.article_set.all()[1] >>> a5.publications.all()

    Removing Publication from an Article: >>> a4.publications.remove(p2) >>> p2.article_set.all() >>> a4.publications.all()

    And from the other end: >>> p2.article_set.remove(a5) >>> p2.article_set.all() >>> a5.publications.all()

    Relation sets can be set: >>> a4.publications.all() >>> a4.publications.set([p3]) >>> a4.publications.all()

    Relation sets can be cleared: >>> p2.article_set.clear() >>> p2.article_set.all()

    And you can clear from the other end:

    3.2. Models and , pub_date=date(2005, 7, 27), ˓→reporter=r) >>> a.save() >>> a.reporter.id 1 >>> a.reporter

    Note that you must save an object before it can be assigned to a foreign key relationship. For example, creating an Article with unsaved Reporter raises ValueError: >>> r3 = Reporter(first_name='John', last_name='Smith', email='[email protected]') >>> Article.objects.create(headline="This is a test", pub_date=date(2005, 7, 27), ˓→reporter=r3) Traceback (most recent call last): ... ValueError: save() prohibited to prevent , pub_ ˓→date=date(2005, 7, 29)) >>> new_article

    3.2. Models and , pub_date=date(2006, 1, 17)) >>> r.article_set.add(new_article2) >>> new_article2.reporter >>> new_article2.reporter.id 1 >>> r.article_set.all() , ]>

    Add the same article to a different article set - check that it moves: >>> r2.article_set.add(new_article2) >>> new_article2.reporter.id 2 >>> new_article2.reporter

    Adding an object of the wrong type raises TypeError: >>> r.article_set.add(r2) Traceback (most recent call last): ... TypeError: 'Article' instance expected >>> r.article_set.all() ]> >>> r.article_set.count() 2 >>> r2.article_set.count() 1

    Note that in the last example the article has moved from John to Paul. Related managers support field lookups as well. The API automatically follows relationships as far as you need. Use double underscores to separate relationships. This works as many levels deep as you want. There’s no limit. For example: >>> r.article_set.filter(headline__startswith='This') # Find all Articles for any Reporter whose first name is "John". >>> Article.objects.filter(reporter__first_name='John') , ]>

    Query twice over the related field. This translates to an AND condition in the WHERE clause: >>> Article.objects.filter(reporter__first_name='John', reporter__last_name='Smith') , ]> >>> Article.objects.filter(reporter=1) , ]> >>> Article.objects.filter(reporter__in=[1,2]).distinct() , ]> >>> Article.objects.filter(reporter__in=[r,r2]).distinct() , ]>

    You can also use a queryset instead of a literal list of instances: >>> Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')). ˓→distinct() {% csrf_token %} {{ form.as_p }}

    CreateView class django.views.generic.edit.CreateView A view that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object. Ancestors (MRO) This view inherits methods and attributes from the following views: • django.views.generic.detail.SingleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.edit.BaseCreateView • django.views.generic.edit.ModelFormMixin • django.views.generic.edit.FormMixin • django.views.generic.detail.SingleObjectMixin • django.views.generic.edit.ProcessFormView • django.views.generic.base.View Attributes template_name_suffix The CreateView page displayed to a GET request uses a template_name_suffix of '_form'. For example, changing this attribute to '_create_form' for a view creating objects for the example Author model would cause the default template_name to be 'myapp/author_create_form. html'. object When using CreateView you have access to self.object, which is the object being created. If the object hasn’t been created yet, the value will be None. Example myapp/views.py: from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name']

    Example myapp/author_form.html: {% csrf_token %} {{ form.as_p }}

    6.3. Built-in class-based views API

    649

    Django Documentation, Release 2.1.dev20171226153947

    UpdateView class django.views.generic.edit.UpdateView A view that displays a form for editing an existing object, redisplaying the form with validation errors (if there are any) and saving changes to the object. This uses a form automatically generated from the object’s model class (unless a form class is manually specified). Ancestors (MRO) This view inherits methods and attributes from the following views: • django.views.generic.detail.SingleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.edit.BaseUpdateView • django.views.generic.edit.ModelFormMixin • django.views.generic.edit.FormMixin • django.views.generic.detail.SingleObjectMixin • django.views.generic.edit.ProcessFormView • django.views.generic.base.View Attributes template_name_suffix The UpdateView page displayed to a GET request uses a template_name_suffix of '_form'. For example, changing this attribute to '_update_form' for a view updating objects for the example Author model would cause the default template_name to be 'myapp/author_update_form. html'. object When using UpdateView you have access to self.object, which is the object being updated. Example myapp/views.py: from django.views.generic.edit import UpdateView from myapp.models import Author class AuthorUpdate(UpdateView): model = Author fields = ['name'] template_name_suffix = '_update_form'

    Example myapp/author_update_form.html: {% csrf_token %} {{ form.as_p }}

    DeleteView class django.views.generic.edit.DeleteView A view that displays a confirmation page and deletes an existing object. The given object will only be deleted if the request method is POST. If this view is fetched via GET, it will display a confirmation page that should contain a form that POSTs to the same URL.

    650

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Ancestors (MRO) This view inherits methods and attributes from the following views: • django.views.generic.detail.SingleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.edit.BaseDeleteView • django.views.generic.edit.DeletionMixin • django.views.generic.detail.BaseDetailView • django.views.generic.detail.SingleObjectMixin • django.views.generic.base.View Attributes template_name_suffix The DeleteView page displayed to a GET request uses a template_name_suffix of '_confirm_delete'. For example, changing this attribute to '_check_delete' for a view deleting objects for the example Author model would cause the default template_name to be 'myapp/ author_check_delete.html'. Example myapp/views.py: from django.views.generic.edit import DeleteView from django.urls import reverse_lazy from myapp.models import Author class AuthorDelete(DeleteView): model = Author success_url = reverse_lazy('author-list')

    Example myapp/author_confirm_delete.html: {% csrf_token %}

    Are you sure you want to delete "{{ object }}"?



    6.3.4 Generic date views Date-based generic views, provided in django.views.generic.dates, are views for displaying drilldown pages for date-based ), name="article_archive"), ]

    Example myapp/article_archive.html:
      {% for article in latest %}
    • {{ article.pub_date }}: {{ article.title }}
    • {% endfor %}


    652

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    This will output all articles. YearArchiveView class YearArchiveView A yearly archive page showing all available months in a given year. Objects with a date in the future are not displayed unless you set allow_future to True. Ancestors (MRO) • django.views.generic.list.MultipleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.dates.BaseYearArchiveView • django.views.generic.dates.YearMixin • django.views.generic.dates.BaseDateListView • django.views.generic.list.MultipleObjectMixin • django.views.generic.dates.DateMixin • django.views.generic.base.View make_object_list A boolean specifying whether to retrieve the full list of objects for this year and pass those to the template. If True, the list of objects will be made available to the context. If False, the None queryset will be used as the object list. By default, this is False. get_make_object_list() Determine if an object list will be returned as part of the context. Returns make_object_list by default. Context In addition to the context provided by django.views.generic.list.MultipleObjectMixin (via django.views.generic.dates.BaseDateListView), the template’s context will be: • date_list: A QuerySet object containing all months that have objects available according to queryset, represented as datetime.datetime objects, in ascending order. • year: A date object representing the given year. • next_year: A date object representing the first day of the next year, according to allow_empty and allow_future. • previous_year: A date object representing the first day of the previous year, according to allow_empty and allow_future. Notes • Uses a default template_name_suffix of _archive_year. Example myapp/views.py: from django.views.generic.dates import YearArchiveView from myapp.models import Article class ArticleYearArchiveView(YearArchiveView): queryset = Article.objects.all() date_field = "pub_date"

    6.3. Built-in class-based views API

    653

    Django Documentation, Release 2.1.dev20171226153947

    make_object_list = True allow_future = True

    Example myapp/urls.py: from django.urls import path from myapp.views import ArticleYearArchiveView urlpatterns = [ path('/', ArticleYearArchiveView.as_view(), name="article_year_archive"), ]

    Example myapp/article_archive_year.html:
      {% for date in date_list %}
    • {{ date|date }}
    • {% endfor %}
    All Articles for {{ year|date:"Y" }} {% for obj in object_list %}

    {{ obj.title }} - {{ obj.pub_date|date:"F j, Y" }}

    {% endfor %}

    MonthArchiveView class MonthArchiveView A monthly archive page showing all objects in a given month. Objects with a date in the future are not displayed unless you set allow_future to True. Ancestors (MRO) • django.views.generic.list.MultipleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.dates.BaseMonthArchiveView • django.views.generic.dates.YearMixin • django.views.generic.dates.MonthMixin • django.views.generic.dates.BaseDateListView • django.views.generic.list.MultipleObjectMixin • django.views.generic.dates.DateMixin • django.views.generic.base.View Context

    654

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be: • date_list: A QuerySet object containing all days that have objects available in the given month, according to queryset, represented as datetime.datetime objects, in ascending order. • month: A date object representing the given month. • next_month: A date object representing the first day of the next month, according to allow_empty and allow_future. • previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future. Notes • Uses a default template_name_suffix of _archive_month. Example myapp/views.py: from django.views.generic.dates import MonthArchiveView from myapp.models import Article class ArticleMonthArchiveView(MonthArchiveView): queryset = Article.objects.all() date_field = "pub_date" allow_future = True

    Example myapp/urls.py: from django.urls import path from myapp.views import ArticleMonthArchiveView urlpatterns = [ # Example: /2012/08/ path('//', ArticleMonthArchiveView.as_view(month_format='%m'), name="archive_month_numeric"), # Example: /2012/aug/ path('//', ArticleMonthArchiveView.as_view(), name="archive_month"), ]

    Example myapp/article_archive_month.html:
      {% for article in object_list %}
    • {{ article.pub_date|date:"F j, Y" }}: {{ article.title }}
    • {% endfor %}

    {% if previous_month %} Previous Month: {{ previous_month|date:"F Y" }} {% endif %} {% if next_month %} Next Month: {{ next_month|date:"F Y" }}

    6.3. Built-in class-based views API

    655

    Django Documentation, Release 2.1.dev20171226153947

    {% endif %}



    WeekArchiveView class WeekArchiveView A weekly archive page showing all objects in a given week. Objects with a date in the future are not displayed unless you set allow_future to True. Ancestors (MRO) • django.views.generic.list.MultipleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.dates.BaseWeekArchiveView • django.views.generic.dates.YearMixin • django.views.generic.dates.WeekMixin • django.views.generic.dates.BaseDateListView • django.views.generic.list.MultipleObjectMixin • django.views.generic.dates.DateMixin • django.views.generic.base.View Context In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be: • week: A date object representing the first day of the given week. • next_week: A date object representing the first day of the next week, according to allow_empty and allow_future. • previous_week: A date object representing the first day of the previous week, according to allow_empty and allow_future. Notes • Uses a default template_name_suffix of _archive_week. • The week_format attribute is a strptime() format string used to parse the week number. The following values are supported: – '%U': Based on the United States week system where the week begins on Sunday. This is the default value. – '%W': Similar to '%U', except it assumes that the week begins on Monday. This is not the same as the ISO 8601 week number. Example myapp/views.py: from django.views.generic.dates import WeekArchiveView from myapp.models import Article class ArticleWeekArchiveView(WeekArchiveView): queryset = Article.objects.all()

    656

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    date_field = "pub_date" week_format = "%W" allow_future = True

    Example myapp/urls.py: from django.urls import path from myapp.views import ArticleWeekArchiveView urlpatterns = [ # Example: /2012/week/23/ path('/week//', ArticleWeekArchiveView.as_view(), name="archive_week"), ]

    Example myapp/article_archive_week.html: Week {{ week|date:'W' }}
      {% for article in object_list %}
    • {{ article.pub_date|date:"F j, Y" }}: {{ article.title }}
    • {% endfor %}

    {% if previous_week %} Previous Week: {{ previous_week|date:"W" }} of year {{ previous_week|date: ˓→"Y" }} {% endif %} {% if previous_week and next_week %}--{% endif %} {% if next_week %} Next week: {{ next_week|date:"W" }} of year {{ next_week|date:"Y" }} {% endif %}



    In this example, you are outputting the week number. Keep in mind that week numbers computed by the date template filter with the 'W' format character are not always the same as those computed by strftime() and strptime() with the '%W' format string. For year 2015, for example, week numbers output by date are higher by one compared to those output by strftime(). There isn’t an equivalent for the '%U' strftime() format string in date. Therefore, you should avoid using date to generate URLs for WeekArchiveView. DayArchiveView class DayArchiveView A day archive page showing all objects in a given day. Days in the future throw a 404 error, regardless of whether any objects exist for future days, unless you set allow_future to True. Ancestors (MRO) • django.views.generic.list.MultipleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.dates.BaseDayArchiveView 6.3. Built-in class-based views API

    657

    Django Documentation, Release 2.1.dev20171226153947

    • django.views.generic.dates.YearMixin • django.views.generic.dates.MonthMixin • django.views.generic.dates.DayMixin • django.views.generic.dates.BaseDateListView • django.views.generic.list.MultipleObjectMixin • django.views.generic.dates.DateMixin • django.views.generic.base.View Context In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be: • day: A date object representing the given day. • next_day: A date object representing the next day, according to allow_empty and allow_future. • previous_day: A date object representing the previous day, according to allow_empty and allow_future. • next_month: A date object representing the first day of the next month, according to allow_empty and allow_future. • previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future. Notes • Uses a default template_name_suffix of _archive_day. Example myapp/views.py: from django.views.generic.dates import DayArchiveView from myapp.models import Article class ArticleDayArchiveView(DayArchiveView): queryset = Article.objects.all() date_field = "pub_date" allow_future = True

    Example myapp/urls.py: from django.urls import path from myapp.views import ArticleDayArchiveView urlpatterns = [ # Example: /2012/nov/10/ path('///', ArticleDayArchiveView.as_view(), name="archive_day"), ]

    Example myapp/article_archive_day.html:

    658

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    {{ day }}
      {% for article in object_list %}
    • {{ article.pub_date|date:"F j, Y" }}: {{ article.title }}
    • {% endfor %}

    {% if previous_day %} Previous Day: {{ previous_day }} {% endif %} {% if previous_day and next_day %}--{% endif %} {% if next_day %} Next Day: {{ next_day }} {% endif %}



    TodayArchiveView class TodayArchiveView A day archive page showing all objects for today. This is exactly the same as django.views.generic. dates.DayArchiveView, except today’s date is used instead of the year/month/day arguments. Ancestors (MRO) • django.views.generic.list.MultipleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.dates.BaseTodayArchiveView • django.views.generic.dates.BaseDayArchiveView • django.views.generic.dates.YearMixin • django.views.generic.dates.MonthMixin • django.views.generic.dates.DayMixin • django.views.generic.dates.BaseDateListView • django.views.generic.list.MultipleObjectMixin • django.views.generic.dates.DateMixin • django.views.generic.base.View Notes • Uses a default template_name_suffix of _archive_today. Example myapp/views.py: from django.views.generic.dates import TodayArchiveView from myapp.models import Article class ArticleTodayArchiveView(TodayArchiveView): queryset = Article.objects.all() date_field = "pub_date" allow_future = True

    6.3. Built-in class-based views API

    659

    Django Documentation, Release 2.1.dev20171226153947

    Example myapp/urls.py: from django.urls import path from myapp.views import ArticleTodayArchiveView urlpatterns = [ path('today/', ArticleTodayArchiveView.as_view(), name="archive_today"), ]

    Where is the example template for TodayArchiveView? This view uses by default the same template as the DayArchiveView, which is in the previous example. If you need a different template, set the template_name attribute to be the name of the new template.

    DateDetailView class DateDetailView A page representing an individual object. If the object has a date value in the future, the view will throw a 404 error by default, unless you set allow_future to True. Ancestors (MRO) • django.views.generic.detail.SingleObjectTemplateResponseMixin • django.views.generic.base.TemplateResponseMixin • django.views.generic.dates.BaseDateDetailView • django.views.generic.dates.YearMixin • django.views.generic.dates.MonthMixin • django.views.generic.dates.DayMixin • django.views.generic.dates.DateMixin • django.views.generic.detail.BaseDetailView • django.views.generic.detail.SingleObjectMixin • django.views.generic.base.View Context • Includes the single object associated with the model specified in the DateDetailView. Notes • Uses a default template_name_suffix of _detail. Example myapp/urls.py: from django.urls import path from django.views.generic.dates import DateDetailView urlpatterns = [

    660

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    path('////', DateDetailView.as_view(model=Article, date_field="pub_date"), name="archive_date_detail"), ]

    Example myapp/article_detail.html: {{ object.title }}

    Note: All of the generic views listed above have matching Base views that only differ in that they do not include the MultipleObjectTemplateResponseMixin (for the archive views) or SingleObjectTemplateResponseMixin (for the DateDetailView): class BaseArchiveIndexView class BaseYearArchiveView class BaseMonthArchiveView class BaseWeekArchiveView class BaseDayArchiveView class BaseTodayArchiveView class BaseDateDetailView

    6.3.5 Class-based views mixins Class-based views API reference. For introductory material, see Using mixins with class-based views. Simple mixins ContextMixin class django.views.generic.base.ContextMixin Attributes extra_context A dictionary to include in the context. This is a convenient way of specifying some simple context in as_view(). Example usage: from django.views.generic import TemplateView TemplateView.as_view(extra_context={'title': 'Custom Title'})

    Methods get_context_ to redirect to a URL composed out of the slug field on a model. get_form_class() Retrieve the form class to instantiate. If form_class is provided, that class will be used. Otherwise, a ModelForm will be instantiated using the model associated with the queryset, or with the model, depending on which attribute is provided. get_form_kwargs() Add the current instance (self.object) to the standard get_form_kwargs(). get_success_url() Determine the URL to redirect to when the form is successfully validated. Returns django.views. generic.edit.ModelFormMixin.success_url if it is provided; otherwise, attempts to use the get_absolute_url() of the object. form_valid(form) Saves the form instance, sets the current object for the view, and redirects to get_success_url(). form_invalid() Renders a response, providing the invalid form as context. ProcessFormView class django.views.generic.edit.ProcessFormView A mixin that provides basic HTTP GET and POST workflow.

    6.3. Built-in class-based views API

    669

    Django Documentation, Release 2.1.dev20171226153947

    Note: This is named ‘ProcessFormView’ and inherits directly from django.views.generic.base. View, but breaks if used independently, so it is more of a mixin. Extends • django.views.generic.base.View Methods and Attributes get(request, *args, **kwargs) Renders a response using a context created with get_context_ to redirect to a URL composed out of the parent_id field on a model. get_success_url() Returns the url to redirect to when the nominated object has been successfully deleted. success_url by default.

    Returns

    Date-based mixins

    Note: All the date formatting attributes in these mixins use strftime() format characters. Do not try to use the format characters from the now template tag as they are not compatible.

    YearMixin class YearMixin A mixin that can be used to retrieve and provide parsing information for a year component of a date. Methods and Attributes year_format The strftime() format to use when parsing the year. By default, this is '%Y'. year Optional The value for the year, as a string. By default, set to None, which means the year will be determined using other means. 670

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    get_year_format() Returns the strftime() format to use when parsing the year. Returns year_format by default. get_year() Returns the year for which this view will display ) serializers.serialize("json", queryset, stream=response) return response

    Generally, something like the above isn’t considered a great idea. Most of the time, the best practice will be to return an HttpResponseRedirect and redirect the user to a view you’ve written, passing the list of selected objects in the GET query string. This allows you to provide complex interaction logic on the intermediary pages. For example, if you wanted to provide a more complete export function, you’d want to let the user choose a format, and possibly a list of fields to include in the export. The best thing to do would be to write a small action that simply redirects to your custom export view: from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.http import HttpResponseRedirect def export_selected_objects(modeladmin, request, queryset): selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) ct = ContentType.objects.get_for_model(queryset.model) return HttpResponseRedirect("/export/?ct=%s&ids=%s" % (ct.pk, ",".join(selected)))

    As you can see, the action is the simple part; all the complex logic would belong in your export view. This would need to deal with objects of any type, hence the business with the ContentType. Writing this view is left as an exercise to the reader. Making actions available site-wide AdminSite.add_action(action, name=None) Some actions are best if they’re made available to any object in the admin site – the export action defined above would be a good candidate. You can make an action globally available using AdminSite.add_action(). For example: from django.contrib import admin admin.site.add_action(export_selected_objects)

    This makes the export_selected_objects action globally available as an action named “export_selected_objects”. You can explicitly give the action a name – good if you later want to programmatically remove the action – by passing a second argument to AdminSite.add_action(): admin.site.add_action(export_selected_objects, 'export_selected')

    6.5. contrib packages

    697

    Django Documentation, Release 2.1.dev20171226153947

    Disabling actions Sometimes you need to disable certain actions – especially those registered site-wide – for particular objects. There’s a few ways you can disable actions: Disabling a site-wide action AdminSite.disable_action(name) If you need to disable a site-wide action you can call AdminSite.disable_action(). For example, you can use this method to remove the built-in “delete selected objects” action: admin.site.disable_action('delete_selected')

    Once you’ve done the above, that action will no longer be available site-wide. If, however, you need to re-enable a globally-disabled action for one particular model, simply list it explicitly in your ModelAdmin.actions list: # Globally disable delete selected admin.site.disable_action('delete_selected') # This ModelAdmin will not have delete_selected available class SomeModelAdmin(admin.ModelAdmin): actions = ['some_other_action'] ... # This one will class AnotherModelAdmin(admin.ModelAdmin): actions = ['delete_selected', 'a_third_action'] ...

    Disabling all actions for a particular ModelAdmin If you want no bulk actions available for a given ModelAdmin, simply set ModelAdmin.actions to None: class MyModelAdmin(admin.ModelAdmin): actions = None

    This tells the ModelAdmin to not display or allow any actions, including any site-wide actions. Conditionally enabling or disabling actions ModelAdmin.get_actions(request) Finally, you can conditionally enable or disable actions on a per-request (and hence per-user basis) by overriding ModelAdmin.get_actions(). This returns a dictionary of actions allowed. The keys are action names, and the values are (function, name, short_description) tuples. Most of the time you’ll use this method to conditionally remove actions from the list gathered by the superclass. For example, if I only wanted users whose names begin with ‘J’ to be able to delete objects in bulk, I could do the following:

    698

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    class MyModelAdmin(admin.ModelAdmin): ... def get_actions(self, request): actions = super().get_actions(request) if request.user.username[0].upper() != 'J': if 'delete_selected' in actions: del actions['delete_selected'] return actions

    The Django admin documentation generator Django’s admindocs app pulls documentation from the docstrings of models, views, template tags, and template filters for any app in INSTALLED_APPS and makes that documentation available from the Django admin. Overview To activate the admindocs, you will need to do the following: • Add django.contrib.admindocs to your INSTALLED_APPS. • Add path('admin/doc/', include('django.contrib.admindocs.urls')) to your urlpatterns. Make sure it’s included before the 'admin/' entry, so that requests to /admin/doc/ don’t get handled by the latter entry. • Install the docutils Python module (http://docutils.sf.net/). • Optional: Using the admindocs bookmarklets requires django.contrib.admindocs.middleware. XViewMiddleware to be installed. Once those steps are complete, you can start browsing the documentation by going to your admin interface and clicking the “Documentation” link in the upper right of the page. Documentation helpers The following special markup can be used in your docstrings to easily create hyperlinks to other components: Django Component Models Views Template tags Template filters Templates

    reStructuredText roles :model:`app_label.ModelName` :view:`app_label.view_name` :tag:`tagname` :filter:`filtername` :template:`path/to/template.html`

    Model reference The models section of the admindocs page describes each model in the system along with all the fields and methods available on it. Relationships to other models appear as hyperlinks. Descriptions are pulled from help_text attributes on fields or from docstrings on model methods. A model with useful documentation might look like this:

    6.5. contrib packages

    699

    Django Documentation, Release 2.1.dev20171226153947

    class BlogEntry(models.Model): """ Stores a single blog entry, related to :model:`blog.Blog` and :model:`auth.User`. """ slug = models.SlugField(help_text="A short label, generally used in URLs.") author = models.ForeignKey( User, models.SET_NULL, blank=True, null=True, ) blog = models.ForeignKey(Blog, models.CASCADE) ... def publish(self): """Makes the blog entry live on the site.""" ...

    View reference Each URL in your site has a separate entry in the admindocs page, and clicking on a given URL will show you the corresponding view. Helpful things you can document in your view function docstrings include: • A short description of what the view does. • The context, or a list of variables available in the view’s template. • The name of the template or templates that are used for that view. For example: from django.shortcuts import render from myapp.models import MyModel def my_view(request, slug): """ Display an individual :model:`myapp.MyModel`. **Context** ``mymodel`` An instance of :model:`myapp.MyModel`. **Template:** :template:`myapp/my_template.html` """ context = {'mymodel': MyModel.objects.get(slug=slug)} return render(request, 'myapp/my_template.html', context)

    Template tags and filters reference The tags and filters admindocs sections describe all the tags and filters that come with Django (in fact, the built-in tag reference and built-in filter reference documentation come directly from those pages). Any tags or filters that you create or are added by a third-party app will show up in these sections as well. 700

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Template reference While admindocs does not include a place to document templates by themselves, if you use the :template:`path/to/template.html` syntax in a docstring the resulting page will verify the path of that template with Django’s template loaders. This can be a handy way to check if the specified template exists and to show where on the filesystem that template is stored. Included Bookmarklets One bookmarklet is available from the admindocs page: Documentation for this page Jumps you from any page to the documentation for the view that generates that page. Using this bookmarklet requires that XViewMiddleware is installed and that you are logged into the Django admin as a User with is_staff set to True. JavaScript customizations in the admin Inline form events You may want to execute some JavaScript when an inline form is added or removed in the admin change form. The formset:added and formset:removed jQuery events allow this. The event handler is passed three arguments: • event is the jQuery event. • $row is the newly added (or removed) row. • formsetName is the formset the row belongs to. The event is fired using the django.jQuery namespace. In your custom change_form.html template, extend the admin_change_form_document_ready block and add the event listener code: {% extends 'admin/change_form.html' %} {% load static %} {% block admin_change_form_document_ready %} {{ block.super }} {% endblock %} app/static/app/formset_handlers.js (function($) { $(document).on('formset:added', function(event, $row, formsetName) { if (formsetName == 'author_set') { // Do something } }); $(document).on('formset:removed', function(event, $row, formsetName) { // Row removed }); })(django.jQuery);

    Two points to keep in mind:

    6.5. contrib packages

    701

    Django Documentation, Release 2.1.dev20171226153947

    • The JavaScript code must go in a template block if you are inheriting admin/change_form.html or it won’t be rendered in the final HTML. • {{ block.super }} is added because Django’s admin_change_form_document_ready block contains JavaScript code to handle various operations in the change form and we need that to be rendered too. Sometimes you’ll need to work with jQuery plugins that are not registered in the django.jQuery namespace. To do that, simply change how the code listens for events. Instead of wrapping the listener in the django.jQuery namespace, just listen to the event triggered from there. For example: {% extends 'admin/change_form.html' %} {% load static %} {% block admin_change_form_document_ready %} {{ block.super }}

    Setting the token on the AJAX request Finally, you’ll have to actually set the header on your AJAX request, while protecting the CSRF token from being sent to other domains using settings.crossDomain in jQuery 1.5.1 and newer: function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } });

    If you’re using AngularJS 1.1.3 and newer, it’s sufficient to configure the $http provider with the cookie and header names: $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

    Using CSRF in Jinja2 templates Django’s Jinja2 template backend adds {{ csrf_input }} to the context of all templates which is equivalent to {% csrf_token %} in the Django template language. For example: {{ csrf_input }}

    958

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    The decorator method Rather than adding CsrfViewMiddleware as a blanket protection, you can use the csrf_protect decorator, which has exactly the same functionality, on particular views that need the protection. It must be used both on views that insert the CSRF token in the output, and on those that accept the POST form content="no-referrer"> tag or include the Referrer-Policy: no-referrer header. Due to the CSRF protection’s strict referer checking on HTTPS requests, those techniques cause a CSRF failure on requests with ‘unsafe’ methods. Instead, use alternatives like " for links to third-party sites.

    6.6.4 Caching If the csrf_token template tag is used by a template (or the get_token function is called some other way), CsrfViewMiddleware will add a cookie and a Vary: Cookie header to the response. This means that the middleware will play well with the cache middleware if it is used as instructed (UpdateCacheMiddleware goes before all other middleware). However, if you use cache decorators on individual views, the CSRF middleware will not yet have been able to set the Vary header or the CSRF cookie, and the response will be cached without either one. In this case, on any views that will require a CSRF token to be inserted you should use the django.views.decorators.csrf. csrf_protect() decorator first:

    960

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect @cache_page(60 * 15) @csrf_protect def my_view(request): ...

    If you are using class-based views, you can refer to Decorating class-based views.

    6.6.5 Testing The CsrfViewMiddleware will usually be a big hindrance to testing view functions, due to the need for the CSRF token which must be sent with every POST request. For this reason, Django’s HTTP client for tests has been modified to set a flag on requests which relaxes the middleware and the csrf_protect decorator so that they no longer rejects requests. In every other respect (e.g. sending cookies etc.), they behave the same. If, for some reason, you want the test client to perform CSRF checks, you can create an instance of the test client that enforces CSRF checks: >>> from django.test import Client >>> csrf_client = Client(enforce_csrf_checks=True)

    6.6.6 Limitations Subdomains within a site will be able to set cookies on the client for the whole domain. By setting the cookie and using a corresponding token, subdomains will be able to circumvent the CSRF protection. The only way to avoid this is to ensure that subdomains are controlled by trusted users (or, are at least unable to set cookies). Note that even without CSRF, there are other vulnerabilities, such as session fixation, that make giving subdomains to untrusted parties a bad idea, and these vulnerabilities cannot easily be fixed with current browsers.

    6.6.7 Edge cases Certain views can have unusual requirements that mean they don’t fit the normal pattern envisaged here. A number of utilities can be useful in these situations. The scenarios they might be needed in are described in the following section. Utilities The examples below assume you are using function-based views. If you are working with class-based views, you can refer to Decorating class-based views. csrf_exempt(view) This decorator marks a view as being exempt from the protection ensured by the middleware. Example: from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def my_view(request): return HttpResponse('Hello world')

    6.6. Cross Site Request Forgery protection

    961

    Django Documentation, Release 2.1.dev20171226153947

    requires_csrf_token(view) Normally the csrf_token template tag will not work if CsrfViewMiddleware.process_view or an equivalent like csrf_protect has not run. The view decorator requires_csrf_token can be used to ensure the template tag does work. This decorator works similarly to csrf_protect, but never rejects an incoming request. Example: from django.views.decorators.csrf import requires_csrf_token from django.shortcuts import render @requires_csrf_token def my_view(request): c = {} # ... return render(request, "a_template.html", c)

    ensure_csrf_cookie(view) This decorator forces a view to send the CSRF cookie. Scenarios CSRF protection should be disabled for just a few views Most views requires CSRF protection, but a few do not. Solution: rather than disabling the middleware and applying csrf_protect to all the views that need it, enable the middleware and use csrf_exempt(). CsrfViewMiddleware.process_view not used There are cases when CsrfViewMiddleware.process_view may not have run before your view is run - 404 and 500 handlers, for example - but you still need the CSRF token in a form. Solution: use requires_csrf_token() Unprotected view needs the CSRF token There may be some views that are unprotected and have been exempted by csrf_exempt, but still need to include the CSRF token. Solution: use csrf_exempt() followed by requires_csrf_token(). (i.e. requires_csrf_token should be the innermost decorator). View needs protection for one path A view needs CSRF protection under one set of conditions only, and mustn’t have it for the rest of the time. Solution: use csrf_exempt() for the whole view function, and csrf_protect() for the path within it that needs protection. Example:

    962

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    from django.views.decorators.csrf import csrf_exempt, csrf_protect @csrf_exempt def my_view(request): @csrf_protect def protected_path(request): do_something() if some_condition(): return protected_path(request) else: do_something_else()

    Page uses AJAX without any HTML form A page makes a POST request via AJAX, and the page does not have an HTML form with a csrf_token that would cause the required CSRF cookie to be sent. Solution: use ensure_csrf_cookie() on the view that sends the page.

    6.6.8 Contrib and reusable apps Because it is possible for the developer to turn off the CsrfViewMiddleware, all relevant views in contrib apps use the csrf_protect decorator to ensure the security of these applications against CSRF. It is recommended that the developers of other reusable apps that want the same guarantees also use the csrf_protect decorator on their views.

    6.6.9 Settings A number of settings can be used to control Django’s CSRF behavior: • CSRF_COOKIE_AGE • CSRF_COOKIE_DOMAIN • CSRF_COOKIE_HTTPONLY • CSRF_COOKIE_NAME • CSRF_COOKIE_PATH • CSRF_COOKIE_SECURE • CSRF_FAILURE_VIEW • CSRF_HEADER_NAME • CSRF_TRUSTED_ORIGINS • CSRF_USE_SESSIONS

    6.6. Cross Site Request Forgery protection

    963

    Django Documentation, Release 2.1.dev20171226153947

    6.6.10 Frequently Asked Questions Is posting an arbitrary CSRF token pair (cookie and POST ) will match a name of "Aabb".

    That is a filter such as

    2. For strings containing characters outside the ASCII range, all exact string matches are performed case-sensitively, even when the case-insensitive options are passed into the query. So the iexact filter will behave exactly the same as the exact filter in these cases. Some possible workarounds for this are documented at sqlite.org, but they aren’t utilized by the default SQLite backend in Django, as incorporating them would be fairly difficult to do robustly. Thus, Django exposes the default SQLite behavior and you should be aware of this when doing case-insensitive or substring filtering.

    972

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947



    You can also pass code in on standard input to execute it. For example: $ > > >

    django-admin shell ' >>> f.fields['name'].label = "Username" >>> f.as_table().split('\n')[0] 'Username: ˓→'

    Beware not to alter the base_fields attribute because this modification will influence all subsequent ContactForm instances within the same Python process: >>> f.base_fields['name'].label = "Username" >>> another_f = CommentForm(auto_id=False) >>> another_f.as_table().split('\n')[0] 'Username:'

    1018

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Accessing “clean” >Subject: Message: Sender: Cc myself:

    If the form is bound to >, the >, then that HTML will include checked if appropriate: >>> >Subject: Message: Sender: Cc myself:

    1020

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    This default output is a two-column HTML table, with a for each field. Notice the following: • For flexibility, the output does not include the and
    tags, nor does it include the and tags or an tag. It’s your job to do that. • Each field type has a default HTML representation. CharField is represented by an and EmailField by an . BooleanField is represented by an . Note these are merely sensible defaults; you can specify which HTML to use for a given field by using widgets, which we’ll explain shortly. • The HTML name for each tag is taken directly from its attribute name in the ContactForm class. • The text label for each field – e.g. 'Subject:', 'Message:' and 'Cc myself:' is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Again, note these are merely sensible defaults; you can also specify labels manually. • Each text label is surrounded in an HTML tag, which points to the appropriate form field via its id. Its id, in turn, is generated by prepending 'id_' to the field name. The id attributes and tags are included in the output by default, to follow best practices, but you can change that behavior. • The output uses HTML5 syntax, targeting . For example, it uses boolean attributes such as checked rather than the XHTML style of checked='checked'. Although output is the default output style when you print a form, other output styles are available. Each style is available as a method on a form object, and each rendering method returns a string. as_p() Form.as_p() as_p() renders the form as a series of

    tags, with each

    containing one field: >>> f = ContactForm() >>> f.as_p() '

    Subject:

    \n

    Message:

    \n

    Sender:

    \n

    Cc myself:

    ' >>> print(f.as_p())

    Subject:

    Message:

    Sender:

    Cc myself:



    as_ul() Form.as_ul() as_ul() renders the form as a series of
  • tags, with each
  • containing one field. It does not include the
      or
    , so that you can specify any HTML attributes on the
      for flexibility:

      6.12. Forms

      1021

      Django Documentation, Release 2.1.dev20171226153947

      >>> f = ContactForm() >>> f.as_ul() '
    • Subject:
    • \n
    • Message:
    • \n
    • ˓→Sender:
    • \n
    • Cc myself:
    • ' >>> print(f.as_ul())
    • Subject:
    • Message:
    • Sender:
    • Cc myself:


    • as_table() Form.as_table() Finally, as_table() outputs the form as an HTML
  • . This is exactly the same as print. In fact, when you print a form object, it calls its as_table() method behind the scenes: >>> f = ContactForm() >>> f.as_table() '\n\n\n' >>> print(f)

    Styling required or erroneous form rows Form.error_css_class Form.required_css_class It’s pretty common to style form rows and fields that are required or have errors. For example, you might want to present required form rows in bold and highlight errors in red. The Form class has a couple of hooks you can use to add class attributes to required rows or to rows with errors: simply set the Form.error_css_class and/or Form.required_css_class attributes:

    1022

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    from django import forms class ContactForm(forms.Form): error_css_class = 'error' required_css_class = 'required' # ... and the rest of your fields here

    Once you’ve done that, rows will be given "error" and/or "required" classes, as needed. The HTML will look something like: >>> f = ContactForm(> >>> print(f.as_ul())
  • Subject:
  • Message:
  • Sender:
  • Cc myself:
  • >>> print(f.as_p())

    6.12. Forms

    1023

    Django Documentation, Release 2.1.dev20171226153947

    Subject:

    Message:

    Sender:

    Cc myself:



    If auto_id is set to True, then the form output will include tags and will simply use the field name as its id for each form field: >>> f = ContactForm(auto_id=True) >>> print(f.as_table()) >>> print(f.as_ul())
  • Subject:
  • Message:
  • Sender:
  • Cc myself:
  • >>> print(f.as_p())

    Subject:

    Message:

    Sender:

    Cc myself:



    If auto_id is set to a string containing the format character '%s', then the form output will include tags, and will generate id attributes based on the format string. For example, for a format string 'field_%s', a field named subject will get the id value 'field_subject'. Continuing our example: >>> f = ContactForm(auto_id='id_for_%s') >>> print(f.as_table()) >>> print(f.as_ul())
  • Subject:
  • Message:
  • Sender:


  • 1024

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

  • Cc myself:
  • >>> print(f.as_p())

    Subject:

    Message:

    Sender:

    Cc myself:



    If auto_id is set to any other true value – such as a string that doesn’t include %s – then the library will act as if auto_id is True. By default, auto_id is set to the string 'id_%s'. Form.label_suffix A translatable string (defaults to a colon (:) in English) that will be appended after any label name when a form is rendered. It’s possible to customize that character, or omit it entirely, using the label_suffix parameter: >>> f = ContactForm(auto_id='id_for_%s', label_suffix='') >>> print(f.as_ul())
  • Subject
  • Message
  • Sender
  • Cc myself
  • >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->') >>> print(f.as_ul())
  • Subject ->
  • Message ->
  • Sender ->
  • Cc myself ->


  • Note that the label suffix is added only if the last character of the label isn’t a punctuation character (in English, those are ., !, ? or :). Fields can also define their own label_suffix. This will take precedence over Form.label_suffix. The suffix can also be overridden at runtime using the label_suffix parameter to label_tag(). Form.use_required_attribute When set to True (the default), required form fields will have the required HTML attribute. Formsets instantiate forms with use_required_attribute=False to avoid incorrect browser validation when adding and deleting forms from a formset.

    6.12. Forms

    1025

    Django Documentation, Release 2.1.dev20171226153947

    Configuring the rendering of a form’s widgets Form.default_renderer Specifies the renderer to use for the form. Defaults to None which means to use the default renderer specified by the FORM_RENDERER setting. You can set this as a class attribute when declaring your form or use the renderer argument to Form. __init__(). For example: from django import forms class MyForm(forms.Form): default_renderer = MyRenderer()

    or: form = MyForm(renderer=MyRenderer())

    Notes on field ordering In the as_p(), as_ul() and as_table() shortcuts, the fields are displayed in the order in which you define them in your form class. For example, in the ContactForm example, the fields are defined in the order subject, message, sender, cc_myself. To reorder the HTML output, just change the order in which those fields are listed in the class. There are several other ways to customize the order: Form.field_order By default Form.field_order=None, which retains the order in which you define the fields in your form class. If field_order is a list of field names, the fields are ordered as specified by the list and remaining fields are appended according to the default order. Unknown field names in the list are ignored. This makes it possible to disable a field in a subclass by setting it to None without having to redefine ordering. You can also use the Form.field_order argument to a Form to override the field order. If a Form defines field_order and you include field_order when instantiating the Form, then the latter field_order will have precedence. Form.order_fields(field_order) You may rearrange the fields any time using order_fields() with a list of field names as in field_order. How errors are displayed If you render a bound Form object, the act of rendering will automatically run the form’s validation if it hasn’t already happened, and the HTML output will include the validation errors as a
      near the field. The particular positioning of the error messages depends on the output method you’re using: >>> >
    • This field is required.
    ˓→

    1026

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    ˓→ >>> print(f.as_ul())
    • This field is required.
    Subject:
  • Message:
    • Enter a valid email address.
    Sender:
  • Cc myself:
  • >>> print(f.as_p())

    • This field is required.

    Subject:

    Message:

    • Enter a valid email address.

    Sender: ˓→

    Cc myself:



    Customizing the error list format By default, forms use django.forms.utils.ErrorList to format validation errors. If you’d like to use an alternate class for displaying errors, you can pass that in at construction time: >>> from django.forms.utils import ErrorList >>> class DivErrorList(ErrorList): ... def __str__(self): ... return self.as_divs() ... def as_divs(self): ... if not self: return '' ... return '%s' % ''.join(['%s ˓→' % e for e in self]) >>> f = ContactForm(>This field is required.

    Subject:

    Message:

    Enter a valid email address.

    Sender: ˓→

    Cc myself:



    More granular output The as_p(), as_ul(), and as_table() methods are simply shortcuts – they’re not the only way a form object can be displayed. class BoundField Used to display HTML or access attributes for a single field of a Form instance. The __str__() method of this object displays the HTML for this field.

    6.12. Forms

    1027

    Django Documentation, Release 2.1.dev20171226153947

    To retrieve a single BoundField, use dictionary lookup syntax on your form using the field’s name as the key: >>> form = ContactForm() >>> print(form['subject'])

    To retrieve all BoundField objects, iterate the form: >>> form = ContactForm() >>> for boundfield in form: print(boundfield)

    The field-specific output honors the form object’s auto_id setting: >>> f = ContactForm(auto_id=False) >>> print(f['message']) >>> f = ContactForm(auto_id='id_%s') >>> print(f['message'])

    Attributes of BoundField BoundField.auto_id The HTML ID attribute for this BoundField. Returns an empty string if Form.auto_id is False. BoundField.> when printed: >>> name="message" required /> >>> f['message'].errors ['This field is required.'] >>> print(f['message'].errors)
    • This field is required.
    >>> f['subject'].errors [] >>> print(f['subject'].errors) >>> str(f['subject'].errors) ''

    1028

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    BoundField.field The form Field instance from the form class that this BoundField wraps. BoundField.form The Form instance this BoundField is bound to. BoundField.help_text The help_text of the field. BoundField.html_name The name that will be used in the widget’s HTML name attribute. It takes the form prefix into account. BoundField.id_for_label Use this property to render the ID of this field. For example, if you are manually constructing a in your template (despite the fact that label_tag() will do this for you): ...{{ my_field }}

    By default, this will be the field’s name prefixed by id_ (“id_my_field” for the example above). You may modify the ID by setting attrs on the field’s widget. For example, declaring a field like this: my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))

    and using the template above, would render something like: ...

    BoundField.is_hidden Returns True if this BoundField’s widget is hidden. BoundField.label The label of the field. This is used in label_tag(). BoundField.name The name of this field in the form: >>> f = ContactForm() >>> print(f['subject'].name) subject >>> print(f['message'].name) message

    Methods of BoundField BoundField.as_hidden(attrs=None, **kwargs) Returns a string of HTML for representing this as an . **kwargs are passed to as_widget(). This method is primarily used internally. You should use a widget instead. BoundField.as_widget(widget=None, attrs=None, only_initial=False) Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field’s default widget will be used. only_initial is used by Django internals and should not be set explicitly.

    6.12. Forms

    1029

    Django Documentation, Release 2.1.dev20171226153947

    BoundField.css_classes() When you use Django’s rendering shortcuts, CSS classes are used to indicate required form fields or fields that contain errors. If you’re manually rendering a form, you can access these CSS classes using the css_classes method: >>> f = ContactForm(>Message:

    You can provide the contents parameter which will replace the auto-generated label tag. An attrs dictionary may contain additional attributes for the tag. The HTML that’s generated includes the form’s label_suffix (a colon, by default) or, if set, the current field’s label_suffix. The optional label_suffix parameter allows you to override any previously set suffix. For example, you can use an empty string to hide the label on selected fields. If you need to do this in a template, you could write a custom filter to allow passing parameters to label_tag. BoundField.value() Use this method to render the raw value of this field as it would be rendered by a Widget: >>> initial = {'subject': 'welcome'} >>> unbound_form = ContactForm(initial=initial) >>> bound_form = ContactForm( method="post" action="/foo/">

    Secondly, when you use the form, you need to bind the file method="post" action="/foo/"> {% else %} {% endif %} {{ form }}

    Subclassing forms If you have multiple Form classes that share fields, you can use subclassing to remove redundancy. When you subclass a custom Form class, the resulting subclass will include all fields of the parent class(es), followed by the fields you define in the subclass. In this example, ContactFormWithPriority contains all the fields from ContactForm, plus an additional field, priority. The ContactForm fields are ordered first: >>> class ContactFormWithPriority(ContactForm): ... priority = forms.CharField() >>> f = ContactFormWithPriority(auto_id=False) >>> print(f.as_ul())
  • Subject:
  • Message:
  • Sender:
  • Cc myself:
  • Priority:


  • It’s possible to subclass multiple forms, treating forms as mixins. In this example, BeatleForm subclasses both PersonForm and InstrumentForm (in that order), and its field list includes the fields from the parent classes: >>> from django import forms >>> class PersonForm(forms.Form): ... first_name = forms.CharField() ... last_name = forms.CharField() >>> class InstrumentForm(forms.Form): ... instrument = forms.CharField() >>> class BeatleForm(InstrumentForm, PersonForm): ... haircut_type = forms.CharField() >>> b = BeatleForm(auto_id=False) >>> print(b.as_ul())
  • First name:
  • Last name:


  • 1032

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

  • Instrument:
  • Haircut type:


  • It’s possible to declaratively remove a Field inherited from a parent class by setting the name of the field to None on the subclass. For example: >>> from django import forms >>> class ParentForm(forms.Form): ... name = forms.CharField() ... age = forms.IntegerField() >>> class ChildForm(ParentForm): ... name = None >>> list(ChildForm().fields) ['age']

    Prefixes for forms Form.prefix You can put several Django forms inside one tag. To give each Form its own namespace, use the prefix keyword argument: >>> mother = PersonForm(prefix="mother") >>> father = PersonForm(prefix="father") >>> print(mother.as_ul())
  • First name:
  • Last name:
  • >>> print(father.as_ul())
  • First name:
  • Last name:


  • The prefix can also be specified on the form class: >>> class PersonForm(forms.Form): ... ... ... prefix = 'person'

    6.12.2 Form fields class Field(**kwargs) When you create a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. Field.clean(value) Although the primary way you’ll use Field classes is in Form classes, you can also instantiate them and use them directly to get a better idea of how they work. Each Field instance has a clean() method, which takes a single argument and either raises a django.forms.ValidationError exception or returns the clean value:

    6.12. Forms

    1033

    Django Documentation, Release 2.1.dev20171226153947

    >>> from django import forms >>> f = forms.EmailField() >>> f.clean('[email protected]') '[email protected]' >>> f.clean('invalid email address') Traceback (most recent call last): ... ValidationError: ['Enter a valid email address.']

    Core field arguments Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: required Field.required By default, each Field class assumes the value is required, so if you pass an empty value – either None or the empty string ("") – then clean() will raise a ValidationError exception: >>> from django import forms >>> f = forms.CharField() >>> f.clean('foo') 'foo' >>> f.clean('') Traceback (most recent call last): ... ValidationError: ['This field is required.'] >>> f.clean(None) Traceback (most recent call last): ... ValidationError: ['This field is required.'] >>> f.clean(' ') ' ' >>> f.clean(0) '0' >>> f.clean(True) 'True' >>> f.clean(False) 'False'

    To specify that a field is not required, pass required=False to the Field constructor: >>> f = forms.CharField(required=False) >>> f.clean('foo') 'foo' >>> f.clean('') '' >>> f.clean(None) '' >>> f.clean(0) '0' >>> f.clean(True) 'True'

    1034

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    >>> f.clean(False) 'False'

    If a Field has required=False and you pass clean() an empty value, then clean() will return a normalized empty value rather than raising ValidationError. For CharField, this will be an empty string. For other Field classes, it might be None. (This varies from field to field.) Widgets of required form fields have the required HTML attribute. Set the Form.use_required_attribute attribute to False to disable it. The required attribute isn’t included on forms of formsets because the browser validation may not be correct when adding and deleting formsets. label Field.label The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form. As explained in “Outputting forms as HTML” above, the default label for a Field is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Specify label if that default behavior doesn’t result in an adequate label. Here’s a full example Form that implements label for two of its fields. We’ve specified auto_id=False to simplify the output: >>> from django import forms >>> class CommentForm(forms.Form): ... name = forms.CharField(label='Your name') ... url = forms.URLField(label='Your website', required=False) ... comment = forms.CharField() >>> f = CommentForm(auto_id=False) >>> print(f)

    label_suffix Field.label_suffix The label_suffix argument lets you override the form’s label_suffix on a per-field basis: >>> class ContactForm(forms.Form): ... age = forms.IntegerField() ... nationality = forms.CharField() ... captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =') >>> f = ContactForm(label_suffix='?') >>> print(f.as_p())

    Age?

    Nationality?

    2 + 2 =



    6.12. Forms

    1035

    Django Documentation, Release 2.1.dev20171226153947

    initial Field.initial The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form. To specify dynamic initial name="name" value="Your name" required />

    You may be thinking, why not just pass a dictionary of the initial values as name="name" value="Your name" required />

    This is why initial values are only displayed for unbound forms. For bound forms, the HTML output will use the bound name="day" value="12/23/2008" required />

    The callable will be evaluated only when the unbound form is displayed, not when it is defined. widget Field.widget The widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information. help_text Field.help_text The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods (e.g., as_ul()). Like the model field’s help_text, this value isn’t HTML-escaped in automatically-generated forms. Here’s a full example Form that implements help_text for two of its fields. We’ve specified auto_id=False to simplify the output: >>> from django import forms >>> class HelpTextContactForm(forms.Form): ... subject = forms.CharField(max_length=100, help_text='100 characters max.') ... message = forms.CharField() ... sender = forms.EmailField(help_text='A valid email address, please.') ... cc_myself = forms.BooleanField(required=False) >>> f = HelpTextContactForm(auto_id=False) >>> print(f.as_table()) >>> print(f.as_ul()))
  • Subject: 100 characters max.
  • Message:
  • Sender: A valid email address, ˓→please.
  • Cc myself:
  • >>> print(f.as_p())

    Subject: 100 characters max.

    Message:



    6.12. Forms

    1037

    Django Documentation, Release 2.1.dev20171226153947

    Sender: A valid email address, ˓→please.

    Cc myself:



    error_messages Field.error_messages The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message: >>> from django import forms >>> generic = forms.CharField() >>> generic.clean('') Traceback (most recent call last): ... ValidationError: ['This field is required.']

    And here is a custom error message: >>> name = forms.CharField(error_messages={'required': 'Please enter your name'}) >>> name.clean('') Traceback (most recent call last): ... ValidationError: ['Please enter your name']

    In the built-in Field classes section below, each Field defines the error message keys it uses. validators Field.validators The validators argument lets you provide a list of validation functions for this field. See the validators documentation for more information. localize Field.localize The localize argument enables the localization of form ) # No empty label field2 = forms.ModelChoiceField(queryset=..., empty_label=None)

    Note that if a ModelChoiceField is required and has a default initial value, no empty choice is created (regardless of the value of empty_label). to_field_name This optional argument is used to specify the field to use as the value of the choices in the field’s widget. Be sure it’s a unique field for the model, otherwise the selected value could match more than one object. By default it is set to None, in which case the primary key of each object will be used. For example: # No custom to_field_name field1 = forms.ModelChoiceField(queryset=...)

    would yield:

    6.12. Forms

    1051

    Django Documentation, Release 2.1.dev20171226153947

    Object1 Object2 ...

    and: # to_field_name provided field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")

    would yield: Object1 Object2 ...

    The __str__() method of the model will be called to generate string representations of the objects for use in the field’s choices. To provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object and should return a string suitable for representing it. For example: from django.forms import ModelChoiceField class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "My Object #%i" % obj.id

    ModelMultipleChoiceField class ModelMultipleChoiceField(**kwargs) • Default widget: SelectMultiple • Empty value: An empty QuerySet (self.queryset.none()) • Normalizes to: A QuerySet of model instances. • Validates that every id in the given list of values exists in the queryset. • Error message keys: required, list, invalid_choice, invalid_pk_value The invalid_choice message may contain %(value)s and the invalid_pk_value message may contain %(pk)s, which will be substituted by the appropriate values. Allows the selection of one or more model objects, suitable for representing a many-to-many relation. As with ModelChoiceField, you can use label_from_instance to customize the object representations. A single argument is required: queryset Same as ModelChoiceField.queryset. Takes one optional argument: to_field_name Same as ModelChoiceField.to_field_name.

    1052

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Creating custom fields If the built-in Field classes don’t meet your needs, you can easily create custom Field classes. To do this, just create a subclass of django.forms.Field. Its only requirements are that it implement a clean() method and that its __init__() method accept the core arguments mentioned above (required, label, initial, widget, help_text). You can also customize how a field will be accessed by overriding get_bound_field().

    6.12.3 Model Form Functions Model Form API reference. For introductory material about model forms, see the Creating forms from models topic guide. modelform_factory modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None) Returns a ModelForm class for the given model. You can optionally pass a form argument to use as a starting point for constructing the ModelForm. fields is an optional list of field names. If provided, only the named fields will be included in the returned fields. exclude is an optional list of field names. If provided, the named fields will be excluded from the returned fields, even if they are listed in the fields argument. formfield_callback is a callable that takes a model field and returns a form field. widgets is a dictionary of model field names mapped to a widget. localized_fields is a list of names of fields which should be localized. labels is a dictionary of model field names mapped to a label. help_texts is a dictionary of model field names mapped to a help text. error_messages is a dictionary of model field names mapped to a dictionary of error messages. field_classes is a dictionary of model field names mapped to a form field class. See ModelForm factory function for example usage. You must provide the list of fields explicitly, either via keyword arguments fields or exclude, or the corresponding attributes on the form’s inner Meta class. See Selecting the fields to use for more information. Omitting any definition of the fields to use will result in an ImproperlyConfigured exception. modelformset_factory modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None) Returns a FormSet class for the given model class.

    6.12. Forms

    1053

    Django Documentation, Release 2.1.dev20171226153947

    Arguments model, form, fields, exclude, formfield_callback, widgets, localized_fields, labels, help_texts, error_messages, and field_classes are all passed through to modelform_factory(). Arguments formset, extra, max_num, can_order, can_delete and validate_max are passed through to formset_factory(). See formsets for details. See Model formsets for example usage. inlineformset_factory inlineformset_factory(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None) Returns an InlineFormSet using modelformset_factory() with defaults formset=BaseInlineFormSet, can_delete=True, and extra=3.

    of

    If your model has more than one ForeignKey to the parent_model, you must specify a fk_name. See Inline formsets for example usage.

    6.12.4 Formset Functions Formset API reference. For introductory material about formsets, see the Formsets topic guide. formset_factory formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None, validate_max=False, min_num=None, validate_min=False) Returns a FormSet class for the given form class. See formsets for example usage.

    6.12.5 The form rendering API Django’s form widgets are rendered using Django’s template engines system. The form rendering process can be customized at several levels: • Widgets can specify custom template names. • Forms and widgets can specify custom renderer classes. • A widget’s template can be overridden by a project. (Reusable applications typically shouldn’t override built-in templates because they might conflict with a project’s custom templates.) The low-level render API The rendering of form templates is controlled by a customizable renderer class. A custom renderer can be specified by updating the FORM_RENDERER setting. It defaults to 'django.forms.renderers.DjangoTemplates'. You can also provide a custom renderer by setting the Form.default_renderer attribute or by using the renderer argument of Widget.render(). 1054

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Use one of the built-in template form renderers or implement your own. Custom renderers must implement a render(template_name, context, request=None) method. It should return a rendered templates (as a string) or raise TemplateDoesNotExist. Built-in-template form renderers DjangoTemplates class DjangoTemplates This renderer uses a standalone DjangoTemplates engine (unconnected to what you might have configured in the TEMPLATES setting). It loads templates first from the built-in form templates directory in django/forms/ templates and then from the installed apps’ templates directories using the app_directories loader. If you want to render templates with customizations from your TEMPLATES setting, such as context processors for example, use the TemplatesSetting renderer. Jinja2 class Jinja2 This renderer is the same as the DjangoTemplates renderer except that it uses a Jinja2 backend. Templates for the built-in widgets are located in django/forms/jinja2 and installed apps can provide templates in a jinja2 directory. To use this backend, all the widgets in your project and its third-party apps must have Jinja2 templates. Unless you provide your own Jinja2 templates for widgets that don’t have any, you can’t use this renderer. For example, django. contrib.admin doesn’t include Jinja2 templates for its widgets due to their usage of Django template tags. TemplatesSetting class TemplatesSetting This renderer gives you complete control of how widget templates are sourced. It uses get_template() to find widget templates based on what’s configured in the TEMPLATES setting. Using this renderer along with the built-in widget templates requires either: • 'django.forms' in INSTALLED_APPS and at least one engine with APP_DIRS=True. • Adding the built-in widgets templates directory in DIRS of one of your template engines. To generate that path: import django django.__path__[0] + '/forms/templates'

    # or '/forms/jinja2'

    Using this renderer requires you to make sure the form templates your project needs can be located. Context available in widget templates Widget templates receive a context from Widget.get_context(). By default, widgets receive a single value in the context, widget. This is a dictionary that contains values like: • name • value

    6.12. Forms

    1055

    Django Documentation, Release 2.1.dev20171226153947

    • attrs • is_hidden • template_name Some widgets add further information to the context. For instance, all widgets that subclass Input defines widget['type'] and MultiWidget defines widget['subwidgets'] for looping purposes. Overriding built-in widget templates Each widget has a template_name attribute with a value such as input.html. Built-in widget templates are stored in the django/forms/widgets path. You can provide a custom template for input.html by defining django/forms/widgets/input.html, for example. See Built-in widgets for the name of each widget’s template. If you use the TemplatesSetting renderer, overriding widget templates works the same as overriding any other template in your project. You can’t override built-in widget templates using the other built-in renderers.

    6.12.6 Widgets A widget is Django’s representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of name="name" required />

    On a real Web page, you probably don’t want every widget to look the same. You might want a larger input element for the comment, and you might want the ‘name’ widget to have some special CSS class. It is also possible to specify the ‘type’ attribute to take advantage of the new HTML5 input types. To do this, you use the Widget.attrs argument when creating the widget: class CommentForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'})) url = forms.URLField() comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))

    Django will then include the extra attributes in the rendered output: >>> f = CommentForm(auto_id=False) >>> f.as_table() ˓→ ˓→

    You can also set the HTML id using attrs. See BoundField.id_for_label for an example. Styling widget classes With widgets, it is possible to add assets (css and javascript) and more deeply customize their appearance and behavior. In a nutshell, you will need to subclass the widget and either define a “Media” inner class or create a “media” property. These methods involve somewhat advanced Python programming and are described in detail in the Form Assets topic guide.

    1058

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Base widget classes Base widget classes Widget and MultiWidget are subclassed by all the built-in widgets and may serve as a foundation for custom widgets. Widget class Widget(attrs=None) This abstract class cannot be rendered, but provides the basic attribute attrs. You may also implement or override the render() method on custom widgets. attrs A dictionary containing HTML attributes to be set on the rendered widget. >>> from django import forms >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',}) >>> name.render('name', 'A name') ''

    If you assign a value of True or False to an attribute, it will be rendered as an HTML5 boolean attribute: >>> name = forms.TextInput(attrs={'required': True}) >>> name.render('name', 'A name') '' >>> >>> name = forms.TextInput(attrs={'required': False}) >>> name.render('name', 'A name') ''

    supports_microseconds An attribute that defaults to True. If set to False, the microseconds part of datetime and time values will be set to 0. format_value(value) Cleans and returns a value for use in the widget template. value isn’t guaranteed to be valid input, therefore subclass implementations should program defensively. get_context(name, value, attrs) Returns a dictionary of values to use when rendering the widget template. By default, the dictionary contains a single key, 'widget', which is a dictionary representation of the widget containing the following keys: • 'name': The name of the field from the name argument. • 'is_hidden': A boolean indicating whether or not this widget is hidden. • 'required': A boolean indicating whether or not the field for this widget is required. • 'value': The value as returned by format_value(). • 'attrs': HTML attributes to be set on the rendered widget. The combination of the attrs attribute and the attrs argument. • 'template_name': The value of self.template_name. Widget subclasses can provide custom context values by overriding this method.

    6.12. Forms

    1059

    Django Documentation, Release 2.1.dev20171226153947

    id_for_label(id_) Returns the HTML ID attribute of this widget for use by a , given the ID of the field. Returns None if an ID isn’t available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget’s tags. render(name, value, attrs=None, renderer=None) Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the FORM_RENDERER setting is used. value_from_ ...> NumberInput class NumberInput • input_type: 'number'

    1062

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    • template_name: 'django/forms/widgets/number.html' • Renders as: Beware that not all browsers support entering localized numbers in number input types. Django itself avoids using them for fields having their localize property set to True. EmailInput class EmailInput • input_type: 'email' • template_name: 'django/forms/widgets/email.html' • Renders as: URLInput class URLInput • input_type: 'url' • template_name: 'django/forms/widgets/url.html' • Renders as: PasswordInput class PasswordInput • input_type: 'password' • template_name: 'django/forms/widgets/password.html' • Renders as: Takes one optional argument: render_value Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False). HiddenInput class HiddenInput • input_type: 'hidden' • template_name: 'django/forms/widgets/hidden.html' • Renders as: Note that there also is a MultipleHiddenInput widget that encapsulates a set of hidden input elements.

    6.12. Forms

    1063

    Django Documentation, Release 2.1.dev20171226153947

    DateInput class DateInput • input_type: 'text' • template_name: 'django/forms/widgets/date.html' • Renders as: Takes same arguments as TextInput, with one more optional argument: format The format in which this field’s initial value will be displayed. If no format argument is provided, the default format is the first format found in DATE_INPUT_FORMATS and respects Format localization. DateTimeInput class DateTimeInput • input_type: 'text' • template_name: 'django/forms/widgets/datetime.html' • Renders as: Takes same arguments as TextInput, with one more optional argument: format The format in which this field’s initial value will be displayed. If no format argument is provided, the default format DATETIME_INPUT_FORMATS and respects Format localization.

    is

    the

    first

    format

    found

    in

    By default, the microseconds part of the time value is always set to 0. If microseconds are required, use a subclass with the supports_microseconds attribute set to True. TimeInput class TimeInput • input_type: 'text' • template_name: 'django/forms/widgets/time.html' • Renders as: Takes same arguments as TextInput, with one more optional argument: format The format in which this field’s initial value will be displayed. If no format argument is provided, the default format is the first format found in TIME_INPUT_FORMATS and respects Format localization. For the treatment of microseconds, see DateTimeInput.

    1064

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Textarea class Textarea • template_name: 'django/forms/widgets/textarea.html' • Renders as: ... Selector and checkbox widgets These widgets make use of the HTML elements , , and . Widgets that render multiple choices have an option_template_name attribute that specifies the template used to render each choice. For example, for the Select widget, select_option.html renders the for a . CheckboxInput class CheckboxInput • input_type: 'checkbox' • template_name: 'django/forms/widgets/checkbox.html' • Renders as: Takes one optional argument: check_test A callable that takes the value of the CheckboxInput and returns True if the checkbox should be checked for that value. Select class Select • template_name: 'django/forms/widgets/select.html' • option_template_name: 'django/forms/widgets/select_option.html' • Renders as: ... choices This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the Field. NullBooleanSelect class NullBooleanSelect • template_name: 'django/forms/widgets/select.html' • option_template_name: 'django/forms/widgets/select_option.html' Select widget with options ‘Unknown’, ‘Yes’ and ‘No’

    6.12. Forms

    1065

    Django Documentation, Release 2.1.dev20171226153947

    SelectMultiple class SelectMultiple • template_name: 'django/forms/widgets/select.html' • option_template_name: 'django/forms/widgets/select_option.html' Similar to Select, but allows multiple selection: ... RadioSelect class RadioSelect • template_name: 'django/forms/widgets/radio.html' • option_template_name: 'django/forms/widgets/radio_option.html' Similar to Select, but rendered as a list of radio buttons within
  • tags:
    • ...


    For more granular control over the generated markup, you can loop over the radio buttons in the template. Assuming a form myform with a field beatles that uses a RadioSelect as its widget: {% for radio in myform.beatles %} {{ radio }} {% endfor %}

    This would generate the following HTML: Paul Ringo

    name="beatles" type="radio

    name="beatles" type="radio

    name="beatles" type="radio

    name="beatles" type="radio

    That included the tags. To get more granular, you can use each radio button’s tag, choice_label and id_for_label attributes. For example, this template. . . {% for radio in myform.beatles %}

    1066

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    {{ radio.choice_label }} {{ radio.tag }} {% endfor %}

    . . . will result in the following HTML: John Paul George Ringo

    If you decide not to loop over the radio buttons – e.g., if your template simply includes {{ myform.beatles }} – they’ll be output in a
      with
    • tags, as above. The outer
        container receives the id attribute of the widget, if defined, or BoundField.auto_id otherwise. When looping over the radio buttons, the label and input tags include for and id attributes, respectively. Each radio button has an id_for_label attribute to output the element’s ID. CheckboxSelectMultiple class CheckboxSelectMultiple • template_name: 'django/forms/widgets/checkbox_select.html' • option_template_name: 'django/forms/widgets/checkbox_option.html' Similar to SelectMultiple, but rendered as a list of check buttons:
        • ...


        The outer
          container receives the id attribute of the widget, if defined, or BoundField.auto_id otherwise.

          6.12. Forms

          1067

          Django Documentation, Release 2.1.dev20171226153947

          Like RadioSelect, you can loop over the individual checkboxes for the widget’s choices. Unlike RadioSelect, the checkboxes won’t include the required HTML attribute if the field is required because browser validation would require all checkboxes to be checked instead of at least one. When looping over the checkboxes, the label and input tags include for and id attributes, respectively. Each checkbox has an id_for_label attribute to output the element’s ID. File upload widgets FileInput class FileInput • template_name: 'django/forms/widgets/file.html' • Renders as: ClearableFileInput class ClearableFileInput • template_name: 'django/forms/widgets/clearable_file_input.html' • Renders as: with an additional checkbox input to clear the field’s value, if the field is not required and has initial ...> tags A widget that handles multiple hidden widgets for fields that have a list of values. choices This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the Field. SplitDateTimeWidget class SplitDateTimeWidget • template_name: 'django/forms/widgets/splitdatetime.html' Wrapper (using MultiWidget) around two widgets: DateInput for the date, and TimeInput for the time. Must be used with SplitDateTimeField rather than DateTimeField. SplitDateTimeWidget has several optional arguments: date_format Similar to DateInput.format

          1068

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          time_format Similar to TimeInput.format date_attrs time_attrs Similar to Widget.attrs. A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren’t set, Widget.attrs is used instead. SplitHiddenDateTimeWidget class SplitHiddenDateTimeWidget • template_name: 'django/forms/widgets/splithiddendatetime.html' Similar to SplitDateTimeWidget, but uses HiddenInput for both date and time. SelectDateWidget class SelectDateWidget • template_name: 'django/forms/widgets/select_date.html' Wrapper around three Select widgets: one each for month, day, and year. Takes several optional arguments: years An optional list/tuple of years to use in the “year” select box. The default is a list containing the current year and the next 9 years. months An optional dict of months to use in the “months” select box. The keys of the dict correspond to the month number (1-indexed) and the values are the displayed months: MONTHS = { 1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'), 5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'), 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec') }

          empty_label If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label'). # A custom empty label with string field1 = forms.DateField(widget=SelectDateWidget(empty_label="Nothing")) # A custom empty label with tuple field1 = forms.DateField( widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"),

          6.12. Forms

          1069

          Django Documentation, Release 2.1.dev20171226153947

          ), )

          6.12.7 Form and field validation Form validation happens when the , code="us"), Country(name="France", code="fr"), ]) def reverse_func(apps, schema_editor): # forwards_func() creates two Country instances, # so reverse_func() should delete them. Country = apps.get_model("myapp", "Country") db_alias = schema_editor.connection.alias Country.objects.using(db_alias).filter(name="USA", code="us").delete() Country.objects.using(db_alias).filter(name="France", code="fr").delete() class Migration(migrations.Migration): dependencies = [] operations = [ migrations.RunPython(forwards_func, reverse_func), ]

          This is generally the operation you would use to create

          Alternatively you can use plain text and django.utils.html.escape() to escape any HTML special characters. Ensure that you escape any help text that may come from untrusted users to avoid a cross-site scripting attack. primary_key Field.primary_key If True, this field is the primary key for the model. If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields. primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object. The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one. unique Field.unique If True, this field must be unique throughout the table. This is enforced at the , then Django wouldn’t allow the entry of two records with the same title and pub_date.

          6.15. Models

          1093

          Django Documentation, Release 2.1.dev20171226153947

          Note that if you set this to point to a DateTimeField, only the date portion of the field will be considered. Besides, when USE_TZ is True, the check will be performed in the current time zone at the time the object gets saved. This is enforced by Model.validate_unique() during model validation but not at the , match="foo.*", recursive=True)

          . . . will match /home/images/foo.png but not /home/images/foo/bar.png because the match applies to the base filename (foo.png and bar.png). FilePathField instances are created in your , related_query_name="tag", ) name = models.CharField(max_length=255) # That's now the name of the reverse filter Article.objects.filter(tag__name="important")

          Like related_name, related_query_name supports app label and class interpolation via some special syntax. ForeignKey.to_field The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True. ForeignKey.db_constraint Controls whether or not a constraint should be created in the , ) invite_reason = models.CharField(max_length=64)

          Membership has two foreign keys to Person (person and inviter), which makes the relationship ambiguous and Django can’t know which one to use. In this case, you must explicitly specify which foreign keys Django should use using through_fields, as in the example above. through_fields accepts a 2-tuple ('field1', 'field2'), where field1 is the name of the foreign key to the model the ManyToManyField is defined on (group in this case), and field2 the name of the foreign key to the target model (person in this case). When you have more than one foreign key on an intermediary model to any (or even both) of the models participating in a many-to-many relationship, you must specify through_fields. This also applies to recursive relationships when an intermediary model is used and there are more than two foreign keys to the model, or you want to explicitly specify which two Django should use. Recursive relationships using an intermediary model are always defined as non-symmetrical – that is, with symmetrical=False – therefore, there is the concept of a “source” and a “target”. In that case 'field1' will be treated as the “source” of the relationship and 'field2' as the “target”. ManyToManyField.db_table The name of the table to create for storing the many-to-many ). All built-in lookups are registered by default. All of Django’s built-in fields, such as CharField, are particular implementations of Field. If you need a custom field, you can either subclass any of the built-in fields or write a Field from scratch. In either case, see Writing custom model fields. description A verbose description of the field, e.g. for the django.contrib.admindocs application. The description can be of the form: description = _("String (up to %(max_length)s)")

          where the arguments are interpolated from the field’s __dict__. To map a Field to a >{{ object.name }}

          This template code is much better: {{ object.name }}

          The logic here is that if you change the URL structure of your objects, even for something simple such as correcting a spelling error, you don’t want to have to track down every place that the URL might be created. Specify it once, in get_absolute_url() and have all your other code call that one place. Note: The string you return from get_absolute_url() must contain only ASCII characters (required by the URI specification, RFC 2396) and be URL-encoded, if necessary. Code and templates calling get_absolute_url() should be able to use the result directly without any further processing. You may wish to use the django.utils.encoding.iri_to_uri() function to help with this if you are using strings containing characters outside the ASCII range.

          Extra instance methods In addition to save(), delete(), a model object might have some of the following methods: Model.get_FOO_display() For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field. For example: from django.db import models class Person(models.Model): SHIRT_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60) shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES) >>> p = Person(name="Fred Flintstone", shirt_size="L") >>> p.save() >>> p.shirt_size 'L'

          6.15. Models

          1141

          Django Documentation, Release 2.1.dev20171226153947

          >>> p.get_shirt_size_display() 'Large'

          Model.get_next_by_FOO(**kwargs) Model.get_previous_by_FOO(**kwargs) For every DateField and DateTimeField that does not have null=True, the object will have get_next_by_FOO() and get_previous_by_FOO() methods, where FOO is the name of the field. This returns the next and previous object with respect to the date field, raising a DoesNotExist exception when appropriate. Both of these methods will perform their queries using the default manager for the model. If you need to emulate filtering used by a custom manager, or want to perform one-off custom filtering, both methods also accept optional keyword arguments, which should be in the format described in Field lookups. Note that in the case of identical date values, these methods will use the primary key as a tie-breaker. This guarantees that no records are skipped or duplicated. That also means you cannot use those methods on unsaved objects. Other attributes DoesNotExist exception Model.DoesNotExist This exception is raised by the ORM in a couple places, for example by QuerySet.get() when an object is not found for the given query parameters. Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except. The exception is a subclass of django.core.exceptions.ObjectDoesNotExist.

          6.15.9 QuerySet API reference This document describes the details of the QuerySet API. It builds on the material presented in the model and ): print("There is at least one Entry with the headline Test")

          Note: If you only want to determine if at least one result exists (and don’t need the actual objects), it’s more efficient to use exists(). Pickling QuerySets If you pickle a QuerySet, this will force all the results to be loaded into memory prior to pickling. Pickling is usually used as a precursor to caching and when the cached queryset is reloaded, you want the results to already be present and ready for use (reading from the , last_name="Springsteen")

          and: p = Person(first_name="Bruce", last_name="Springsteen") p.save(force_insert=True)

          are equivalent.

          6.15. Models

          1167

          Django Documentation, Release 2.1.dev20171226153947

          The force_insert parameter is documented elsewhere, but all it means is that a new object will always be created. Normally you won’t need to worry about this. However, if your model contains a manual primary key value that you set and if that value already exists in the ) >>> book.chapters.get_or_create(title="Telemachus") (, True) >>> book.chapters.get_or_create(title="Telemachus") (, False) >>> Chapter.objects.create(title="Chapter 1") >>> book.chapters.get_or_create(title="Chapter 1") # Raises IntegrityError

          This is happening because it’s trying to get or create “Chapter 1” through the book “Ulysses”, but it can’t do any of them: the relation can’t fetch that chapter because it isn’t related to that book, but it can’t create it either because title field should be unique.

          update_or_create() update_or_create(defaults=None, **kwargs) A convenience method for updating an object with the given kwargs, creating a new one if necessary. The defaults is a dictionary of (field, value) pairs used to update the object. The values in defaults can be callables. Returns a tuple of (object, created), where object is the created or updated object and created is a boolean specifying whether a new object was created. The update_or_create method tries to fetch an object from , )

          To avoid a SQL injection vulnerability, extra_context must not contain untrusted user input as these values are interpolated into the SQL string rather than passed as query parameters, where the ) | Q(name__startswith="Paul"), then='name')

          Keep in mind that each of these values can be an expression. Note: Since the then keyword argument is reserved for the result of the When(), there is a potential conflict if a Model has a field named then. This can be resolved in two ways: >>> When(then__exact=0, then=1) >>> When(Q(then=0), then=1)

          Case class Case(*cases, **extra) A Case() expression is like the if . . . elif . . . else statement in Python. Each condition in the provided When() objects is evaluated in order, until one evaluates to a truthful value. The result expression from the matching When() object is returned. A simple example: >>> >>> >>> >>> ... ... ... >>> ... ... ... >>> ... ... ... >>> >>> ... ... ... ... ... ...

          from datetime import date, timedelta from django.db.models import CharField, Case, Value, When Client.objects.create( name='Jane Doe', account_type=Client.REGULAR, registered_on=date.today() - timedelta(days=36)) Client.objects.create( name='James Smith', account_type=Client.GOLD, registered_on=date.today() - timedelta(days=5)) Client.objects.create( name='Jack Black', account_type=Client.PLATINUM, registered_on=date.today() - timedelta(days=10 * 365)) # Get the discount for each Client based on the account type Client.objects.annotate( discount=Case( When(account_type=Client.GOLD, then=Value('5%')), When(account_type=Client.PLATINUM, then=Value('10%')), default=Value('0%'), output_field=CharField(), ),

          6.15. Models

          1211

          Django Documentation, Release 2.1.dev20171226153947

          ... ).values_list('name', 'discount')

          Case() accepts any number of When() objects as individual arguments. Other options are provided using keyword arguments. If none of the conditions evaluate to TRUE, then the expression given with the default keyword argument is returned. If a default argument isn’t provided, None is used. If we wanted to change our previous query to get the discount based on how long the Client has been with us, we could do so using lookups: >>> a_month_ago = date.today() - timedelta(days=30) >>> a_year_ago = date.today() - timedelta(days=365) >>> # Get the discount for each Client based on the registration date >>> Client.objects.annotate( ... discount=Case( ... When(registered_on__lte=a_year_ago, then=Value('10%')), ... When(registered_on__lte=a_month_ago, then=Value('5%')), ... default=Value('0%'), ... output_field=CharField(), ... ) ... ).values_list('name', 'discount')

          Note: Remember that the conditions are evaluated in order, so in the above example we get the correct result even though the second condition matches both Jane Doe and Jack Black. This works just like an if . . . elif . . . else statement in Python. Case() also works in a filter() clause. For example, to find gold clients that registered more than a month ago and platinum clients that registered more than a year ago: >>> a_month_ago = date.today() - timedelta(days=30) >>> a_year_ago = date.today() - timedelta(days=365) >>> Client.objects.filter( ... registered_on__lte=Case( ... When(account_type=Client.GOLD, then=a_month_ago), ... When(account_type=Client.PLATINUM, then=a_year_ago), ... ), ... ).values_list('name', 'account_type')

          Advanced queries Conditional expressions can be used in annotations, aggregations, lookups, and updates. They can also be combined and nested with other expressions. This allows you to make powerful conditional queries. Conditional update Let’s say we want to change the account_type for our clients to match their registration dates. We can do this using a conditional expression and the update() method: >>> a_month_ago = date.today() - timedelta(days=30) >>> a_year_ago = date.today() - timedelta(days=365) >>> # Update the account_type for each Client from the registration date

          1212

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          >>> Client.objects.update( ... account_type=Case( ... When(registered_on__lte=a_year_ago, ... then=Value(Client.PLATINUM)), ... When(registered_on__lte=a_month_ago, ... then=Value(Client.GOLD)), ... default=Value(Client.REGULAR) ... ), ... ) >>> Client.objects.values_list('name', 'account_type')

          Conditional aggregation What if we want to find out how many clients there are for each account_type? We can use the filter argument of aggregate functions to achieve this: >>> # Create some more Clients first so we can have something to count >>> Client.objects.create( ... name='Jean Grey', ... account_type=Client.REGULAR, ... registered_on=date.today()) >>> Client.objects.create( ... name='James Bond', ... account_type=Client.PLATINUM, ... registered_on=date.today()) >>> Client.objects.create( ... name='Jane Porter', ... account_type=Client.PLATINUM, ... registered_on=date.today()) >>> # Get counts for each value of account_type >>> from django.db.models import Count >>> Client.objects.aggregate( ... regular=Count('pk', filter=Q(account_type=Client.REGULAR)), ... gold=Count('pk', filter=Q(account_type=Client.GOLD)), ... platinum=Count('pk', filter=Q(account_type=Client.PLATINUM)), ... ) {'regular': 2, 'gold': 1, 'platinum': 3}

          This aggregate produces a query with the SQL 2003 FILTER WHERE syntax on name="" />. Each value in FILES is an UploadedFile. See Managing files for more information. FILES will only contain . Otherwise, FILES will be a blank dictionary-like object. HttpRequest.META A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples: • CONTENT_LENGTH – The length of the request body (as a string). • CONTENT_TYPE – The MIME type of the request body. • HTTP_ACCEPT – Acceptable content types for the response. • HTTP_ACCEPT_ENCODING – Acceptable encodings for the response. • HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response. • HTTP_HOST – The HTTP Host header sent by the client. • HTTP_REFERER – The referring page, if any. • HTTP_USER_AGENT – The client’s user-agent string. • QUERY_STRING – The query string, as a single (unparsed) string. • REMOTE_ADDR – The IP address of the client. • REMOTE_HOST – The hostname of the client. • REMOTE_USER – The user authenticated by the Web server, if any. • REQUEST_METHOD – A string such as "GET" or "POST". • SERVER_NAME – The hostname of the server. • SERVER_PORT – The port of the server (as a string). With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER. Note that runserver strips all headers with underscores in the name, so you won’t see them in META. This prevents header-spoofing based on ambiguity between underscores and dashes both being normalizing to underscores in WSGI environment variables. It matches the behavior of Web servers like Nginx and Apache 2.4+. HttpRequest.resolver_match An instance of ResolverMatch representing the resolved URL. This attribute is only set after URL resolving took place, which means it’s available in all views but not in middleware which are executed before URL resolving takes place (you can use it in process_view() though).

          6.16. Request and response objects

          1231

          Django Documentation, Release 2.1.dev20171226153947

          Attributes set by application code Django doesn’t set these attributes itself but makes use of them if set by your application. HttpRequest.current_app The url template tag will use its value as the current_app argument to reverse(). HttpRequest.urlconf This will be used as the root URLconf for the current request, overriding the ROOT_URLCONF setting. See How Django processes a request for details. urlconf can be set to None to revert any changes made by previous middleware and return to using the ROOT_URLCONF. Attributes set by middleware Some of the middleware included in Django’s contrib apps set attributes on the request. If you don’t see the attribute on a request, be sure the appropriate middleware class is listed in MIDDLEWARE. HttpRequest.session From the SessionMiddleware: A readable and writable, dictionary-like object that represents the current session. HttpRequest.site From the CurrentSiteMiddleware: An instance of Site or RequestSite as returned by get_current_site() representing the current site. HttpRequest.user From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in, user will be set to an instance of AnonymousUser. You can tell them apart with is_authenticated, like so: if request.user.is_authenticated: ... # Do something for logged-in users. else: ... # Do something for anonymous users.

          Methods HttpRequest.get_host() Returns the originating host of the request using information from the HTTP_X_FORWARDED_HOST (if USE_X_FORWARDED_HOST is enabled) and HTTP_HOST headers, in that order. If they don’t provide a value, the method uses a combination of SERVER_NAME and SERVER_PORT as detailed in PEP 3333. Example: "127.0.0.1:8000" Note: The get_host() method fails when the host is behind multiple proxies. One solution is to use middleware to rewrite the proxy headers, as in the following example: from django.utils.deprecation import MiddlewareMixin class MultipleProxyMiddleware(MiddlewareMixin): FORWARDED_FOR_FIELDS = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_SERVER',

          1232

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          ] def process_request(self, request): """ Rewrites the proxy headers so that only the most recent proxy is used. """ for field in self.FORWARDED_FOR_FIELDS: if field in request.META: if ',' in request.META[field]: parts = request.META[field].split(',') request.META[field] = parts[-1].strip()

          This middleware should be positioned before any other middleware that relies on the value of get_host() – for instance, CommonMiddleware or CsrfViewMiddleware. HttpRequest.get_port() Returns the originating port of the request using information from the HTTP_X_FORWARDED_PORT (if USE_X_FORWARDED_PORT is enabled) and SERVER_PORT META variables, in that order. HttpRequest.get_full_path() Returns the path, plus an appended query string, if applicable. Example: "/music/bands/the_beatles/?print=true" HttpRequest.get_full_path_info() Like get_full_path(), but uses path_info instead of path. Example: "/minfo/music/bands/the_beatles/?print=true" HttpRequest.build_absolute_uri(location) Returns the absolute URI form of location. If no location is provided, the location will be set to request. get_full_path(). If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request. Example: "https://example.com/music/bands/the_beatles/?print=true" Note: Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has. If you need to redirect users to HTTPS, it’s best to let your Web server redirect all HTTP traffic to HTTPS. HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt=”, max_age=None) Returns a cookie value for a signed cookie, or raises a django.core.signing.BadSignature exception if the signature is no longer valid. If you provide the default argument the exception will be suppressed and that default value will be returned instead. The optional salt argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the max_age argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than max_age seconds. For example: >>> request.get_signed_cookie('name') 'Tony' >>> request.get_signed_cookie('name', salt='name-salt') 'Tony' # assuming cookie was set using the same salt

          6.16. Request and response objects

          1233

          Django Documentation, Release 2.1.dev20171226153947

          >>> request.get_signed_cookie('nonexistent-cookie') ... KeyError: 'nonexistent-cookie' >>> request.get_signed_cookie('nonexistent-cookie', False) False >>> request.get_signed_cookie('cookie-that-was-tampered-with') ... BadSignature: ... >>> request.get_signed_cookie('name', max_age=60) ... SignatureExpired: Signature age 1677.3839159 > 60 seconds >>> request.get_signed_cookie('name', False, max_age=60) False

          See cryptographic signing for more information. HttpRequest.is_secure() Returns True if the request is secure; that is, if it was made with HTTPS. HttpRequest.is_ajax() Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string 'XMLHttpRequest'. Most modern JavaScript libraries send this header. If you write your own XMLHttpRequest call (on the browser side), you’ll have to set this header manually if you want is_ajax() to work. If a response varies on whether or not it’s requested via AJAX and you are using some form of caching like Django’s cache middleware, you should decorate the view with vary_on_headers('X-Requested-With') so that the responses are properly cached. HttpRequest.read(size=None) HttpRequest.readline() HttpRequest.readlines() HttpRequest.__iter__() Methods implementing a file-like interface for reading from an HttpRequest instance. This makes it possible to consume an incoming request in a streaming fashion. A common use-case would be to process a big XML payload with an iterative parser without constructing a whole XML tree in memory. Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree: import xml.etree.ElementTree as ET for element in ET.iterparse(request): process(element)

          6.16.3 QueryDict objects class QueryDict In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict, a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably , pass multiple values for the same key. The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle. To get a mutable version you need to use QueryDict.copy().

          1234

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          Methods QueryDict implements all the standard dictionary methods because it’s a subclass of dictionary. Exceptions are outlined here: QueryDict.__init__(query_string=None, mutable=False, encoding=None) Instantiates a QueryDict object based on query_string. >>> QueryDict('a=1&a=2&c=3')

          If query_string is not passed in, the resulting QueryDict will be empty (it will have no keys or values). Most QueryDicts you encounter, and in particular those at request.POST and request.GET, will be immutable. If you are instantiating one yourself, you can make it mutable by passing mutable=True to its __init__(). Strings for setting both keys and values will be converted from encoding to str. If encoding is not set, it defaults to DEFAULT_CHARSET. classmethod QueryDict.fromkeys(iterable, value=”, mutable=False, encoding=None) Creates a new QueryDict with keys from iterable and each value equal to value. For example: >>> QueryDict.fromkeys(['a', 'a', 'b'], value='val')

          QueryDict.__getitem__(key) Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django. utils.)

          But if you want to add content incrementally, you can use response as a file-like object: >>> response = HttpResponse() >>> response.write("

          Here's the text of the Web page.

          ") >>> response.write("

          Here's another paragraph.

          ")

          Passing iterators Finally, you can pass HttpResponse an iterator rather than strings. HttpResponse will consume the iterator immediately, store its content as a string, and discard it. Objects with a close() method such as files and generators are immediately closed. If you need the response to be streamed from the iterator to the client, you must use the StreamingHttpResponse class instead.

          6.16. Request and response objects

          1237

          Django Documentation, Release 2.1.dev20171226153947

          Setting header fields To set or remove a header field in your response, treat it like a dictionary: >>> response = HttpResponse() >>> response['Age'] = 120 >>> del response['Age']

          Note that unlike a dictionary, del doesn’t raise KeyError if the header field doesn’t exist. For setting the Cache-Control and Vary header fields, it is recommended to use the patch_cache_control() and patch_vary_headers() methods from django.utils.cache, since these fields can have multiple, comma-separated values. The “patch” methods ensure that other values, e.g. added by a middleware, are not removed. HTTP header fields cannot contain newlines. An attempt to set a header field containing a newline character (CR or LF) will raise BadHeaderError Telling the browser to treat the response as a file attachment To tell the browser to treat the response as a file attachment, use the content_type argument and set the Content-Disposition header. For example, this is how you might return a Microsoft Excel spreadsheet: >>> response = HttpResponse(my_'

          There’s nothing Django-specific about the Content-Disposition header, but it’s easy to forget the syntax, so we’ve included it here. Attributes HttpResponse.content A bytestring representing the content, encoded from a string if necessary. HttpResponse.charset A string denoting the charset in which the response will be encoded. If not given at HttpResponse instantiation time, it will be extracted from content_type and if that is unsuccessful, the DEFAULT_CHARSET setting will be used. HttpResponse.status_code The HTTP status code for the response. Unless reason_phrase is explicitly set, modifying the value of status_code outside the constructor will also modify the value of reason_phrase. HttpResponse.reason_phrase The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases. Unless explicitly set, reason_phrase is determined by the value of status_code. HttpResponse.streaming This is always False. This attribute exists so middleware can treat streaming responses differently from regular responses. HttpResponse.closed True if the response has been closed.

          1238

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          Methods HttpResponse.__init__(content=”, content_type=None, status=200, reason=None, charset=None) Instantiates an HttpResponse object with the given page content and content type. content should be an iterator or a string. If it’s an iterator, it should return strings, and those strings will be joined together to form the content of the response. If it is not an iterator or a string, it will be converted to a string when accessed. content_type is the MIME type optionally completed by a character set encoding and is used to fill the HTTP Content-Type header. If not specified, it is formed by the DEFAULT_CONTENT_TYPE and DEFAULT_CHARSET settings, by default: “text/html; charset=utf-8”. status is the HTTP status code for the response. reason is the HTTP response phrase. If not provided, a default phrase will be used. charset is the charset in which the response will be encoded. If not given it will be extracted from content_type, and if that is unsuccessful, the DEFAULT_CHARSET setting will be used. HttpResponse.__setitem__(header, value) Sets the given header name to the given value. Both header and value should be strings. HttpResponse.__delitem__(header) Deletes the header with the given name. Fails silently if the header doesn’t exist. Case-insensitive. HttpResponse.__getitem__(header) Returns the value for the given header name. Case-insensitive. HttpResponse.has_header(header) Returns True or False based on a case-insensitive check for a header with the given name. HttpResponse.setdefault(header, value) Sets a header unless it has already been set. HttpResponse.set_cookie(key, value=”, max_age=None, expires=None, path=’/’, domain=None, secure=None, httponly=False) Sets a cookie. The parameters are the same as in the Morsel cookie object in the Python standard library. • max_age should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. If expires is not specified, it will be calculated. • expires should either be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT" or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated. • Use domain if you want to set a cross-domain cookie. For example, domain="example.com" will set a cookie that is readable by the domains www.example.com, blog.example.com, etc. Otherwise, a cookie will only be readable by the domain that set it. • Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie. HTTPOnly is a flag included in a Set-Cookie HTTP response header. It is not part of the RFC 2109 standard for cookies, and it isn’t honored consistently by all browsers. However, when it is honored, it can be a useful way to mitigate the risk of a client-side script from accessing the protected cookie ): ...

          where reason is a short message (intended for developers or logging, not for end users) indicating the reason the request was rejected. It should return an HttpResponseForbidden. django.views.csrf.csrf_failure() accepts an additional template_name parameter that defaults to '403_csrf.html'. If a template with that name exists, it will be used to render the page.

          6.18. Settings

          1251

          Django Documentation, Release 2.1.dev20171226153947

          CSRF_HEADER_NAME Default: 'HTTP_X_CSRFTOKEN' The name of the request header used for CSRF authentication. As with other HTTP headers in request.META, the header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name. For example, if your client sends a 'X-XSRF-TOKEN' header, the setting should be 'HTTP_X_XSRF_TOKEN'. CSRF_TRUSTED_ORIGINS Default: [] (Empty list) A list of hosts which are trusted origins for unsafe requests (e.g. POST). For a secure unsafe request, Django’s CSRF protection requires that the request have a Referer header that matches the origin present in the Host header. This prevents, for example, a POST request from subdomain.example.com from succeeding against api. example.com. If you need cross-origin unsafe requests over HTTPS, continuing the example, add "subdomain. example.com" to this list. The setting also supports subdomains, so you could add ".example.com", for example, to allow access from all subdomains of example.com. downloads/polls_20101022.tar.gz" %}">

          STATICFILES_STORAGE Default: 'django.contrib.staticfiles.storage.StaticFilesStorage' The file storage engine to use when collecting static files with the collectstatic management command. A ready-to-use instance of the storage backend defined in this setting can be found at django.contrib. staticfiles.storage.staticfiles_storage. For an example, see Serving static files from a cloud service or CDN. STATICFILES_FINDERS Default: [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ]

          The list of finder backends that know how to find static files in various locations. The default will find files stored in the STATICFILES_DIRS setting (using django.contrib.staticfiles. finders.FileSystemFinder) and in a static subdirectory of each app (using django.contrib. staticfiles.finders.AppDirectoriesFinder). If multiple files with the same name are present, the first file that is found will be used. One finder is disabled by default: django.contrib.staticfiles.finders.DefaultStorageFinder. If added to your STATICFILES_FINDERS setting, it will look for static files in the default file storage as defined by the DEFAULT_FILE_STORAGE setting. Note: When using the AppDirectoriesFinder finder, make sure your apps can be found by staticfiles. Simply add the app to the INSTALLED_APPS setting of your site. Static file finders are currently considered a private interface, and this interface is thus undocumented.

          1288

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          6.18.7 Core Settings Topical Index Cache • CACHES • CACHE_MIDDLEWARE_ALIAS • CACHE_MIDDLEWARE_KEY_PREFIX • CACHE_MIDDLEWARE_SECONDS , pub_date=datetime.now())

          6.19. Signals

          1293

          Django Documentation, Release 2.1.dev20171226153947

          The arguments sent to a pre_init handler would be: Argument sender args kwargs

          Value Poll (the class itself) [] (an empty list because there were no positional arguments passed to __init__().) {'question': "What's up?", 'pub_date': datetime.now()}

          post_init django.db.models.signals.post_init Like pre_init, but this one is sent when the __init__() method finishes. Arguments sent with this signal: sender As above: the model class that just had an instance created. instance The actual instance of the model that’s just been created. pre_save django.db.models.signals.pre_save This is sent at the beginning of a model’s save() method. Arguments sent with this signal: sender The model class. instance The actual instance being saved. raw A boolean; True if the model is saved exactly as presented (i.e. when loading a fixture). One should not query/modify other records in the > {{ story.headline|upper }}

          {{ story.tease|truncatewords:"100" }}

          {% endfor %} {% endblock %}

          Philosophy

          6.20. Templates

          1301

          Django Documentation, Release 2.1.dev20171226153947

          Why use a text-based template instead of an XML-based one (like Zope’s TAL)? We wanted Django’s template language to be usable for more than just XML/HTML templates. At World Online, we use it for emails, JavaScript and CSV. You can use the template language for any text-based format. Oh, and one more thing: making humans edit XML is sadistic!

          Variables Variables look like this: {{ variable }}. When the template engine encounters a variable, it evaluates that variable and replaces it with the result. Variable names consist of any combination of alphanumeric characters and the underscore ("_"). The dot (".") also appears in variable sections, although that has a special meaning, as indicated below. Importantly, you cannot have spaces or punctuation characters in variable names. Use a dot (.) to access attributes of a variable. Behind the scenes Technically, when the template system encounters a dot, it tries the following lookups, in this order: • Dictionary lookup • Attribute or method lookup • Numeric index lookup If the resulting value is callable, it is called with no arguments. The result of the call becomes the template value. This lookup order can cause some unexpected behavior with objects that override dictionary lookup. For example, consider the following code snippet that attempts to loop over a collections.defaultdict: {% for k, v in defaultdict.items %} Do something with k and v here... {% endfor %}

          Because dictionary lookup happens first, that behavior kicks in and provides a default value instead of using the intended .items() method. In this case, consider converting to a dictionary first. In the above example, {{ section.title }} will be replaced with the title attribute of the section object. If you use a variable that doesn’t exist, the template system will insert the value of the string_if_invalid option, which is set to '' (the empty string) by default. Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context. Filters You can modify variables for display by using filters. Filters look like this: {{ name|lower }}. This displays the value of the {{ name }} variable after being filtered through the lower filter, which converts text to lowercase. Use a pipe (|) to apply a filter. Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to

          tags. Some filters take arguments. A filter argument looks like this: {{ bio|truncatewords:30 }}. This will display the first 30 words of the bio variable.

          1302

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          Filter arguments that contain spaces must be quoted; for example, to join a list with commas and spaces you’d use {{ list|join:", " }}. Django provides about sixty built-in template filters. You can read all about them in the built-in filter reference. To give you a taste of what’s available, here are some of the more commonly used template filters: default If a variable is false or empty, use given default. Otherwise, use the value of the variable. For example: {{ value|default:"nothing" }}

          If value isn’t provided or is empty, the above will display “nothing”. length Returns the length of the value. This works for both strings and lists. For example: {{ value|length }}

          If value is ['a', 'b', 'c', 'd'], the output will be 4. filesizeformat Formats the value like a “human-readable” file size (i.e. bytes', etc.). For example:

          '13 KB', '4.1 MB', '102

          {{ value|filesizeformat }}

          If value is 123456789, the output would be 117.7 MB. Again, these are just a few examples; see the built-in filter reference for the complete list. You can also create your own custom template filters; see Custom template tags and filters. See also: Django’s admin interface can include a complete reference of all template tags and filters available for a given site. See The Django admin documentation generator. Tags Tags look like this: {% tag %}. Tags are more complex than variables: Some create text in the output, some control flow by performing loops or logic, and some load external information into the template to be used by later variables. Some tags require beginning and ending tags (i.e. {% tag %} ... tag contents ... {% endtag %}). Django ships with about two dozen built-in template tags. You can read all about them in the built-in tag reference. To give you a taste of what’s available, here are some of the more commonly used tags: for Loop over each item in an array. For example, to display a list of athletes provided in athlete_list:

            {% for athlete in athlete_list %}
          • {{ athlete.name }}
          • {% endfor %}


          if, elif, and else Evaluates a variable, and if that variable is “true” the contents of the block are displayed: {% if athlete_list %} Number of athletes: {{ athlete_list|length }} {% elif athlete_in_locker_room_list %} Athletes should be out of the locker room soon! {% else %} No athletes. {% endif %}

          6.20. Templates

          1303

          Django Documentation, Release 2.1.dev20171226153947

          In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|length }} variable. Otherwise, if athlete_in_locker_room_list is not empty, the message “Athletes should be out. . . ” will be displayed. If both lists are empty, “No athletes.” will be displayed. You can also use filters and various operators in the if tag: {% if athlete_list|length > 1 %} Team: {% for athlete in athlete_list %} ... {% endfor %} {% else %} Athlete: {{ athlete_list.0.name }} {% endif %}

          While the above example works, be aware that most template filters return strings, so mathematical comparisons using filters will generally not work as you expect. length is an exception. block and extends Set up template inheritance (see below), a powerful way of cutting down on “boilerplate” in templates. Again, the above is only a selection of the whole list; see the built-in tag reference for the complete list. You can also create your own custom template tags; see Custom template tags and filters. See also: Django’s admin interface can include a complete reference of all template tags and filters available for a given site. See The Django admin documentation generator. Comments To comment-out part of a line in a template, use the comment syntax: {# #}. For example, this template would render as 'hello': {# greeting #}hello

          A comment can contain any template code, invalid or not. For example: {# {% if foo %}bar{% else %} #}

          This syntax can only be used for single-line comments (no newlines are permitted between the {# and #} delimiters). If you need to comment out a multiline portion of the template, see the comment tag. Template inheritance The most powerful – and thus the most complex – part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. It’s easiest to understand template inheritance by starting with an example: {% block title %}My amazing site{% endblock %}

          1304

          Chapter 6. API Reference

          Django Documentation, Release 2.1.dev20171226153947

          {% block sidebar %}
          • Home
          • Blog
          {% endblock %} {% block content %}{% endblock %}

          This template, which we’ll call base.html, defines a simple HTML skeleton document that you might use for a simple two-column page. It’s the job of “child” templates to fill the empty blocks with content. In this example, the block tag defines three blocks that child templates can fill in. All the block tag does is to tell the template engine that a child template may override those portions of the template. A child template might look like this: {% extends "base.html" %} {% block title %}My amazing blog{% endblock %} {% block content %} {% for entry in blog_entries %} {{ entry.title }}

          {{ entry.body }}

          {% endfor %} {% endblock %}

          The extends tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, first it locates the parent – in this case, “base.html”. At that point, the template engine will notice the three block tags in base.html and replace those blocks with the contents of the child template. Depending on the value of blog_entries, the output might look like: My amazing blog
          • Home
          • Blog
          Entry one

          This is my first entry.



          6.20. Templates

          1305

          Django Documentation, Release 2.1.dev20171226153947

          Entry two

          This is my second entry.



          Note that since the child template didn’t define the sidebar block, the value from the parent template is used instead. Content within a {% block %} tag in a parent template is always used as a fallback. You can use as many levels of inheritance as needed. One common way of using inheritance is the following three-level approach: • Create a base.html template that holds the main look-and-feel of your site. • Create a base_SECTIONNAME.html template for each “section” of your site. For example, base_news. html, base_sports.html. These templates all extend base.html and include section-specific styles/design. • Create individual templates for each type of page, such as a news article or blog entry. These templates extend the appropriate section template. This approach maximizes code reuse and makes it easy to add items to shared content areas, such as section-wide navigation. Here are some tips for working with inheritance: • If you use {% extends %} in a template, it must be the first template tag in that template. Template inheritance won’t work, otherwise. • More {% block %} tags in your base templates are better. Remember, child templates don’t have to define all parent blocks, so you can fill in reasonable defaults in a number of blocks, then only define the ones you need later. It’s better to have more hooks than fewer hooks. • If you find yourself duplicating content in a number of templates, it probably means you should move that content to a {% block %} in a parent template. • If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. > ... {% endfor %}

          The first iteration produces HTML that refers to class row1, the second to row2, the third to row1 again, and so on for each iteration of the loop. You can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this: {% for o in some_list %}
  • ... {% endfor %}

    Variables included in the cycle will be escaped. You can disable auto-escaping with: {% for o in some_list %} ... {% endfor %}

    You can mix variables and strings: {% for o in some_list %} ... {% endfor %}

    In some cases you might want to refer to the current value of a cycle without advancing to the next value. To do this, just give the {% cycle %} tag a name, using “as”, like this: {% cycle 'row1' 'row2' as rowcolors %}

    From then on, you can insert the current value of the cycle wherever you’d like in your template by referencing the cycle name as a context variable. If you want to move the cycle to the next value independently of the original cycle tag, you can use another cycle tag and specify the name of the variable. So, the following template:

    would output:

    1312

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947



    You can use any number of values in a cycle tag, separated by spaces. Values enclosed in single quotes (') or double quotes (") are treated as string literals, while values without quotes are treated as template variables. By default, when you use the as keyword with the cycle tag, the usage of {% cycle %} that initiates the cycle will itself produce the first value in the cycle. This could be a problem if you want to use the value in a nested loop or an included template. If you only want to declare the cycle but not produce the first value, you can add a silent keyword as the last keyword in the tag. For example: {% for obj in some_list %} {% cycle 'row1' 'row2' as rowcolors silent %} {% include "subtemplate.html" %} {% endfor %}

    This will output a list of elements with class alternating between row1 and row2. The subtemplate will have access to rowcolors in its context and the value will match the class of the that encloses it. If the silent keyword were to be omitted, row1 and row2 would be emitted as normal text, outside the element. When the silent keyword is used on a cycle definition, the silence automatically applies to all subsequent uses of that specific cycle tag. The following template would output nothing, even though the second call to {% cycle %} doesn’t specify silent: {% cycle 'row1' 'row2' as rowcolors silent %} {% cycle rowcolors %}

    You can use the resetcycle tag to make a {% cycle %} tag restart from its first value when it’s next encountered.

    debug Outputs a whole load of debugging information, including the current context and imported modules. extends Signals that this template extends a parent template. This tag can be used in two ways: • {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend. • {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template. See Template inheritance for more information. Normally the template name is relative to the template loader’s root directory. A string argument may also be a relative path starting with ./ or ../. For example, assume the following directory structure:

    6.20. Templates

    1313

    Django Documentation, Release 2.1.dev20171226153947

    dir1/ template.html base2.html my/ base3.html base1.html

    In template.html, the following paths would be valid: {% extends "./base2.html" %} {% extends "../base1.html" %} {% extends "./my/base3.html" %}

    filter Filters the contents of the block through one or more filters. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax. Note that the block includes all the text between the filter and endfilter tags. Sample usage: {% filter force_escape|lower %} This text will be HTML-escaped, and will appear in all lowercase. {% endfilter %}

    Note: The escape and safe filters are not acceptable arguments. Instead, use the autoescape tag to manage autoescaping for blocks of template code.

    firstof Outputs the first argument variable that is not False. Outputs nothing if all the passed variables are False. Sample usage: {% firstof var1 var2 var3 %}

    This is equivalent to: {% if var1 %} {{ var1 }} {% elif var2 %} {{ var2 }} {% elif var3 %} {{ var3 }} {% endif %}

    You can also use a literal string as a fallback value in case all passed variables are False: {% firstof var1 var2 var3 "fallback value" %}

    This tag auto-escapes variable values. You can disable auto-escaping with:

    1314

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    {% autoescape off %} {% firstof var1 var2 var3 "fallback value" %} {% endautoescape %}

    Or if only some variables should be escaped, you can use: {% firstof var1 var2|safe var3 "fallback value"|safe %}

    You can use the syntax {% firstof var1 var2 var3 as value %} to store the output inside a variable. for Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in athlete_list:
      {% for athlete in athlete_list %}
    • {{ athlete.name }}
    • {% endfor %}


    You can loop over a list in reverse by using {% for obj in list reversed %}. If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x,y) coordinates called points, you could use the following to output the list of points: {% for x, y in points %} There is a point at {{ x }},{{ y }} {% endfor %}

    This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary M/d"|lower }}/">{{ date|date:"j" }} {% endfor %}

    2. If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed: {% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %}

    The ifchanged tag can also take an optional {% else %} clause that will be displayed if the value has not changed: {% for match in matches %} {{ match }} {% endfor %}

    include Loads a template and renders it with the current context. This is a way of “including” other templates within a template. The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes. This example includes the contents of the template "foo/bar.html": {% include "foo/bar.html" %}

    Normally the template name is relative to the template loader’s root directory. A string argument may also be a relative path starting with ./ or ../ as described in the extends tag. This example includes the contents of the template whose name is contained in the variable template_name: {% include template_name %}

    The variable may also be any object with a render() method that accepts a context. This allows you to reference a compiled Template in your context. An included template is rendered within the context of the template that includes it. This example produces the output "Hello, John!": • Context: variable person is set to "John" and variable greeting is set to "Hello". • Template: {% include "name_snippet.html" %}

    • The name_snippet.html template: {{ greeting }}, {{ person|default:"friend" }}!

    You can pass additional context to the template using keyword arguments: {% include "name_snippet.html" with person="Jane" greeting="Hello" %}

    If you want to render the context only with the variables provided (or even no variables at all), use the only option. No other variables are available to the included template: {% include "name_snippet.html" with greeting="Hi" only %}

    Note: The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process. Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered - not blocks that can be overridden by, for example, an extending template.

    6.20. Templates

    1321

    Django Documentation, Release 2.1.dev20171226153947

    load Loads a custom template tag set. For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package: {% load somelibrary package.otherlibrary %}

    You can also selectively load individual filters or tags from a library, using the from argument. In this example, the template tags/filters named foo and bar will be loaded from somelibrary: {% load foo bar from somelibrary %}

    See Custom tag and filter libraries for more information. lorem Displays random “lorem ipsum” Latin text. This is useful for providing sample >{{ athlete.name }}

    {% endfor %} {% resetcycle %} {% endfor %}

    This example would return this HTML: José Mourinho

    Thibaut Courtois

    John Terry

    Eden Hazard

    Carlo Ancelotti

    Manuel Neuer

    Thomas Müller



    6.20. Templates

    1325

    Django Documentation, Release 2.1.dev20171226153947

    Notice how the first block ends with and the new one starts with . Without the {% resetcycle %} tag, the second block would start with . You can also reset named cycle tags: {% for item in list %}

    {{ item.>Foo

    {% endspaceless %}

    This example would return this HTML:

    Foo



    Only space between tags is removed – not space between tags and text. In this example, the space around Hello won’t be stripped: {% spaceless %} Hello {% endspaceless %}

    templatetag Outputs one of the syntax characters used to compose template tags. Since the template system has no concept of “escaping”, to display one of the bits used in template tags, you must use the {% templatetag %} tag. The argument tells which template bit to output:

    1326

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    Argument openblock closeblock openvariable closevariable openbrace closebrace opencomment closecomment

    Outputs {% %} {{ }} { } {# #}

    Sample usage: {% templatetag openblock %} url 'entry_list' {% templatetag closeblock %}

    url Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. Any special characters in the resulting path will be encoded using iri_to_uri(). This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates: {% url 'some-url-name' v1 v2 %}

    The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL. The example above shows passing positional arguments. Alternatively you may use keyword syntax: {% url 'some-url-name' arg1=v1 arg2=v2 %}

    Do not mix both positional and keyword syntax in a single call. All arguments required by the URLconf should be present. For example, suppose you have a view, app_views.client, whose URLconf takes a client ID (here, client() is a method inside the views file app_views.py). The URLconf line might look like this: path('client//', app_views.client, name='app-views-client')

    If this app’s URLconf is included into the project’s URLconf under a path such as this: path('clients/', include('project_name.app_name.urls'))

    . . . then, in a template, you can create a link to this view like this: {% url 'app-views-client' client.id %}

    The template tag will output the string /clients/client/123/. Note that if the URL you’re reversing doesn’t exist, you’ll get an NoReverseMatch exception raised, which will cause your site to display an error page. If you’d like to retrieve a URL without displaying it, you can use a slightly different call: {% url 'some-url-name' arg arg2 as the_url %} I'm linking to {{ the_url }}

    6.20. Templates

    1327

    Django Documentation, Release 2.1.dev20171226153947

    The scope of the variable created by the as var syntax is the {% block %} in which the {% url %} tag appears. This {% url ... as var %} syntax will not cause an error if the view is missing. In practice you’ll use this to link to views that are optional: {% url 'some-url-name' as the_url %} {% if the_url %} Link to optional stuff {% endif %}

    If you’d like to retrieve a namespaced URL, specify the fully qualified name: {% url 'myapp:view-name' %}

    This will follow the normal namespaced URL resolution strategy, including using any hints provided by the context as to the current application. Warning: Don’t forget to put quotes around the URL pattern name, otherwise the value will be interpreted as a context variable!

    verbatim Stops the template engine from rendering the contents of this block tag. A common use is to allow a JavaScript template layer that collides with Django’s syntax. For example: {% verbatim %} {{if dying}}Still alive.{{/if}} {% endverbatim %}

    You can also designate a specific closing tag, allowing the use of {% endverbatim %} as part of the unrendered contents: {% verbatim myblock %} Avoid template rendering via the {% verbatim %}{% endverbatim %} block. {% endverbatim myblock %}

    widthratio For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant. For example:

    If this_value is 175, max_value is 200, and max_width is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88). In some cases you might want to capture the result of widthratio in a variable. It can be useful, for instance, in a blocktrans like this:

    1328

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    {% widthratio this_value max_value max_width as width %} {% blocktrans %}The width is: {{ width }}{% endblocktrans %}

    with Caches a complex variable under a simpler name. This is useful when accessing an “expensive” method (e.g., one that hits the attribute added to them. For example: {{ value|urlize }}

    If value is "Check out www.djangoproject.com", the output will be "Check out www.djangoproject.com". In addition to web links, urlize also converts email addresses into mailto: links. If value is "Send questions to [email protected]", the output will be "Send questions to [email protected]". The urlize filter also takes an optional parameter autoescape. If autoescape is True, the link text and URLs will be escaped using Django’s built-in escape filter. The default value for autoescape is True. Note: If urlize is applied to text that already contains HTML markup, things won’t work as expected. Apply this filter only to plain text.

    urlizetrunc Converts URLs and email addresses into clickable links just like urlize, but truncates URLs longer than the given character limit. Argument: Number of characters that link text should be truncated to, including the ellipsis that’s added if truncation is necessary. For example: {{ value|urlizetrunc:15 }}

    If value is "Check out www.djangoproject.com", the output would be 'Check out www.djangopr...'. As with urlize, this filter should only be applied to plain text. wordcount Returns the number of words. For example:

    6.20. Templates

    1345

    Django Documentation, Release 2.1.dev20171226153947

    {{ value|wordcount }}

    If value is "Joel is a slug", the output will be 4. wordwrap Wraps words at specified line length. Argument: number of characters at which to wrap the text For example: {{ value|wordwrap:5 }}

    If value is Joel is a slug, the output would be: Joel is a slug

    yesno Maps values for True, False, and (optionally) None, to the strings “yes”, “no”, “maybe”, or a custom mapping passed as a comma-separated list, and returns one of those strings according to the value: For example: {{ value|yesno:"yeah,no,maybe" }}

    Value True True False None None

    Argument "yeah,no,maybe" "yeah,no,maybe" "yeah,no,maybe" "yeah,no"

    Outputs yes yeah no maybe no (converts None to False if no mapping for None is given)

    Internationalization tags and filters Django provides template tags and filters to control each aspect of internationalization in templates. They allow for granular control of translations, formatting, and time zone conversions. i18n This library allows specifying translatable text in templates. To enable it, set USE_I18N to True, then load it with {% load i18n %}. See Internationalization: in template code.

    1346

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    l10n This library provides control over the localization of values in templates. You only need to load the library using {% load l10n %}, but you’ll often set USE_L10N to True so that localization is active by default. See Controlling localization in templates. tz This library provides control over time zone conversions in templates. Like l10n, you only need to load the library using {% load tz %}, but you’ll usually also set USE_TZ to True so that conversion to local time happens by default. See Time zone aware output in templates. Other tags and filters libraries Django comes with a couple of other template-tag libraries that you have to enable explicitly in your INSTALLED_APPS setting and enable in your template with the {% load %} tag. django.contrib.humanize A set of Django template filters useful for adding a “human touch” to images/hi.jpg" %}" alt="Hi!" />

    It is also able to consume standard context variables, e.g. assuming a user_stylesheet variable is passed to the template: {% load static %}

    If you’d like to retrieve a static URL without displaying it, you can use a slightly different call: {% load static %} {% static "images/hi.jpg" as myphoto %}

    Using Jinja2 templates? See Jinja2 for information on using the static tag with Jinja2.

    6.20. Templates

    1347

    Django Documentation, Release 2.1.dev20171226153947

    get_static_prefix You should prefer the static template tag, but if you need more control over exactly where and how STATIC_URL is injected into the template, you can use the get_static_prefix template tag: {% load static %}

    There’s also a second form you can use to avoid extra processing if you need the value multiple times: {% load static %} {% get_static_prefix as STATIC_PREFIX %}

    get_media_prefix Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL, e.g.: {% load static %}

    By storing the value in a %} {% with tvar="Some string literal with %} in it." %}{% endwith %}

    The same issue can be triggered by using a reserved sequence in filter arguments: {{ some.variable|default:"}}" }}

    If you need to use strings with these sequences, store them in template variables or use a custom template tag or filter to workaround the limitation. Playing with Context objects Most of the time, you’ll instantiate Context objects by passing in a fully-populated dictionary to Context(). But you can add and delete items from a Context object once it’s been instantiated, too, using standard dictionary syntax: >>> from django.template import Context >>> c = Context({"foo": "bar"}) >>> c['foo'] 'bar' >>> del c['foo'] >>> c['foo'] Traceback (most recent call last): ... KeyError: 'foo' >>> c['newvariable'] = 'hello' >>> c['newvariable'] 'hello'

    Context.get(key, otherwise=None) Returns the value for key if key is in the context, else returns otherwise. Context.setdefault(key, default=None) If key is in the context, returns its value. Otherwise inserts key with a value of default and returns default. Context.pop() Context.push() exception ContextPopException A Context object is a stack. That is, you can push() and pop() it. If you pop() too much, it’ll raise django. template.ContextPopException: >>> c = Context() >>> c['foo'] = 'first level' >>> c.push() {} >>> c['foo'] = 'second level' >>> c['foo'] 'second level' >>> c.pop() {'foo': 'second level'}

    1354

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    >>> c['foo'] 'first level' >>> c['foo'] = 'overwritten' >>> c['foo'] 'overwritten' >>> c.pop() Traceback (most recent call last): ... ContextPopException

    You can also use push() as a context manager to ensure a matching pop() is called. >>> c = Context() >>> c['foo'] = 'first level' >>> with c.push(): ... c['foo'] = 'second level' ... c['foo'] 'second level' >>> c['foo'] 'first level'

    All arguments passed to push() will be passed to the dict constructor used to build the new context level. >>> c = Context() >>> c['foo'] = 'first level' >>> with c.push(foo='second level'): ... c['foo'] 'second level' >>> c['foo'] 'first level'

    Context.update(other_dict) In addition to push() and pop(), the Context object also defines an update() method. This works like push() but takes a dictionary as an argument and pushes that dictionary onto the stack instead of an empty one. >>> c = Context() >>> c['foo'] = 'first level' >>> c.update({'foo': 'updated'}) {'foo': 'updated'} >>> c['foo'] 'updated' >>> c.pop() {'foo': 'updated'} >>> c['foo'] 'first level'

    Like push(), you can use update() as a context manager to ensure a matching pop() is called. >>> c = Context() >>> c['foo'] = 'first level' >>> with c.update({'foo': 'second level'}): ... c['foo'] 'second level' >>> c['foo'] 'first level'

    Using a Context as a stack comes in handy in some custom template tags.

    6.20. Templates

    1355

    Django Documentation, Release 2.1.dev20171226153947

    Context.flatten() Using flatten() method you can get whole Context stack as one dictionary including builtin variables. >>> c = Context() >>> c['foo'] = 'first level' >>> c.update({'bar': 'second level'}) {'bar': 'second level'} >>> c.flatten() {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second ˓→level'}

    A flatten() method is also internally used to make Context objects comparable. >>> c1 = Context() >>> c1['foo'] = 'first level' >>> c1['bar'] = 'second level' >>> c2 = Context() >>> c2.update({'bar': 'second level', 'foo': 'first level'}) {'foo': 'first level', 'bar': 'second level'} >>> c1 == c2 True

    Result from flatten() can be useful in unit tests to compare Context against dict: class ContextTest(unittest.TestCase): def test_against_dictionary(self): c1 = Context() c1['update'] = 'value' self.assertEqual(c1.flatten(), { 'True': True, 'None': None, 'False': False, 'update': 'value', })

    Using RequestContext class RequestContext(request, dict_=None, processors=None) Django comes with a special Context class, django.template.RequestContext, that acts slightly differently from the normal django.template.Context. The first difference is that it takes an HttpRequest as its first argument. For example: c = RequestContext(request, { 'foo': 'bar', })

    The second difference is that it automatically populates the context with a few variables, according to the engine’s context_processors configuration option. The context_processors option is a list of callables – called context processors – that take a request object as their argument and return a dictionary of items to be merged into the context. In the default generated settings file, the default template engine contains the following context processors: [ 'django.template.context_processors.debug',

    1356

    Chapter 6. API Reference

    Django Documentation, Release 2.1.dev20171226153947

    'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ]

    In addition to these, RequestContext always enables 'django.template.context_processors. csrf'. This is a security related context processor required by the admin and other contrib apps, and, in case of accidental misconfiguration, it is deliberately hardcoded in and cannot be turned off in the context_processors option. Each processor is applied in order. That means, if one processor adds a variable to the context and a second processor adds a variable with the same name, the second will override the first. The default processors are explained below. When context processors are applied Context processors are applied on top of context

    6.22.7 Form submission HTML form submission is a tricky area. There’s no guarantee that the submission will include encoding information, which means the framework might have to guess at the encoding of submitted , ... link="http://www.poynter.org/column.asp?id=31", ... description="A group Weblog by the sharpest minds in online media/journalism/ ˓→publishing.", ... language="en", ... ) >>> feed.add_item( ... title="Hello", ... link="http://www.holovaty.com/test/", ... description="Testing.", ... ) >>> with open('test.rss', 'w') as fp: ... feed.write(fp, 'utf-8')

    For simplifying the selection of a generator use feedgenerator.DefaultFeed which is currently Rss201rev2Feed For definitions of the different versions of RSS, see: diveintomark.org/archives/2004/02/04/incompatible-rss

    https://web.archive.org/web/20110718035220/http://

    get_tag_uri(url, date) Creates a TagURI. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id

    6.26. Django Utils

    1381

    Django Documentation, Release 2.1.dev20171226153947

    SyndicationFeed class SyndicationFeed Base class for all syndication feeds. Subclasses should provide write(). __init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs) Initialize the feed with the given dictionary of meta> is replaced with a tag to allow including lists inside help text. Read-only fields are wrapped in ... instead of

    ...

    to allow any kind of HTML as the field’s content. Changes due to the introduction of template-based widget rendering Some undocumented classes in django.forms.widgets are removed: • SubWidget • RendererMixin, ChoiceFieldRenderer, RadioFieldRenderer, CheckboxFieldRenderer • ChoiceInput, RadioChoiceInput, CheckboxChoiceInput The undocumented Select.render_option() method is removed. The Widget.format_output() method is removed. Use a custom widget template instead. Some widget values, such as options, are now localized if settings.USE_L10N=True. You could revert to the old behavior with custom widget templates that uses the localize template tag to turn off localization. django.template.backends.django.Template.render() prohibits non-dict context For compatibility with multiple template engines, django.template.backends.django.Template. render() (returned from high-level template loader APIs such as loader.get_template()) must receive a dictionary of context rather than Context or RequestContext. If you were passing either of the two classes, pass a dictionary instead – doing so is backwards-compatible with older versions of Django. Model state changes in migration operations To improve the speed of applying migrations, rendering of related models is delayed until an operation that needs them (e.g. RunPython). If you have a custom operation that works with model classes or model instances from the from_state argument in rather than type="text". • Conditional HTTP headers are now parsed and compared according to the RFC 7232 Conditional Requests specification rather than the older RFC 2616. • patch_response_headers() no longer adds a Last-Modified header. According to the RFC 7234#section-4.2.2, this header is useless alongside other caching headers that provide an explicit expiration time, e.g. Expires or Cache-Control. UpdateCacheMiddleware and add_never_cache_headers() call patch_response_headers() and therefore are also affected by this change. • In the admin templates,

    is replaced with a tag to allow including lists inside help text. • ConditionalGetMiddleware no longer sets the Date header as Web servers set that header. It also no longer sets the Content-Length header as this is now done by CommonMiddleware.

    9.1. Final releases

    1441

    Django Documentation, Release 2.1.dev20171226153947

    If you have a middleware that modifies a response’s content and appears before CommonMiddleware in the MIDDLEWARE or MIDDLEWARE_CLASSES settings, you must reorder your middleware so that responses aren’t modified after Content-Length is set, or have the response modifying middleware reset the Content-Length header. • get_model() and get_models() now raise AppRegistryNotReady if they’re called before models of all applications have been loaded. Previously they only required the target application’s models to be loaded and thus could return models without all their relations set up. If you need the old behavior of get_model(), set the require_ready argument to False. • The unused BaseCommand.can_import_settings attribute is removed. • The undocumented django.utils.functional.lazy_property is removed. • For consistency with non-multipart requests, MultiPartParser.parse() now leaves request.POST immutable. If you’re modifying that QueryDict, you must now first copy it, e.g. request.POST.copy(). • Support for cx_Oracle < 5.2 is removed. • Support for IPython < 1.0 is removed from the shell command. • The signature of private API Widget.build_attrs() changed from extra_attrs=None, **kwargs to base_attrs, extra_attrs=None. • File-like objects (e.g., StringIO and BytesIO) uploaded to an ImageField using the test client now require a name attribute with a value that passes the validate_image_file_extension validator. See the note in Client.post(). Features deprecated in 1.11 models.permalink() decorator Use django.urls.reverse() instead. For example: from django.db import models class MyModel(models.Model): ... @models.permalink def url(self): return ('guitarist_detail', [self.slug])

    becomes: from django.db import models from django.urls import reverse class MyModel(models.Model): ... def url(self): return reverse('guitarist_detail', args=[self.slug])

    Miscellaneous • contrib.auth’s login() and logout() function-based views are deprecated in favor of new class-based 1442

    Chapter 9. Release notes

    Django Documentation, Release 2.1.dev20171226153947

    views LoginView and LogoutView. • The unused extra_context parameter of contrib.auth.views.logout_then_login() is deprecated. • contrib.auth’s password_change(), password_change_done(), password_reset(), password_reset_done(), password_reset_confirm(), and password_reset_complete() function-based views are deprecated in favor of new class-based views PasswordChangeView, PasswordChangeDoneView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, and PasswordResetCompleteView. • django.test.runner.setup_)), ... ]

    9.1. Final releases

    1491

    Django Documentation, Release 2.1.dev20171226153947

    to: mysite/urls.py urlpatterns = [ url(r'^polls/', include('polls.urls')), ... ]

    # 'namespace="polls"' removed

    polls/urls.py app_name = 'polls' # added urlpatterns = [...]

    This change also means that the old way of including an AdminSite instance is deprecated. Instead, pass admin. site.urls directly to url(): urls.py from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]

    URL application namespace required if setting an instance namespace In the past, an instance namespace without an application namespace would serve the same purpose as the application namespace, but it was impossible to reverse the patterns if there was an application namespace with the same name. Includes that specify an instance namespace require that the included URLconf sets an application namespace. current_app parameter to contrib.auth views All views in django.contrib.auth.views have the following structure: def view(request, ..., current_app=None, ...): ... if current_app is not None: request.current_app = current_app return TemplateResponse(request, template_name, context)

    As of Django 1.8, current_app is set on the request object. For consistency, these views will require the caller to set current_app on the request instead of passing it in a separate argument. django.contrib.gis.geoip The django.contrib.gis.geoip2 module supersedes django.contrib.gis.geoip. The new module provides a similar API except that it doesn’t provide the legacy GeoIP-Python API compatibility methods.

    1492

    Chapter 9. Release notes

    Django Documentation, Release 2.1.dev20171226153947

    Miscellaneous • The weak argument to django.dispatch.signals.Signal.disconnect() has been deprecated as it has no effect. • The check_aggregate_support() method of django.db.backends.base. Base) >>> book.author = Author(name="John") >>> book.save() Traceback (most recent call last): ... ValueError: save() prohibited to prevent ) book.author = Author(name="John") book.author.save() book.save()

    >>> Book.objects.get(name="Django") >>> book.author >>>

    Now, an error will be raised to prevent ) Traceback (most recent call last): ... ValueError: Cannot assign "": "Author" instance isn't saved in the ˓→) >>> book = Book.objects.filter(author=book) Traceback (most recent call last): ... ValueError: Cannot query "": Must be "Author" instance.

    select_related() now checks given fields select_related() now validates that the given fields actually exist. Previously, nonexistent fields were silently ignored. Now, an error is raised:

    9.1. Final releases

    1517

    Django Documentation, Release 2.1.dev20171226153947

    >>> book = Book.objects.select_related('nonexistent_field') Traceback (most recent call last): ... FieldError: Invalid field name(s) given in select_related: 'nonexistent_field'

    The validation also makes sure that the given field is relational: >>> book = Book.objects.select_related('name') Traceback (most recent call last): ... FieldError: Non-relational field given in select_related: 'name'

    Default EmailField.max_length increased to 254 The old default 75 character max_length was not capable of storing all possible RFC3696/5321-compliant email addresses. In order to store all possible valid email addresses, the max_length has been increased to 254 characters. You will need to generate and apply ). • The ModelAdmin.get_object() method (private API) now takes a third argument named from_field in order to specify which field should match the provided object_id. • The ModelAdmin.response_delete() method now takes a second argument named obj_id which is the serialized identifier used to retrieve the object before deletion. Default autoescaping of functions in django.template.defaultfilters In order to make built-in template filters that output HTML “safe by default” when calling them in Python code, the following functions in django.template.defaultfilters have been changed to automatically escape their input value: • join • linebreaksbr • linebreaks_filter • linenumbers • unordered_list • urlize • urlizetrunc You can revert to the old behavior by specifying autoescape=False if you are passing trusted content. This change doesn’t have any effect when using the corresponding filters in templates.

    9.1. Final releases

    1521

    Django Documentation, Release 2.1.dev20171226153947

    Miscellaneous • connections.queries is now a read-only attribute. • >My Field:

    If you want to keep the current behavior of rendering label_tag without the label_suffix, instantiate the form label_suffix=''. You can also customize the label_suffix on a per-field basis using the new label_suffix parameter on label_tag(). Admin views _changelist_filters GET parameter To achieve preserving and restoring list view filters, admin views now pass around the _changelist_filters GET parameter. It’s important that you account for that change if you have custom admin templates or if your tests rely on the previous URLs. If you want to revert to the original behavior you can set the preserve_filters attribute to False.

    9.1. Final releases

    1585

    Django Documentation, Release 2.1.dev20171226153947

    django.contrib.auth password reset uses base 64 encoding of User PK Past versions of Django used base 36 encoding of the User primary key in the password reset views and URLs (django.contrib.auth.views.password_reset_confirm()). Base 36 encoding is sufficient if the user primary key is an integer, however, with the introduction of custom user models in Django 1.5, that assumption may no longer be true. django.contrib.auth.views.password_reset_confirm() has been modified to take a uidb64 parameter instead of uidb36. If you are reversing this view, for example in a custom password_reset_email. html template, be sure to update your code. A temporary shim for django.contrib.auth.views.password_reset_confirm() that will allow password reset links generated prior to Django 1.6 to continue to work has been added to provide backwards compatibility; this will be removed in Django 1.7. Thus, as long as your site has been running Django 1.6 for more than PASSWORD_RESET_TIMEOUT_DAYS, this change will have no effect. If not (for example, if you upgrade directly from Django 1.5 to Django 1.7), then any password reset links generated before you upgrade to Django 1.7 or later won’t work after the upgrade. In addition, if you have any custom password reset URLs, you will need to update them by replacing uidb36 with uidb64 and the dash that follows that pattern with a slash. Also add _\- to the list of characters that may match the uidb64 pattern. For example: url(r'^reset/(?P[0-9A-Za-z]+)-(?P.+)/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'),

    becomes: url(r'^reset/(?P[0-9A-Za-z_\-]+)/(?P.+)/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'),

    You may also want to add the shim to support the old style reset links. Using the example above, you would modify the existing url by replacing django.contrib.auth.views.password_reset_confirm with django. contrib.auth.views.password_reset_confirm_uidb36 and also remove the name argument so it doesn’t conflict with the new url: url(r'^reset/(?P[0-9A-Za-z]+)-(?P.+)/$', 'django.contrib.auth.views.password_reset_confirm_uidb36'),

    You can remove this URL pattern PASSWORD_RESET_TIMEOUT_DAYS.

    after

    your

    app

    has

    been

    deployed

    with

    Django

    1.6

    for

    Default session serialization switched to JSON Historically, django.contrib.sessions used pickle to serialize session {% endif %} >{{ message }}

    Template caching In previous versions of Django, every time you rendered a template, it would be reloaded from disk. In Django 1.2, you can use a cached template loader to load templates once, then cache the result for every subsequent render. This can lead to a significant performance improvement if your templates are broken into lots of smaller subtemplates (using the {% extends %} or {% include %} tags). As a side effect, it is now much easier to support non-Django template languages. Class-based template loaders As part of the changes made to introduce Template caching and following a general trend in Django, the template loaders API has been modified to use template loading mechanisms that are encapsulated in Python classes as opposed to functions, the only method available until Django 1.1. All the template loaders shipped with Django have been ported to the new API but they still implement the functionbased API and the template core machinery still accepts function-based loaders (builtin or third party) so there is no immediate need to modify your TEMPLATE_LOADERS setting in existing projects, things will keep working if you leave it untouched up to and including the Django 1.3 release. If you have developed your own custom template loaders we suggest to consider porting them to a class-based implementation because the code for backwards compatibility with function-based loaders starts its deprecation process in Django 1.2 and will be removed in Django 1.4. There is a description of the API these loader classes must implement in the template API reference and you can also examine the source code of the loaders shipped with Django. Natural keys in fixtures Fixtures can now refer to remote objects using Natural keys. This lookup scheme is an alternative to the normal primary-key based object references in a fixture, improving readability and resolving problems referring to objects whose primary key value may not be predictable or known. 9.1. Final releases

    1663

    Django Documentation, Release 2.1.dev20171226153947

    Fast failure for tests Both the test subcommand of django-admin.py and the runtests.py script used to run Django’s own test suite now support a --failfast option. When specified, this option causes the test runner to exit after encountering a failure instead of continuing with the test run. In addition, the handling of Ctrl-C during a test run has been improved to trigger a graceful exit from the test run that reports details of the tests that were run before the interruption. BigIntegerField Models can now use a 64-bit BigIntegerField type. Improved localization Django’s internationalization framework has been expanded with locale-aware formatting and form processing. That means, if enabled, dates and numbers on templates will be displayed using the format specified for the current locale. Django will also use localized formats when parsing > – and visible fields on the form, respectively. • The redirect_to generic view now accepts an additional keyword argument permanent. If permanent is True, the view will emit an HTTP permanent redirect (status code 301). If False, the view will emit an HTTP temporary redirect (status code 302). • A new , ˓→parent_link=True) value = models.IntegerField()

    This bug will be fixed in the next release of Django.

    9.1. Final releases

    1701

    Django Documentation, Release 2.1.dev20171226153947

    Caveats with support of certain $ export LC_ALL="en_US.UTF-8"

    Run the locale command to confirm the change. Optionally, add those export commands to your shell’s startup file (e.g. ~/.bashrc for Bash) to avoid having to retype them. Tests that only fail in combination In case a test passes when run in isolation but fails within the whole suite, we have some tools to help analyze the problem. The --bisect option of runtests.py will run the failing test while halving the test set it is run together with on each iteration, often making it possible to identify a small number of tests that may be related to the failure. For example, suppose that the failing test that works on its own is ModelTest.test_eq, then using: $ ./runtests.py --bisect basic.tests.ModelTest.test_eq

    will try to determine a test that interferes with the given one. First, the test is run with the first half of the test suite. If a failure occurs, the first half of the test suite is split in two groups and each group is then run with the specified test. If there is no failure with the first half of the test suite, the second half of the test suite is run with the specified test and split appropriately as described earlier. The process repeats until the set of failing tests is minimized. The --pair option runs the given test alongside every other test from the suite, letting you check if another test has side-effects that cause the failure. So: $ ./runtests.py --pair basic.tests.ModelTest.test_eq

    will pair test_eq with every test label. With both --bisect and --pair, if you already suspect which cases might be responsible for the failure, you may limit tests to be cross-analyzed by specifying further test labels after the first one: $ ./runtests.py --pair basic.tests.ModelTest.test_eq queries transactions

    You can also try running any set of tests in reverse using the --reverse option in order to verify that executing tests in a different order does not cause any trouble:

    1744

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    $ ./runtests.py basic --reverse

    Seeing the SQL queries run during a test If you wish to examine the SQL being run in failing tests, you can turn on SQL logging using the --debug-sql option. If you combine this with --verbosity=2, all SQL queries will be output: $ ./runtests.py basic --debug-sql

    Seeing the full traceback of a test failure By default tests are run in parallel with one process per core. When the tests are run in parallel, however, you’ll only see a truncated traceback for any test failures. You can adjust this behavior with the --parallel option: $ ./runtests.py basic --parallel=1

    You can also use the DJANGO_TEST_PROCESSES environment variable for this purpose. Tips for writing tests Isolating model registration To avoid polluting the global apps registry and prevent unnecessary table creation, models defined in a test method should be bound to a temporary Apps instance: from django.apps.registry import Apps from django.db import models from django.test import SimpleTestCase class TestModelDefinition(SimpleTestCase): def test_model_definition(self): test_apps = Apps(['app_label']) class TestModel(models.Model): class Meta: apps = test_apps ...

    django.test.utils.isolate_apps(*app_labels, attr_name=None, kwarg_name=None) Since this pattern involves a lot of boilerplate, Django provides the isolate_apps() decorator. It’s used like this: from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps class TestModelDefinition(SimpleTestCase): @isolate_apps('app_label') def test_model_definition(self): class TestModel(models.Model): pass ...

    10.1. Contributing to Django

    1745

    Django Documentation, Release 2.1.dev20171226153947

    Setting app_label Models defined in a test method with no explicit app_label are automatically assigned the label of the app in which their test class is located. In order to make sure the models defined within the context of isolate_apps() instances are correctly installed, you should pass the set of targeted app_label as arguments: tests/app_label/tests.py from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps class TestModelDefinition(SimpleTestCase): @isolate_apps('app_label', 'other_app_label') def test_model_definition(self): # This model automatically receives app_label='app_label' class TestModel(models.Model): pass class OtherAppModel(models.Model): class Meta: app_label = 'other_app_label' ...

    The decorator can also be applied to classes: from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps('app_label') class TestModelDefinition(SimpleTestCase): def test_model_definition(self): class TestModel(models.Model): pass ...

    The temporary Apps instance used to isolate model registration can be retrieved as an attribute when used as a class decorator by using the attr_name parameter: from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps('app_label', attr_name='apps') class TestModelDefinition(SimpleTestCase): def test_model_definition(self): class TestModel(models.Model): pass self.assertIs(self.apps.get_model('app_label', 'TestModel'), TestModel)

    Or as an argument on the test method when used as a method decorator by using the kwarg_name parameter: from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps

    1746

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    class TestModelDefinition(SimpleTestCase): @isolate_apps('app_label', kwarg_name='apps') def test_model_definition(self, apps): class TestModel(models.Model): pass self.assertIs(apps.get_model('app_label', 'TestModel'), TestModel)

    Submitting patches We’re always grateful for patches to Django’s code. Indeed, bug reports with associated patches will get fixed far more quickly than those without patches. Typo fixes and trivial documentation changes If you are fixing a really trivial issue, for example changing a word in the documentation, the preferred way to provide the patch is using GitHub pull requests without a Trac ticket. See the Working with Git and GitHub for more details on how to use pull requests. “Claiming” tickets In an open-source project with hundreds of contributors around the world, it’s important to manage communication efficiently so that work doesn’t get duplicated and contributors can be as effective as possible. Hence, our policy is for contributors to “claim” tickets in order to let other developers know that a particular bug or feature is being worked on. If you have identified a contribution you want to make and you’re capable of fixing it (as measured by your coding ability, knowledge of Django internals and time availability), claim it by following these steps: • Login using your GitHub account or create an account in our ticket system. If you have an account but have forgotten your password, you can reset it using the password reset page. • If a ticket for this issue doesn’t exist yet, create one in our ticket tracker. • If a ticket for this issue already exists, make sure nobody else has claimed it. To do this, look at the “Owned by” section of the ticket. If it’s assigned to “nobody,” then it’s available to be claimed. Otherwise, somebody else may be working on this ticket. Either find another bug/feature to work on, or contact the developer working on the ticket to offer your help. If a ticket has been assigned for weeks or months without any activity, it’s probably safe to reassign it to yourself. • Log into your account, if you haven’t already, by clicking “GitHub Login” or “DjangoProject Login” in the upper left of the ticket page. • Claim the ticket by clicking the “assign to myself” radio button under “Action” near the bottom of the page, then click “Submit changes.” Note: The Django software foundation requests that anyone contributing more than a trivial patch to Django sign and submit a Contributor License Agreement, this ensures that the Django Software Foundation has clear license to all contributions allowing for a clear license for all users.

    10.1. Contributing to Django

    1747

    Django Documentation, Release 2.1.dev20171226153947

    Ticket claimers’ responsibility Once you’ve claimed a ticket, you have a responsibility to work on that ticket in a reasonably timely fashion. If you don’t have time to work on it, either unclaim it or don’t claim it in the first place! If there’s no sign of progress on a particular claimed ticket for a week or two, another developer may ask you to relinquish the ticket claim so that it’s no longer monopolized and somebody else can claim it. If you’ve claimed a ticket and it’s taking a long time (days or weeks) to code, keep everybody updated by posting comments on the ticket. If you don’t provide regular updates, and you don’t respond to a request for a progress report, your claim on the ticket may be revoked. As always, more communication is better than less communication! Which tickets should be claimed? Of course, going through the steps of claiming tickets is overkill in some cases. In the case of small changes, such as typos in the documentation or small bugs that will only take a few minutes to fix, you don’t need to jump through the hoops of claiming tickets. Just submit your patch and be done with it. Of course, it is always acceptable, regardless whether someone has claimed it or not, to submit patches to a ticket if you happen to have a patch ready. Patch style Make sure that any contribution you do fulfills at least the following requirements: • The code required to fix a problem or add a feature is an essential part of a patch, but it is not the only part. A good patch should also include a regression test to validate the behavior that has been fixed and to prevent the problem from arising again. Also, if some tickets are relevant to the code that you’ve written, mention the ticket numbers in some comments in the test so that one can easily trace back the relevant discussions after your patch gets committed, and the tickets get closed. • If the code associated with a patch adds a new feature, or modifies behavior of an existing feature, the patch should also contain documentation. When you think your work is ready to be reviewed, send a GitHub pull request. Please review the patch yourself using our patch review checklist first. If you can’t send a pull request for some reason, you can also use patches in Trac. When using this style, follow these guidelines. • Submit patches in the format returned by the git diff command. • Attach patches to a ticket in the ticket tracker, using the “attach file” button. Please don’t put the patch in the ticket description or comment unless it’s a single line patch. • Name the patch file with a .diff extension; this will let the ticket tracker apply correct syntax highlighting, which is quite helpful. Regardless of the way you submit your work, follow these steps. • Make sure your code fulfills the requirements in our patch review checklist. • Check the “Has patch” box on the ticket and make sure the “Needs documentation”, “Needs tests”, and “Patch needs improvement” boxes aren’t checked. This makes the ticket appear in the “Patches needing review” queue on the Development dashboard.

    1748

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    Non-trivial patches A “non-trivial” patch is one that is more than a simple bug fix. It’s a patch that introduces Django functionality and makes some sort of design decision. If you provide a non-trivial patch, include evidence that alternatives have been discussed on django-developers. If you’re not sure whether your patch should be considered non-trivial, just ask. Deprecating a feature There are a couple reasons that code in Django might be deprecated: • If a feature has been improved or modified in a backwards-incompatible way, the old feature or behavior will be deprecated. • Sometimes Django will include a backport of a Python library that’s not included in a version of Python that Django currently supports. When Django no longer needs to support the older version of Python that doesn’t include the library, the library will be deprecated in Django. As the deprecation policy describes, the first release of Django that deprecates a feature (A.B) should raise a RemovedInDjangoXXWarning (where XX is the Django version where the feature will be removed) when the deprecated feature is invoked. Assuming we have good test coverage, these warnings are converted to errors when running the test suite with warnings enabled: python -Wall runtests.py. Thus, when adding a RemovedInDjangoXXWarning you need to eliminate or silence any warnings generated when running the tests. The first step is to remove any use of the deprecated behavior by Django itself. Next you can silence warnings in tests that actually test the deprecated behavior by using the ignore_warnings decorator, either at the test or class level: 1. In a particular test: from django.test import ignore_warnings from django.utils.deprecation import RemovedInDjangoXXWarning @ignore_warnings(category=RemovedInDjangoXXWarning) def test_foo(self): ...

    2. For an entire test case: from django.test import ignore_warnings from django.utils.deprecation import RemovedInDjangoXXWarning @ignore_warnings(category=RemovedInDjangoXXWarning) class MyDeprecatedTests(unittest.TestCase): ...

    You can also add a test for the deprecation warning. You’ll have to disable the “warning as error” behavior in your test by doing: import warnings def test_foo_deprecation_warning(self): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('always') # prevent warnings from appearing as errors # invoke deprecated behavior self.assertEqual(len(warns), 1)

    10.1. Contributing to Django

    1749

    Django Documentation, Release 2.1.dev20171226153947

    msg = str(warns[0].message) self.assertEqual(msg, 'Expected deprecation message')

    Finally, there are a couple of updates to Django’s documentation to make: 1. If the existing feature is documented, mark it deprecated in documentation using the .. deprecated:: A.B annotation. Include a short description and a note about the upgrade path if applicable. 2. Add a description of the deprecated behavior, and the upgrade path if applicable, to the current release notes (docs/releases/A.B.txt) under the “Features deprecated in A.B” heading. 3. Add an entry in the deprecation timeline (docs/internals/deprecation.txt) under the appropriate version describing what code will be removed. Once you have completed these steps, you are finished with the deprecation. RemovedInDjangoXXWarnings matching the new version are removed.

    In each feature release, all

    JavaScript patches For information on JavaScript patches, see the JavaScript patches documentation. Patch review checklist Use this checklist to review a pull request. If you are reviewing a pull request that is not your own and it passes all the criteria below, please set the “Triage Stage” on the corresponding Trac ticket to “Ready for checkin”. If you’ve left comments for improvement on the pull request, please tick the appropriate flags on the Trac ticket based on the results of your review: “Patch needs improvement”, “Needs documentation”, and/or “Needs tests”. As time and interest permits, committers do final reviews of “Ready for checkin” tickets and will either commit the patch or bump it back to “Accepted” if further works need to be done. If you’re looking to become a committer, doing thorough reviews of patches is a great way to earn trust. Looking for a patch to review? Check out the “Patches needing review” section of the Django Development Dashboard. Looking to get your patch reviewed? Ensure the Trac flags on the ticket are set so that the ticket appears in that queue. Documentation • Does the documentation build without any errors (make html, or make.bat html on Windows, from the docs directory)? • Does the documentation follow the writing style guidelines in Writing documentation? • Are there any spelling errors? Bugs • Is there a proper regression test (the test should fail before the fix is applied)? New Features • Are there tests to “exercise” all of the new code? • Is there a release note in docs/releases/A.B.txt?

    1750

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    • Is there documentation for the feature and is it annotated appropriately with .. versionadded:: or .. versionchanged:: A.B?

    A.B

    Deprecating a feature See the Deprecating a feature guide. All code changes • Does the coding style conform to our guidelines? Are there any flake8 errors? • If the change is backwards incompatible in any way, is there a note in the release notes (docs/releases/ A.B.txt)? • Is Django’s test suite passing? All tickets • Is the pull request a single squashed commit with a message that follows our commit message format? • Are you the patch author and a new contributor? Please add yourself to the AUTHORS file and submit a Contributor License Agreement. Working with Git and GitHub This section explains how the community can contribute code to Django via pull requests. If you’re interested in how committers handle them, see Committing code. Below, we are going to show how to create a GitHub pull request containing the changes for Trac ticket #xxxxx. By creating a fully-ready pull request, you will make the reviewer’s job easier, meaning that your work is more likely to be merged into Django. You could also upload a traditional patch to Trac, but it’s less practical for reviews. Installing Git Django uses Git for its source control. You can download Git, but it’s often easier to install with your operating system’s package manager. Django’s Git repository is hosted on GitHub, and it is recommended that you also work using GitHub. After installing Git, the first thing you should do is setup your name and email: $ git config --global user.name "Your Real Name" $ git config --global user.email "[email protected]"

    Note that user.name should be your real name, not your GitHub nick. GitHub should know the email you use in the user.email field, as this will be used to associate your commits with your GitHub account.

    10.1. Contributing to Django

    1751

    Django Documentation, Release 2.1.dev20171226153947

    Setting up local repository When you have created your GitHub account, with the nick “GitHub_nick”, and forked Django’s repository, create a local copy of your fork: git clone [email protected]:GitHub_nick/django.git

    This will create a new directory “django”, containing a clone of your GitHub repository. The rest of the git commands on this page need to be run within the cloned directory, so switch to it now: cd django

    Your GitHub repository will be called “origin” in Git. You should also setup django/django as an “upstream” remote (that is, tell git that the reference Django repository was the source of your fork of it): git remote add upstream [email protected]:django/django.git git fetch upstream

    You can add other remotes similarly, for example: git remote add akaariai [email protected]:akaariai/django.git

    Working on a ticket When working on a ticket, create a new branch for the work, and base that work on upstream/master: git checkout -b ticket_xxxxx upstream/master

    The -b flag creates a new branch for you locally. Don’t hesitate to create new branches even for the smallest things that’s what they are there for. If instead you were working for a fix on the 1.4 branch, you would do: git checkout -b ticket_xxxxx_1_4 upstream/stable/1.4.x

    Assume the work is carried on the ticket_xxxxx branch. Make some changes and commit them: git commit

    When writing the commit message, follow the commit message guidelines to ease the work of the committer. If you’re uncomfortable with English, try at least to describe precisely what the commit does. If you need to do additional work on your branch, commit as often as necessary: git commit -m 'Added two more tests for edge cases'

    Publishing work You can publish your work on GitHub just by doing: git push origin ticket_xxxxx

    1752

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    When you go to your GitHub page, you will notice a new branch has been created. If you are working on a Trac ticket, you should mention in the ticket that your work is available from branch ticket_xxxxx of your GitHub repo. Include a link to your branch. Note that the above branch is called a “topic branch” in Git parlance. You are free to rewrite the history of this branch, by using git rebase for example. Other people shouldn’t base their work on such a branch, because their clone would become corrupt when you edit commits. There are also “public branches”. These are branches other people are supposed to fork, so the history of these branches should never change. Good examples of public branches are the master and stable/A.B.x branches in the django/django repository. When you think your work is ready to be pulled into Django, you should create a pull request at GitHub. A good pull request means: • commits with one logical change in each, following the coding style, • well-formed messages for each commit: a summary line and then paragraphs wrapped at 72 characters thereafter – see the committing guidelines for more details, • documentation and tests, if needed – actually tests are always needed, except for documentation changes. The test suite must pass and the documentation must build without warnings. Once you have created your pull request, you should add a comment in the related Trac ticket explaining what you’ve done. In particular, you should note the environment in which you ran the tests, for instance: “all tests pass under SQLite and MySQL”. Pull requests at GitHub have only two states: open and closed. The committer who will deal with your pull request has only two options: merge it or close it. For this reason, it isn’t useful to make a pull request until the code is ready for merging – or sufficiently close that a committer will finish it himself. Rebasing branches In the example above, you created two commits, the “Fixed ticket_xxxxx” commit and “Added two more tests” commit. We do not want to have the entire history of your working process in your repository. Your commit “Added two more tests” would be unhelpful noise. Instead, we would rather only have one commit containing all your work. To rework the history of your branch you can squash the commits into one by using interactive rebase: git rebase -i HEAD~2

    The HEAD~2 above is shorthand for two latest commits. The above command will open an editor showing the two commits, prefixed with the word “pick”. Change “pick” on the second line to “squash” instead. This will keep the first commit, and squash the second commit into the first one. Save and quit the editor. A second editor window should open, so you can reword the commit message for the commit now that it includes both your steps. You can also use the “edit” option in rebase. This way you can change a single commit, for example to fix a typo in a docstring: git rebase -i HEAD~3 # Choose edit, pick, pick for the commits # Now you are able to rework the commit (use git add normally to add changes) # When finished, commit work with "--amend" and continue git commit --amend # Reword the commit message if needed

    10.1. Contributing to Django

    1753

    Django Documentation, Release 2.1.dev20171226153947

    git rebase --continue # The second and third commits should be applied.

    If your topic branch is already published at GitHub, for example if you’re making minor changes to take into account a review, you will need to force-push the changes: git push -f origin ticket_xxxxx

    Note that this will rewrite history of ticket_xxxxx - if you check the commit hashes before and after the operation at GitHub you will notice that the commit hashes do not match anymore. This is acceptable, as the branch is merely a topic branch, and nobody should be basing their work on it. After upstream has changed When upstream (django/django) has changed, you should rebase your work. To do this, use: git fetch upstream git rebase

    The work is automatically rebased using the branch you forked on, in the example case using upstream/master. The rebase command removes all your local commits temporarily, applies the upstream commits, and then applies your local commits again on the work. If there are merge conflicts, you will need to resolve them and then use git rebase --continue. At any point you can use git rebase --abort to return to the original state. Note that you want to rebase on upstream, not merge the upstream. The reason for this is that by rebasing, your commits will always be on top of the upstream’s work, not mixed in with the changes in the upstream. This way your branch will contain only commits related to its topic, which makes squashing easier. After review It is unusual to get any non-trivial amount of code into core without changes requested by reviewers. In this case, it is often a good idea to add the changes as one incremental commit to your work. This allows the reviewer to easily check what changes you have done. In this case, do the changes required by the reviewer. Commit as often as necessary. Before publishing the changes, rebase your work. If you added two commits, you would run: git rebase -i HEAD~2

    Squash the second commit into the first. Write a commit message along the lines of: Made changes asked in review by - Fixed whitespace errors in foobar - Reworded the docstring of bar()

    Finally, push your work back to your GitHub repository. Since you didn’t touch the public commits during the rebase, you should not need to force-push: git push origin ticket_xxxxx

    1754

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    Your pull request should now contain the new commit too. Note that the committer is likely to squash the review commit into the previous commit when committing the code. Working on a patch One of the ways that developers can contribute to Django is by reviewing patches. Those patches will typically exist as pull requests on GitHub and can be easily integrated into your local repository: git checkout -b pull_xxxxx upstream/master curl https://github.com/django/django/pull/xxxxx.patch | git am

    This will create a new branch and then apply the changes from the pull request to it. At this point you can run the tests or do anything else you need to do to investigate the quality of the patch. For more detail on working with pull requests see the guidelines for committers. Summary • Work on GitHub if you can. • Announce your work on the Trac ticket by linking to your GitHub branch. • When you have something ready, make a pull request. • Make your pull requests as good as you can. • When doing fixes to your work, use git rebase -i to squash the commits. • When upstream has changed, do git fetch upstream; git rebase. JavaScript While most of Django core is Python, the admin and gis contrib apps contain JavaScript code. Please follow these coding standards when writing JavaScript code for inclusion in Django. Code style • Please conform to the indentation style dictated in the .editorconfig file. We recommend using a text editor with EditorConfig support to avoid indentation and whitespace issues. Most of the JavaScript files use 4 spaces for indentation, but there are some exceptions. • When naming variables, use camelCase instead of underscore_case. Different JavaScript files sometimes use a different code style. Please try to conform to the code style of each file. • Use the JSHint code linter to check your code for bugs and style errors. JSHint will be run when you run the JavaScript tests. We also recommended installing a JSHint plugin in your text editor. • Where possible, write code that will work even if the page structure is later changed with JavaScript. For instance, when binding a click handler, use $('body').on('click', selector, func) instead of $(selector).click(func). This makes it easier for projects to extend Django’s default behavior with JavaScript.

    10.1. Contributing to Django

    1755

    Django Documentation, Release 2.1.dev20171226153947

    JavaScript patches Django’s admin system leverages the jQuery framework to increase the capabilities of the admin interface. In conjunction, there is an emphasis on admin JavaScript performance and minimizing overall admin media file size. Serving compressed or “minified” versions of JavaScript files is considered best practice in this regard. To that end, patches for JavaScript files should include both the original code for future development (e.g. foo.js), and a compressed version for production use (e.g. foo.min.js). Any links to the file in the codebase should point to the compressed version. Compressing JavaScript To simplify the process of providing optimized JavaScript code, Django includes a handy Python script which should be used to create a “minified” version. To run it: $ pip install closure $ python django/contrib/admin/bin/compress.py

    Behind the scenes, compress.py is a front-end for Google’s Closure Compiler which is written in Java. The Closure Compiler library is not bundled with Django, but you can install it using pip as done above. The Closure Compiler library requires Java 7 or higher. Please don’t forget to run compress.py and include the diff of the minified scripts when submitting patches for Django’s JavaScript. JavaScript tests Django’s JavaScript tests can be run in a browser or from the command line. The tests are located in a top level js_tests directory. Writing tests Django’s JavaScript tests use QUnit. Here is an example test module: QUnit.module('magicTricks', { beforeEach: function() { var $ = django.jQuery; $('#qunit-fixture').append(''); } }); QUnit.test('removeOnClick removes button on click', function(assert) { var $ = django.jQuery; removeOnClick('.button'); assert.equal($('.button').length, 1); $('.button').click(); assert.equal($('.button').length, 0); }); QUnit.test('copyOnClick adds button on click', function(assert) { var $ = django.jQuery; copyOnClick('.button'); assert.equal($('.button').length, 1); $('.button').click();

    1756

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    assert.equal($('.button').length, 2); });

    Please consult the QUnit documentation for information on the types of assertions supported by QUnit. Running tests The JavaScript tests may be run from a web browser or from the command line. Testing from a web browser To run the tests from a web browser, open up js_tests/tests.html in your browser. To measure code coverage when running the tests, you need to view that file over HTTP. To view code coverage: • Execute python -m http.server from the root directory (not from inside js_tests). • Open http://localhost:8000/js_tests/tests.html in your web browser. Testing from the command line To run the tests from the command line, you need to have Node.js installed. After installing Node.js, install the JavaScript test dependencies by running the following from the root of your Django checkout: $ npm install

    Then run the tests with: $ npm test

    10.1.5 Writing documentation We place a high importance on consistency and readability of documentation. After all, Django was created in a journalism environment! So we treat our documentation like we treat our code: we aim to improve it as often as possible. Documentation changes generally come in two forms: • General improvements: typo corrections, error fixes and better explanations through clearer writing and more examples. • New features: documentation of features that have been added to the framework since the last release. This section explains how writers can craft their documentation changes in the most useful and least error-prone ways. Getting the raw documentation Though Django’s documentation is intended to be read as HTML at https://docs.djangoproject.com/, we edit it as a collection of text files for maximum flexibility. These files live in the top-level docs/ directory of a Django release. If you’d like to start contributing to our docs, get the development version of Django from the source code repository (see Installing the development version). The development version has the latest-and-greatest documentation, just 10.1. Contributing to Django

    1757

    Django Documentation, Release 2.1.dev20171226153947

    as it has latest-and-greatest code. We also backport documentation fixes and improvements, at the discretion of the committer, to the last release branch. That’s because it’s highly advantageous to have the docs for the last release be up-to-date and correct (see Differences between versions). Getting started with Sphinx Django’s documentation uses the Sphinx documentation system, which in turn is based on docutils. The basic idea is that lightly-formatted plain-text documentation is transformed into HTML, PDF, and any other output format. To actually build the documentation locally, you’ll currently need to install Sphinx – pip install Sphinx should do the trick. Then, building the HTML is easy; just make html (or make.bat html on Windows) from the docs directory. To get started contributing, you’ll want to read the reStructuredText Primer. After that, you’ll want to read about the Sphinx-specific markup that’s used to manage meta 1.5.1

    You can check your work by running git tag --verify . 8. Push your work, including the tag: git push --tags. 9. Make sure you have an absolutely clean tree by running git clean -dfx. 10. Run make -f extras/Makefile to generate the release packages. This will create the release packages in a dist/ directory. 11. Generate the hashes of the release packages: $ $ $ $

    cd dist md5sum * sha1sum * sha256sum *

    12. Create a “checksums” file, Django-.checksum.txt containing the hashes and release information. Start with this template and insert the correct version, date, GPG key ID (from gpg --list-keys --keyid-format LONG), release URL, and checksums:

    10.8. How is Django Formed?

    1797

    Django Documentation, Release 2.1.dev20171226153947

    This file contains MD5, SHA1, and SHA256 checksums for the source-code tarball and wheel files of Django , released . To use this file, you will need a working install of PGP or other compatible public-key encryption software. You will also need to have the Django release manager's public key in your keyring; this key has the ID ``XXXXXXXXXXXXXXXX`` and can be imported from the MIT keyserver. For example, if using the open-source GNU Privacy Guard implementation of PGP: gpg --keyserver pgp.mit.edu --recv-key XXXXXXXXXXXXXXXX Once the key is imported, verify this file:: gpg --verify Once you have verified this file, you can use normal MD5, SHA1, or SHA256 checksumming applications to generate the checksums of the Django package and compare them to the checksums listed below. Release packages: ================= https://www.djangoproject.com/m/releases/ https://www.djangoproject.com/m/releases/ MD5 checksums: ==============



    SHA1 checksums: ===============



    SHA256 checksums: =================



    13. Sign the checksum file (gpg --clearsign --digest-algo SHA256 Django-. checksum.txt). This generates a signed document, Django-.checksum.txt.asc which you can then verify using gpg --verify Django-.checksum.txt.asc. If you’re issuing multiple releases, repeat these steps for each release.

    10.8.6 Making the release(s) available to the public Now you’re ready to actually put the release out there. To do this: 1. Upload the release package(s) to the djangoproject server, replacing A.B. with the appropriate version number, e.g. 1.5 for a 1.5.x release:

    1798

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    $ scp Django-* djangoproject.com:/home/www/www/media/releases/A.B

    2. Upload the checksum file(s): $ scp Django-A.B.C.checksum.txt.asc djangoproject.com:/home/www/www/media/pgp/ ˓→Django-A.B.C.checksum.txt

    3. Test that the release packages install correctly using easy_install and pip. Here’s one method (which requires virtualenvwrapper): $ RELEASE_VERSION='1.7.2' $ MAJOR_VERSION=`echo $RELEASE_VERSION| cut -c 1-3` $ mktmpenv $ easy_install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django˓→$RELEASE_VERSION.tar.gz $ deactivate $ mktmpenv $ pip install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django˓→$RELEASE_VERSION.tar.gz $ deactivate $ mktmpenv $ pip install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django˓→$RELEASE_VERSION-py3-none-any.whl $ deactivate

    This just tests that the tarballs are available (i.e. redirects are up) and that they install correctly, but it’ll catch silly mistakes. 4. Ask a few people on IRC to verify the checksums by visiting the checksums file (e.g. https://www.djangoproject. com/m/pgp/Django-1.5b1.checksum.txt) and following the instructions in it. For bonus points, they can also unpack the downloaded release tarball and verify that its contents appear to be correct (proper version numbers, no stray .pyc or other undesirable files). 5. Upload the release packages to PyPI (for pre-releases, only upload the wheel file): $ twine upload -s dist/*

    6. Go to the Add release page in the admin, enter the new release number exactly as it appears in the name of the tarball (Django-.tar.gz). So for example enter “1.5.1” or “1.4c2”, etc. If the release is part of an LTS branch, mark it so. 7. Make the blog post announcing the release live. 8. For a new version release (e.g. 1.5, 1.6), update the default stable version of the docs by flipping the is_default flag to True on the appropriate DocumentRelease object in the docs.djangoproject. com database (this will automatically flip it to False for all others); you can do this using the site’s admin. Create new DocumentRelease objects for each language that has an entry for the previous release. Update djangoproject.com’s robots.docs.txt file by copying entries from the previous release. 9. Post the release announcement to the django-announce, django-developers, and django-users mailing lists. This should include a link to the announcement blog post. If this is a security release, also include [email protected]. 10. Add a link to the blog post in the topic of the #django IRC channel: /msg chanserv TOPIC #django new topic goes here.

    10.8. How is Django Formed?

    1799

    Django Documentation, Release 2.1.dev20171226153947

    10.8.7 Post-release You’re almost done! All that’s left to do now is: 1. Update the VERSION tuple in django/__init__.py again, incrementing to whatever the next expected release will be. For example, after releasing 1.5.1, update VERSION to VERSION = (1, 5, 2, 'alpha', 0). 2. Add the release in Trac’s versions list if necessary (and make it the default if it’s a final release). Not all versions are declared; take example on previous releases. 3. If this was a security release, update Archive of security issues with details of the issues addressed.

    10.8.8 New stable branch tasks There are several items to do in the time following the creation of a new stable branch (often following an alpha release). Some of these tasks don’t need to be done by the releaser. 1. Create a new DocumentRelease object in the docs.djangoproject.com database for the new version’s docs, and update the docs/fixtures/doc_releases.json JSON fixture, so people without access to the production DB can still run an up-to-date copy of the docs site. 2. Create a stub release note for the new feature version. Use the stub from the previous feature release version or copy the contents from the previous feature version and delete most of the contents leaving only the headings. 3. Increase the default PBKDF2 iterations in django.contrib.auth.hashers. PBKDF2PasswordHasher by about 20% (pick a round number). Run the tests, and update the 3 failing hasher tests with the new values. Make sure this gets noted in the release notes (see the 1.8 release notes for an example). 4. Remove features that have reached the end of their deprecation cycle. Each removal should be done in a separate commit for clarity. In the commit message, add a “refs #XXXX” to the original ticket where the deprecation began if possible. 5. Remove .. versionadded::, .. versionadded::, and .. deprecated:: annotations in the documentation from two releases ago. For example, in Django 1.9, notes for 1.7 will be removed. 6. Add the new branch to Read the Docs. Since the automatically generated version names (“stable-A.B.x”) differ from the version numbers we’ve used historically in Read the Docs (“A.B.x”), we currently ask Eric Holscher to add the version for us. Someday the alias functionality may be built-in to the Read the Docs UI.

    10.8.9 Notes on setting the VERSION tuple Django’s version reporting is controlled by the VERSION tuple in django/__init__.py. This is a five-element tuple, whose elements are: 1. Major version. 2. Minor version. 3. Micro version. 4. Status – can be one of “alpha”, “beta”, “rc” or “final”. 5. Series number, for alpha/beta/RC packages which run in sequence (allowing, for example, “beta 1”, “beta 2”, etc.). For a final release, the status is always “final” and the series number is always 0. A series number of 0 with an “alpha” status will be reported as “pre-alpha”.

    1800

    Chapter 10. Django internals

    Django Documentation, Release 2.1.dev20171226153947

    Some examples: • (1, 2, 1, 'final', 0) → “1.2.1” • (1, 3, 0, 'alpha', 0) → “1.3 pre-alpha” • (1, 3, 0, 'beta', 2) → “1.3 beta 2”

    10.8. How is Django Formed?

    1801

    Django Documentation, Release 2.1.dev20171226153947

    1802

    Chapter 10. Django internals

    CHAPTER

    11

    Indices, glossary and tables

    • genindex • modindex • Glossary

    1803

    Django Documentation, Release 2.1.dev20171226153947

    1804

    Chapter 11. Indices, glossary and tables

    Python Module Index

    a

    django.contrib.gis.utils.ogrinspect, 871 django.contrib.humanize, 878 django.contrib.messages, 881 c django.contrib.messages.middleware, 1078 django.contrib.postgres, 887 django.conf.urls, 1376 django.contrib.postgres.aggregates, 888 django.conf.urls.i18n, 461 django.contrib.postgres.indexes, 908 django.contrib.admin, 692 django.contrib.postgres.validators, 915 django.contrib.admindocs, 699 django.contrib.redirects, 915 django.contrib.auth, 408 django.contrib.sessions, 214 django.contrib.auth.backends, 751 django.contrib.sessions.middleware, 1080 django.contrib.auth.forms, 380 django.contrib.sitemaps, 916 django.contrib.auth.hashers, 389 django.contrib.sites, 924 django.contrib.auth.middleware, 1080 django.contrib.auth.password_validation, django.contrib.sites.middleware, 1080 django.contrib.staticfiles, 931 389 django.contrib.syndication, 937 django.contrib.auth.signals, 750 django.core.checks, 528 django.contrib.auth.views, 373 django.core.exceptions, 1002 django.contrib.contenttypes, 753 django.core.files, 1006 django.contrib.contenttypes.admin, 758 django.core.files.storage, 1008 django.contrib.contenttypes.fields, 755 django.core.files.uploadedfile, 1011 django.contrib.contenttypes.forms, 758 django.core.files.uploadhandler, 1012 django.contrib.flatpages, 759 django.core.mail, 433 django.contrib.gis, 764 django.core.management, 535 django.contrib.gis.admin, 874 django.core.paginator, 497 django.contrib.gis.db.backends, 793 django.core.signals, 1299 django.contrib.gis.db.models, 789 django.contrib.gis.db.models.functions, django.core.signing, 430 django.core.validators, 1391 814 django.contrib.gis.feeds, 875 d django.contrib.gis.forms, 799 django.db, 84 django.contrib.gis.forms.widgets, 800 django.db.backends, 1300 django.contrib.gis.gdal, 839 django.db.backends.base.schema, 1243 django.contrib.gis.geoip2, 865 django.db.migrations, 309 django.contrib.gis.geos, 824 django.db.migrations.operations, 1082 django.contrib.gis.measure, 821 django.contrib.gis.serializers.geojson, django.db.models, 84 django.db.models.fields, 1089 872 django.db.models.fields.related, 1104 django.contrib.gis.utils, 868 django.db.models.functions, 1214 django.contrib.gis.utils.layermapping, django.db.models.indexes, 1115 868 django.apps, 623

    1805

    Django Documentation, Release 2.1.dev20171226153947

    django.db.models.lookups, 1191 django.db.models.options, 1116 django.db.models.signals, 1293 django.db.transaction, 146 django.dispatch, 524

    f django.forms, 1014 django.forms.fields, 1033 django.forms.formsets, 236 django.forms.models, 247 django.forms.renderers, 1054 django.forms.widgets, 1056

    h django.http, 1229

    m

    django.utils.http, 1386 django.utils.log, 487 django.utils.module_loading, 1387 django.utils.safestring, 1387 django.utils.text, 1388 django.utils.timezone, 1388 django.utils.translation, 443

    v django.views, 1396 django.views.decorators.cache, 201 django.views.decorators.csrf, 959 django.views.decorators.gzip, 201 django.views.decorators.http, 200 django.views.decorators.vary, 201 django.views.generic.dates, 651 django.views.i18n, 457

    django.middleware, 1076 django.middleware.cache, 1076 django.middleware.clickjacking, 1081 django.middleware.common, 1076 django.middleware.csrf, 1080 django.middleware.exception, 1076 django.middleware.gzip, 1077 django.middleware.http, 1077 django.middleware.locale, 1077 django.middleware.security, 1078

    s django.shortcuts, 205

    t django.template, 272 django.template.backends, 275 django.template.backends.django, 275 django.template.backends.jinja2, 276 django.template.loader, 273 django.template.response, 1363 django.test, 323 django.test.signals, 1299 django.test.utils, 360

    u django.urls, 1372 django.urls.conf, 1375 django.utils, 1378 django.utils.cache, 1378 django.utils.dateparse, 1379 django.utils.decorators, 1379 django.utils.encoding, 1380 django.utils.feedgenerator, 1381 django.utils.functional, 1383 django.utils.html, 1385 1806

    Python Module Index

    Index

    Symbols –add-location [{full,file,never}] makemessages command line option, 986 –addrport ADDRPORT testserver command line option, 996 –admins sendtestemail command line option, 989 –all diffsettings command line option, 979 –all, -a dumpdata command line option, 980 makemessages command line option, 985 –app APP_LABEL loaddata command line option, 982 –backwards sqlmigrate command line option, 991 –blank BLANK ogrinspect command line option, 873 –check makemigrations command line option, 987 –clear, -c collectstatic command line option, 932 –command COMMAND, -c COMMAND shell command line option, 990 –database DATABASE changepassword command line option, 996 createcachetable command line option, 979 createsuperuser command line option, 997 dbshell command line option, 979 dumpdata command line option, 980 flush command line option, 981 inspectdb command line option, 982 loaddata command line option, 982 migrate command line option, 987 remove_stale_contenttypes command line 997 showmigrations command line option, 991 sqlflush command line option, 991 sqlmigrate command line option, 991

    sqlsequencereset command line option, 991 –debug-mode test command line option, 994 –debug-sql, -d test command line option, 994 –decimal DECIMAL ogrinspect command line option, 873 –default MODULE diffsettings command line option, 980 –deploy check command line option, 978 –domain DOMAIN, -d DOMAIN makemessages command line option, 985 –dry-run createcachetable command line option, 979 makemigrations command line option, 986 –dry-run, -n collectstatic command line option, 932 –email EMAIL createsuperuser command line option, 997 –empty makemigrations command line option, 986 –exclude EXCLUDE, -e EXCLUDE dumpdata command line option, 980 loaddata command line option, 982 –exclude EXCLUDE, -x EXCLUDE compilemessages command line option, 978 makemessages command line option, 985 –exclude-tag EXCLUDE_TAGS test command line option, 995 –extension EXTENSIONS, -e EXTENSIONS makemessages command line option, 985 startapp command line option, 992 startproject command line option, 993 –fail-level {CRITICAL,ERROR,WARNING,INFO,DEBUG} option, check command line option, 978 –failfast test command line option, 994 –fake migrate command line option, 987 1807

    Django Documentation, Release 2.1.dev20171226153947

    –fake-initial migrate command line option, 987 –format FORMAT dumpdata command line option, 980 loaddata command line option, 982 –geom-name GEOM_NAME ogrinspect command line option, 873 –ignore PATTERN, -i PATTERN collectstatic command line option, 932 makemessages command line option, 985 –ignorenonexistent, -i loaddata command line option, 982 –indent INDENT dumpdata command line option, 980 –insecure runserver command line option, 934 –interface {ipython,bpython,python}, {ipython,bpython,python} shell command line option, 990 –ipv6, -6 runserver command line option, 988 –keep-pot makemessages command line option, 986 –keepdb, -k test command line option, 994 –layer LAYER_KEY ogrinspect command line option, 873 –link, -l collectstatic command line option, 932 –list, -l showmigrations command line option, 990 –list-tags check command line option, 978 –locale LOCALE, -l LOCALE compilemessages command line option, 978 makemessages command line option, 985 –managers sendtestemail command line option, 989 –mapping ogrinspect command line option, 873 –merge makemigrations command line option, 987 –multi-geom ogrinspect command line option, 873 –name FILES, -n FILES startapp command line option, 992 startproject command line option, 993 –name NAME, -n NAME makemigrations command line option, 987 –name-field NAME_FIELD ogrinspect command line option, 873 –natural-foreign dumpdata command line option, 980 –natural-primary

    1808

    dumpdata command line option, 980 –no-color command line option, 999 –no-default-ignore collectstatic command line option, 932 makemessages command line option, 986 –no-imports ogrinspect command line option, 873 –no-location makemessages command line option, 986 –no-optimize squashmigrations command line option, 992 –no-post-process collectstatic command line option, 932 –no-wrap makemessages command line option, 986 -i –noinput, –no-input collectstatic command line option, 932 flush command line option, 981 makemigrations command line option, 986 migrate command line option, 987 squashmigrations command line option, 992 test command line option, 994 testserver command line option, 996 –noreload runserver command line option, 988 –nostartup shell command line option, 990 –nostatic runserver command line option, 933 –nothreading runserver command line option, 988 –null NULL ogrinspect command line option, 873 –output OUTPUT, -o OUTPUT dumpdata command line option, 981 –output {hash,unified} diffsettings command line option, 980 –parallel [N] test command line option, 994 –pks PRIMARY_KEYS dumpdata command line option, 981 –plan, -p showmigrations command line option, 990 –pythonpath PYTHONPATH command line option, 998 –reverse, -r test command line option, 994 –run-syncdb migrate command line option, 987 –settings SETTINGS command line option, 998 –squashed-name SQUASHED_NAME squashmigrations command line option, 992

    Index

    Django Documentation, Release 2.1.dev20171226153947

    –srid SRID ogrinspect command line option, 873 –symlinks, -s makemessages command line option, 985 –tag TAGS test command line option, 995 –tag TAGS, -t TAGS check command line option, 978 –template TEMPLATE startapp command line option, 992 startproject command line option, 993 –testrunner TESTRUNNER test command line option, 994 –traceback command line option, 998 –use-fuzzy, -f compilemessages command line option, 978 –username USERNAME createsuperuser command line option, 997 –verbosity {0,1,2,3}, -v {0,1,2,3} command line option, 999 __contains__() (QueryDict method), 1235 __contains__() (backends.base.SessionBase method), 216 __delitem__() (HttpResponse method), 1239 __delitem__() (backends.base.SessionBase method), 216 __eq__() (Model method), 1139 __getattr__() (Area method), 823 __getattr__() (Distance method), 823 __getitem__() (HttpResponse method), 1239 __getitem__() (OGRGeometry method), 846 __getitem__() (QueryDict method), 1235 __getitem__() (SpatialReference method), 852 __getitem__() (backends.base.SessionBase method), 216 __hash__() (Model method), 1140 __init__() (HttpResponse method), 1239 __init__() (QueryDict method), 1235 __init__() (SimpleTemplateResponse method), 1364 __init__() (SyndicationFeed method), 1382 __init__() (TemplateResponse method), 1365 __init__() (requests.RequestSite method), 930 __iter__() (File method), 1007 __iter__() (HttpRequest method), 1234 __iter__() (OGRGeometry method), 846 __len__() (OGRGeometry method), 846 __setitem__() (HttpResponse method), 1239 __setitem__() (QueryDict method), 1235 __setitem__() (backends.base.SessionBase method), 216 __str__() (Model method), 1139 _base_manager (Model attribute), 136 _default_manager (Model attribute), 136 _open() (in module django.core.files.storage), 573 _save() (in module django.core.files.storage), 573

    Index

    A A (class in django.contrib.gis.measure), 823 ABSOLUTE_URL_OVERRIDES setting, 1246 abstract (Options attribute), 1123 AccessMixin (class in django.contrib.auth.mixins), 372 action_flag (LogEntry attribute), 743 action_time (LogEntry attribute), 743 actions (ModelAdmin attribute), 704 actions_on_bottom (ModelAdmin attribute), 704 actions_on_top (ModelAdmin attribute), 704 actions_selection_counter (ModelAdmin attribute), 704 activate() (in module django.utils.timezone), 1389 activate() (in module django.utils.translation), 1390 add template filter, 1329 add() (GeometryCollection method), 851 add() (RelatedManager method), 1120 add_action() (AdminSite method), 697 add_arguments() (BaseCommand method), 539 add_arguments() (django.test.runner.DiscoverRunner class method), 359 add_error() (Form method), 1016 add_field() (BaseDatabaseSchemaEditor method), 1245 add_form_template (ModelAdmin attribute), 721 add_index() (BaseDatabaseSchemaEditor method), 1244 add_item() (SyndicationFeed method), 1382 add_item_elements() (SyndicationFeed method), 1382 add_message() (in module django.contrib.messages), 883 add_never_cache_headers() (in module django.utils.cache), 1378 add_post_render_callback() (SimpleTemplateResponse method), 1364 add_root_elements() (SyndicationFeed method), 1382 add_view() (ModelAdmin method), 729 AddField (class in django.db.migrations.operations), 1084 AddIndex (class in django.db.migrations.operations), 1084 addslashes template filter, 1329 AdminEmailHandler (class in django.utils.log), 495 AdminPasswordChangeForm (class in django.contrib.auth.forms), 380 ADMINS setting, 1246 AdminSite (class in django.contrib.admin), 739 Aggregate (class in django.db.models), 1198 aggregate() (in module django.db.models.query.QuerySet), 1174 all() (in module django.db.models.query.QuerySet), 1153 allow_database_queries (SimpleTestCase attribute), 337 allow_empty (BaseDateListView attribute), 674

    1809

    Django Documentation, Release 2.1.dev20171226153947

    allow_empty (django.views.generic.list.MultipleObjectMixinappendlist() (QueryDict method), 1236 attribute), 665 application namespace, 195 allow_files (FilePathField attribute), 1044, 1101 AppRegistryNotReady, 1002 allow_folders (FilePathField attribute), 1044, 1101 apps (in module django.apps), 627 allow_future (DateMixin attribute), 673 apps.AdminConfig (class in django.contrib.admin), 703 allow_migrate(), 157 apps.SimpleAdminConfig (class in allow_relation(), 157 django.contrib.admin), 703 allow_unicode (SlugField attribute), 1047, 1103 ArchiveIndexView (built-in class), 681 AllowAllUsersModelBackend (class in ArchiveIndexView (class in django.views.generic.dates), django.contrib.auth.backends), 752 652 AllowAllUsersRemoteUserBackend (class in Area (class in django.contrib.gis.db.models.functions), django.contrib.auth.backends), 752 814 ALLOWED_HOSTS Area (class in django.contrib.gis.measure), 823 setting, 1247 area (GEOSGeometry attribute), 832 alter_db_table() (BaseDatabaseSchemaEditor method), area (OGRGeometry attribute), 847 1245 arg_joiner (Func attribute), 1197 alter_db_tablespace() (BaseDatabaseSchemaEditor args (ResolverMatch attribute), 1373 method), 1245 arity (Func attribute), 1197 alter_field() (BaseDatabaseSchemaEditor method), 1245 ArrayAgg (class in django.contrib.postgres.aggregates), alter_index_together() (BaseDatabaseSchemaEditor 888 method), 1244 ArrayField (class in django.contrib.postgres.fields), 891 alter_unique_together() (BaseDatabaseSchemaEditor arrayfield.contained_by method), 1244 field lookup type, 893 AlterField (class in django.db.migrations.operations), arrayfield.contains 1084 field lookup type, 893 AlterIndexTogether (class in arrayfield.index django.db.migrations.operations), 1083 field lookup type, 894 AlterModelManagers (class in arrayfield.len django.db.migrations.operations), 1083 field lookup type, 893 AlterModelOptions (class in arrayfield.overlap django.db.migrations.operations), 1083 field lookup type, 893 AlterModelTable (class in arrayfield.slice django.db.migrations.operations), 1083 field lookup type, 894 AlterOrderWithRespectTo (class in as_data() (Form.errors method), 1015 django.db.migrations.operations), 1083 as_datetime() (Field method), 845 AlterUniqueTogether (class in as_double() (Field method), 845 django.db.migrations.operations), 1083 as_hidden() (BoundField method), 1029 angular_name (SpatialReference attribute), 854 as_int() (Field method), 845 angular_units (SpatialReference attribute), 854 as_json() (Form.errors method), 1016 annotate() (in module django.db.models.query.QuerySet), as_manager() (in module 1145 django.db.models.query.QuerySet), 1177 apnumber as_p() (Form method), 1021 template filter, 878 as_sql() (Func method), 1198 app_directories.Loader (class in as_sql() (in module django.db.models), 1192 django.template.loaders), 1360 as_string() (Field method), 845 app_index_template (AdminSite attribute), 740 as_table() (Form method), 1022 app_label (ContentType attribute), 753 as_ul() (Form method), 1021 app_label (Options attribute), 1123 as_vendorname() (in module django.db.models), 1192 app_name (ResolverMatch attribute), 1374 as_view() (django.views.generic.base.View class app_names (ResolverMatch attribute), 1374 method), 641 AppCommand (class in django.core.management), 539 as_widget() (BoundField method), 1029 AppConfig (class in django.apps), 625 asc() (Expression method), 1207 APPEND_SLASH AsGeoJSON (class in setting, 1247 django.contrib.gis.db.models.functions),

    1810

    Index

    Django Documentation, Release 2.1.dev20171226153947

    814 AsGML (class in django.contrib.gis.db.models.functions), 815 AsKML (class in django.contrib.gis.db.models.functions), 815 assertContains() (SimpleTestCase method), 347 assertFieldOutput() (SimpleTestCase method), 346 assertFormError() (SimpleTestCase method), 347 assertFormsetError() (SimpleTestCase method), 347 assertHTMLEqual() (SimpleTestCase method), 348 assertHTMLNotEqual() (SimpleTestCase method), 348 assertInHTML() (SimpleTestCase method), 349 assertJSONEqual() (SimpleTestCase method), 349 assertJSONNotEqual() (SimpleTestCase method), 349 assertNotContains() (SimpleTestCase method), 347 assertNumQueries() (TransactionTestCase method), 349 assertQuerysetEqual() (TransactionTestCase method), 349 assertRaisesMessage() (SimpleTestCase method), 346 assertRedirects() (SimpleTestCase method), 348 assertTemplateNotUsed() (SimpleTestCase method), 347 assertTemplateUsed() (SimpleTestCase method), 347 assertXMLEqual() (SimpleTestCase method), 348 assertXMLNotEqual() (SimpleTestCase method), 349 AsSVG (class in django.contrib.gis.db.models.functions), 816 Atom1Feed (class in django.utils.feedgenerator), 1383 atomic() (in module django.db.transaction), 147 attr_value() (SpatialReference method), 853 attrs (Widget attribute), 1059 auth() (in module django.contrib.auth.context_processors), 1357 auth_code() (SpatialReference method), 853 auth_name() (SpatialReference method), 853 AUTH_PASSWORD_VALIDATORS setting, 1283 AUTH_USER_MODEL setting, 1281 authenticate() (in module django.contrib.auth), 363 authenticate() (ModelBackend method), 751 authenticate() (RemoteUserBackend method), 752 AUTHENTICATION_BACKENDS setting, 1281 AuthenticationForm (class in django.contrib.auth.forms), 380 AuthenticationMiddleware (class in django.contrib.auth.middleware), 1080 auto_created (Field attribute), 1114 auto_id (BoundField attribute), 1028 auto_id (Form attribute), 1023 auto_now (DateField attribute), 1096 auto_now_add (DateField attribute), 1096 autocomplete_fields (ModelAdmin attribute), 718 autodiscover() (in module django.contrib.admin), 703

    Index

    autoescape template tag, 1311 AutoField (class in django.db.models), 1094 available_apps (TransactionTestCase attribute), 356 Avg (class in django.db.models), 1187 Azimuth (class in django.contrib.gis.db.models.functions), 816

    B backends.base.SessionBase (class in django.contrib.sessions), 216 backends.cached_db.SessionStore (class in django.contrib.sessions), 224 backends.db.SessionStore (class in django.contrib.sessions), 224 backends.smtp.EmailBackend (class in django.core.mail), 439 bands (GDALRaster attribute), 858 base36_to_int() (in module django.utils.http), 1386 base_field (ArrayField attribute), 891 base_field (django.contrib.postgres.forms.BaseRangeField attribute), 904 base_field (RangeField attribute), 903 base_field (SimpleArrayField attribute), 904 base_field (SplitArrayField attribute), 905 base_manager_name (Options attribute), 1123 base_session.AbstractBaseSession (class in django.contrib.sessions), 224 base_session.BaseSessionManager (class in django.contrib.sessions), 224 base_url (FileSystemStorage attribute), 1009 base_widget (RangeWidget attribute), 907 BaseArchiveIndexView (class in django.views.generic.dates), 661 BaseCommand (class in django.core.management), 538 BaseDatabaseSchemaEditor (class in django.db.backends.base.schema), 1243 BaseDateDetailView (class in django.views.generic.dates), 661 BaseDateListView (class in django.views.generic.dates), 673 BaseDayArchiveView (class in django.views.generic.dates), 661 BaseFormSet (class in django.forms.formsets), 236 BaseGenericInlineFormSet (class in django.contrib.contenttypes.forms), 758 BaseGeometryWidget (class in django.contrib.gis.forms.widgets), 801 BaseMonthArchiveView (class in django.views.generic.dates), 661 BaseTodayArchiveView (class in django.views.generic.dates), 661 BaseWeekArchiveView (class in django.views.generic.dates), 661 1811

    Django Documentation, Release 2.1.dev20171226153947

    BaseYearArchiveView (class in django.views.generic.dates), 661 bbcontains field lookup type, 802 bboverlaps field lookup type, 803 BigAutoField (class in django.db.models), 1095 BigIntegerField (class in django.db.models), 1095 BigIntegerRangeField (class in django.contrib.postgres.fields), 900 bilateral (Transform attribute), 1192 BinaryField (class in django.db.models), 1095 BitAnd (class in django.contrib.postgres.aggregates), 888 BitOr (class in django.contrib.postgres.aggregates), 888 blank (Field attribute), 1090 block template tag, 1311 blocktrans template tag, 452 body (HttpRequest attribute), 1230 BoolAnd (class in django.contrib.postgres.aggregates), 888 BooleanField (class in django.db.models), 1095 BooleanField (class in django.forms), 1039 BoolOr (class in django.contrib.postgres.aggregates), 888 boundary (GEOSGeometry attribute), 831 boundary() (OGRGeometry method), 849 BoundField (class in django.forms), 1027 BoundingCircle (class in django.contrib.gis.db.models.functions), 816 BrinIndex (class in django.contrib.postgres.indexes), 908 BrokenLinkEmailsMiddleware (class in django.middleware.common), 1076 BtreeGinExtension (class in django.contrib.postgres.operations), 910 BtreeGistExtension (class in django.contrib.postgres.operations), 910 buffer() (GEOSGeometry method), 830 build_absolute_uri() (HttpRequest method), 1233 build_suite() (DiscoverRunner method), 359 bulk_create() (in module django.db.models.query.QuerySet), 1170 byteorder (WKBWriter attribute), 837

    CACHE_MIDDLEWARE_KEY_PREFIX setting, 1249 CACHE_MIDDLEWARE_SECONDS setting, 1249 cached.Loader (class in django.template.loaders), 1361 cached_property (class in django.utils.functional), 1383 CACHES setting, 1247 CACHES-BACKEND setting, 1248 CACHES-KEY_FUNCTION setting, 1248 CACHES-KEY_PREFIX setting, 1248 CACHES-LOCATION setting, 1248 CACHES-OPTIONS setting, 1249 CACHES-TIMEOUT setting, 1249 CACHES-VERSION setting, 1249 CallbackFilter (class in django.utils.log), 496 callproc() (CursorWrapper method), 145 can_delete (BaseFormSet attribute), 243 can_delete (InlineModelAdmin attribute), 734 can_order (BaseFormSet attribute), 242 capfirst template filter, 1330 CASCADE (in module django.db.models), 1106 Case (class in django.db.models.expressions), 1211 Cast (class in django.db.models.functions), 1214 center template filter, 1330 Centroid (class in django.contrib.gis.db.models.functions), 816 centroid (GEOSGeometry attribute), 831 centroid (Polygon attribute), 850 change_form_template (ModelAdmin attribute), 721 change_list_template (ModelAdmin attribute), 721 change_message (LogEntry attribute), 744 change_view() (ModelAdmin method), 729 changed_data (Form attribute), 1018 changed_objects (models.BaseModelFormSet attribute), 260 C changefreq (Sitemap attribute), 919 changelist_view() (ModelAdmin method), 729 cache changepassword template tag, 418 django-admin command, 996 cache_control() (in module changepassword command line option django.views.decorators.cache), 201 –database DATABASE, 996 cache_key_prefix (backends.cached_db.SessionStore atCharField (class in django.db.models), 1095 tribute), 224 CharField (class in django.forms), 1039 CACHE_MIDDLEWARE_ALIAS charset (HttpResponse attribute), 1238 setting, 1249 1812

    Index

    Django Documentation, Release 2.1.dev20171226153947

    charset (UploadedFile attribute), 1011 check django-admin command, 978 check command line option –deploy, 978 –fail-level {CRITICAL,ERROR,WARNING,INFO,DEBUG}, 978 –list-tags, 978 –tag TAGS, -t TAGS, 978 check() (BaseCommand method), 539 check_for_language() (in module django.utils.translation), 1391 check_password() (in module django.contrib.auth.hashers), 389 check_password() (models.AbstractBaseUser method), 402 check_password() (models.User method), 748 check_test (CheckboxInput attribute), 1065 CheckboxInput (class in django.forms), 1065 CheckboxSelectMultiple (class in django.forms), 1067 CheckMessage (class in django.core.checks), 629 ChoiceField (class in django.forms), 1040 choices (ChoiceField attribute), 1040 choices (Field attribute), 1090 choices (MultipleHiddenInput attribute), 1068 choices (Select attribute), 1065 chunk_size (FileUploadHandler attribute), 1013 chunks() (File method), 1007 chunks() (UploadedFile method), 1011 CICharField (class in django.contrib.postgres.fields), 895 CIEmailField (class in django.contrib.postgres.fields), 895 CIText (class in django.contrib.postgres.fields), 895 CITextExtension (class in django.contrib.postgres.operations), 910 CITextField (class in django.contrib.postgres.fields), 895 city() (GeoIP2 method), 867 classes (InlineModelAdmin attribute), 733 clean() (Field method), 1033 clean() (Form method), 1015 clean() (Model method), 1134 clean() (models.AbstractBaseUser method), 401 clean() (models.AbstractUser method), 402 clean_fields() (Model method), 1133 clean_savepoints() (in module django.db.transaction), 153 clean_username() (RemoteUserBackend method), 752 cleaned_data (Form attribute), 1019 clear() (backends.base.SessionBase method), 217 clear() (RelatedManager method), 1122 clear_cache() (ContentTypeManager method), 755 clear_expired() (backends.base.SessionBase method), 218

    Index

    ClearableFileInput (class in django.forms), 1068 clearsessions django-admin command, 997 Client (class in django.test), 329 client (Response attribute), 333 client (SimpleTestCase attribute), 341 client.RedirectCycleError, 1006 client_class (SimpleTestCase attribute), 341 clone() (GEOSGeometry method), 832 clone() (OGRGeometry method), 848 clone() (SpatialReference method), 853 close() (FieldFile method), 1100 close() (File method), 1007 close_rings() (OGRGeometry method), 848 closed (HttpResponse attribute), 1238 closed (LineString attribute), 833 closed (MultiLineString attribute), 834 Coalesce (class in django.db.models.functions), 1214 code (EmailValidator attribute), 1393 code (ProhibitNullCharactersValidator attribute), 1396 code (RegexValidator attribute), 1393 codename (models.Permission attribute), 750 coerce (TypedChoiceField attribute), 1040 Collect (class in django.contrib.gis.db.models), 812 collectstatic django-admin command, 931 collectstatic command line option –clear, -c, 932 –dry-run, -n, 932 –ignore PATTERN, -i PATTERN, 932 –link, -l, 932 –no-default-ignore, 932 –no-post-process, 932 –noinput, –no-input, 932 color_interp() (GDALBand method), 861 ComboField (class in django.forms), 1048 command line option –no-color, 999 –pythonpath PYTHONPATH, 998 –settings SETTINGS, 998 –traceback, 998 –verbosity {0,1,2,3}, -v {0,1,2,3}, 999 CommandError, 540 comment template tag, 1311 commit() (in module django.db.transaction), 152 CommonMiddleware (class in django.middleware.common), 1076 CommonPasswordValidator (class in django.contrib.auth.password_validation), 391 compilemessages django-admin command, 978 compilemessages command line option

    1813

    Django Documentation, Release 2.1.dev20171226153947

    –exclude EXCLUDE, -x EXCLUDE, 978 convert_value() (Expression method), 1207 –locale LOCALE, -l LOCALE, 978 convex_hull (GEOSGeometry attribute), 831 –use-fuzzy, -f, 978 convex_hull (OGRGeometry attribute), 849 compress() (MultiValueField method), 1050 cookie_date() (in module django.utils.http), 1386 Concat (class in django.db.models.functions), 1225 cookies (Client attribute), 335 concrete (Field attribute), 1114 COOKIES (HttpRequest attribute), 1231 concrete model, 1407 coord_dim (OGRGeometry attribute), 846 condition (FilteredRelation attribute), 1190 coords (GEOSGeometry attribute), 827 condition() (in module django.views.decorators.http), 201 coords (OGRGeometry attribute), 850 conditional_escape() (in module django.utils.html), 1385 coords() (GeoIP2 method), 867 ConditionalGetMiddleware (class in CoordTransform (class in django.contrib.gis.gdal), 855 django.middleware.http), 1077 copy() (QueryDict method), 1236 configure_user() (RemoteUserBackend method), 752 Corr (class in django.contrib.postgres.aggregates), 889 confirm_login_allowed() (AuthenticationForm method), Count (class in django.db.models), 1187 380 count (Paginator attribute), 500 CONN_MAX_AGE count() (in module django.db.models.query.QuerySet), setting, 1253 1170 connect() (Signal method), 524 country() (GeoIP2 method), 867 connection (SchemaEditor attribute), 1246 country_code() (GeoIP2 method), 867 contained country_name() (GeoIP2 method), 867 field lookup type, 803 coupling contains loose, 1400 field lookup type, 1178 CovarPop (class in django.contrib.postgres.aggregates), contains() (GEOSGeometry method), 829 889 contains() (OGRGeometry method), 849 coveredby contains() (PreparedGeometry method), 835 field lookup type, 804 contains_aggregate (Expression attribute), 1206 covers contains_over_clause (Expression attribute), 1206 field lookup type, 804 contains_properly covers() (GEOSGeometry method), 829 field lookup type, 804 covers() (PreparedGeometry method), 835 contains_properly() (PreparedGeometry method), 835 create() (in module django.db.models.query.QuerySet), content (HttpResponse attribute), 1238 1167 content (Response attribute), 333 create() (RelatedManager method), 1121 content_params (HttpRequest attribute), 1230 create_model() (BaseDatabaseSchemaEditor method), content_type (django.views.generic.base.TemplateResponseMixin 1244 attribute), 662 create_model_instance() (backends.db.SessionStore content_type (HttpRequest attribute), 1230 method), 224 content_type (LogEntry attribute), 743 create_superuser() (models.CustomUserManager content_type (models.Permission attribute), 750 method), 402 content_type (UploadedFile attribute), 1011 create_superuser() (models.UserManager method), 749 content_type_extra (UploadedFile attribute), 1011 create_test_db() (in module ContentFile (class in django.core.files.base), 1007 django.db.connection.creation), 361 ContentType (class in create_unknown_user (RemoteUserBackend attribute), django.contrib.contenttypes.models), 753 752 ContentTypeManager (class in create_user() (models.CustomUserManager method), 402 django.contrib.contenttypes.models), 755 create_user() (models.UserManager method), 749 Context (class in django.template), 1351 createcachetable context (Response attribute), 333 django-admin command, 979 context_data (SimpleTemplateResponse attribute), 1363 createcachetable command line option context_object_name (django.views.generic.detail.SingleObjectMixin –database DATABASE, 979 attribute), 663 –dry-run, 979 context_object_name (django.views.generic.list.MultipleObjectMixin CreateExtension (class in attribute), 666 django.contrib.postgres.operations), 910 ContextPopException, 1354

    1814

    Index

    Django Documentation, Release 2.1.dev20171226153947

    CreateModel (class in django.db.migrations.operations), 1082 createsuperuser django-admin command, 996 createsuperuser command line option –database DATABASE, 997 –email EMAIL, 997 –username USERNAME, 997 CreateView (built-in class), 678 Critical (class in django.core.checks), 630 crosses field lookup type, 805 crosses() (GEOSGeometry method), 830 crosses() (OGRGeometry method), 849 crosses() (PreparedGeometry method), 835 CryptoExtension (class in django.contrib.postgres.operations), 910 CSRF_COOKIE_AGE setting, 1250 CSRF_COOKIE_DOMAIN setting, 1250 CSRF_COOKIE_HTTPONLY setting, 1250 CSRF_COOKIE_NAME setting, 1250 CSRF_COOKIE_PATH setting, 1251 CSRF_COOKIE_SECURE setting, 1251 csrf_exempt() (in module django.views.decorators.csrf), 961 CSRF_FAILURE_VIEW setting, 1251 CSRF_HEADER_NAME setting, 1251 csrf_protect() (in module django.views.decorators.csrf), 959 csrf_token template tag, 1311 CSRF_TRUSTED_ORIGINS setting, 1252 CSRF_USE_SESSIONS setting, 1251 CsrfViewMiddleware (class in django.middleware.csrf), 1080 css_classes() (BoundField method), 1029 ct_field (GenericInlineModelAdmin attribute), 759 ct_fk_field (GenericInlineModelAdmin attribute), 759 CumeDist (class in django.db.models.functions), 1227 current_app (HttpRequest attribute), 1232 CurrentSiteMiddleware (class in django.contrib.sites.middleware), 1080 cut template filter, 1330

    Index

    cycle template tag, 1311 cycle_key() (backends.base.SessionBase method), 218

    D D (class in django.contrib.gis.measure), 823 data (BoundField attribute), 1028 data() (GDALBand method), 861 DATA_UPLOAD_MAX_MEMORY_SIZE setting, 1258 DATA_UPLOAD_MAX_NUMBER_FIELDS setting, 1259 DATABASE-ATOMIC_REQUESTS setting, 1252 DATABASE-AUTOCOMMIT setting, 1253 DATABASE-DISABLE_SERVER_SIDE_CURSORS setting, 1254 DATABASE-ENGINE setting, 1253 DATABASE-TEST setting, 1255 DATABASE-TIME_ZONE setting, 1254 DATABASE_ROUTERS setting, 1259 DatabaseError, 1005 DATABASES setting, 1252 DataError, 1005 DATAFILE setting, 1257 DATAFILE_EXTSIZE setting, 1258 DATAFILE_MAXSIZE setting, 1257 DATAFILE_SIZE setting, 1258 DATAFILE_TMP setting, 1257 DATAFILE_TMP_EXTSIZE setting, 1258 DATAFILE_TMP_MAXSIZE setting, 1258 DATAFILE_TMP_SIZE setting, 1258 DataSource (class in django.contrib.gis.gdal), 840 datatype() (GDALBand method), 861 date field lookup type, 1181 template filter, 1330 date_attrs (SplitDateTimeWidget attribute), 1069 date_field (DateMixin attribute), 673 DATE_FORMAT 1815

    Django Documentation, Release 2.1.dev20171226153947

    setting, 1259 date_format (SplitDateTimeWidget attribute), 1068 date_hierarchy (ModelAdmin attribute), 704 DATE_INPUT_FORMATS setting, 1259 date_joined (models.User attribute), 747 date_list_period (BaseDateListView attribute), 674 DateDetailView (built-in class), 688 DateDetailView (class in django.views.generic.dates), 660 DateField (class in django.db.models), 1096 DateField (class in django.forms), 1041 DateInput (class in django.forms), 1064 DateMixin (class in django.views.generic.dates), 673 DateRangeField (class in django.contrib.postgres.fields), 900 DateRangeField (class in django.contrib.postgres.forms), 907 dates() (in module django.db.models.query.QuerySet), 1152 DATETIME_FORMAT setting, 1260 DATETIME_INPUT_FORMATS setting, 1260 DateTimeField (class in django.db.models), 1096 DateTimeField (class in django.forms), 1041 DateTimeInput (class in django.forms), 1064 DateTimeRangeField (class in django.contrib.postgres.fields), 900 DateTimeRangeField (class in django.contrib.postgres.forms), 907 datetimes() (in module django.db.models.query.QuerySet), 1152 day field lookup type, 1182 day (DayMixin attribute), 672 day_format (DayMixin attribute), 672 DayArchiveView (built-in class), 685 DayArchiveView (class in django.views.generic.dates), 657 DayMixin (class in django.views.generic.dates), 672 db (QuerySet attribute), 1144 db_column (Field attribute), 1091 db_constraint (ForeignKey attribute), 1108 db_constraint (ManyToManyField attribute), 1110 db_for_read(), 157 db_for_write(), 157 db_index (Field attribute), 1092 db_table (ManyToManyField attribute), 1110 db_table (Options attribute), 1123 db_tablespace (Field attribute), 1092 db_tablespace (Index attribute), 1116 db_tablespace (Options attribute), 1124 db_type() (Field method), 1112

    1816

    dbshell django-admin command, 979 dbshell command line option –database DATABASE, 979 deactivate() (in module django.utils.timezone), 1389 deactivate() (in module django.utils.translation), 1390 deactivate_all() (in module django.utils.translation), 1390 DEBUG setting, 1260 debug template tag, 1313 Debug (class in django.core.checks), 630 debug() (in module django.template.context_processors), 1358 DEBUG_PROPAGATE_EXCEPTIONS setting, 1261 decimal_places (DecimalField attribute), 1042, 1097 DECIMAL_SEPARATOR setting, 1261 DecimalField (class in django.db.models), 1097 DecimalField (class in django.forms), 1042 DecimalValidator (class in django.core.validators), 1395 decompress() (MultiWidget method), 1060 decompress() (RangeWidget method), 907 deconstruct() (Field method), 1114 decorator_from_middleware() (in module django.utils.decorators), 1379 decorator_from_middleware_with_args() (in module django.utils.decorators), 1379 default template filter, 1332 default (Field attribute), 1092 DEFAULT_CHARSET setting, 1261 DEFAULT_CONTENT_TYPE setting, 1261 DEFAULT_EXCEPTION_REPORTER_FILTER setting, 1262 DEFAULT_FILE_STORAGE setting, 1262 DEFAULT_FROM_EMAIL setting, 1262 default_if_none template filter, 1332 DEFAULT_INDEX_TABLESPACE setting, 1262 default_lat (GeoModelAdmin attribute), 874 default_lat (OSMWidget attribute), 801 default_lon (GeoModelAdmin attribute), 874 default_lon (OSMWidget attribute), 802 default_manager_name (Options attribute), 1124 default_permissions (Options attribute), 1127 default_related_name (Options attribute), 1124 default_renderer (Form attribute), 1026

    Index

    Django Documentation, Release 2.1.dev20171226153947

    DEFAULT_TABLESPACE difference() (in module setting, 1262 django.db.models.query.QuerySet), 1154 default_zoom (GeoModelAdmin attribute), 874 difference() (OGRGeometry method), 849 default_zoom (OSMWidget attribute), 802 diffsettings defaults.bad_request() (in module django.views), 1398 django-admin command, 979 defaults.page_not_found() (in module django.views), diffsettings command line option 1397 –all, 979 defaults.permission_denied() (in module django.views), –default MODULE, 980 1397 –output {hash,unified}, 980 defaults.server_error() (in module django.views), 1397 dim (GeometryField attribute), 791 DefaultStorage (class in django.core.files.storage), 1008 dimension (OGRGeometry attribute), 846 defer() (in module django.db.models.query.QuerySet), dims (GEOSGeometry attribute), 827 1163 directory_permissions_mode (FileSystemStorage atdelete() (Client method), 332 tribute), 1009 delete() (FieldFile method), 1100 disable_action() (AdminSite method), 698 delete() (File method), 1008 disabled (Field attribute), 1038 delete() (in module django.db.models.query.QuerySet), DISALLOWED_USER_AGENTS 1176 setting, 1262 delete() (Model method), 1138 disconnect() (Signal method), 527 delete() (Storage method), 1009 DiscoverRunner (class in django.test.runner), 358 delete_confirmation_template (ModelAdmin attribute), disjoint 721 field lookup type, 805 delete_cookie() (HttpResponse method), 1240 disjoint() (GEOSGeometry method), 830 delete_model() (BaseDatabaseSchemaEditor method), disjoint() (OGRGeometry method), 849 1244 disjoint() (PreparedGeometry method), 835 delete_model() (ModelAdmin method), 722 dispatch() (django.views.generic.base.View method), 642 delete_selected_confirmation_template (ModelAdmin at- display_raw (BaseGeometryWidget attribute), 801 tribute), 721 Distance (class in django.contrib.gis.db.models.functions), delete_test_cookie() (backends.base.SessionBase 817 method), 217 Distance (class in django.contrib.gis.measure), 823 delete_view() (ModelAdmin method), 729 distance() (GEOSGeometry method), 832 deleted_objects (models.BaseModelFormSet attribute), distance_gt 260 field lookup type, 810 DeleteModel (class in django.db.migrations.operations), distance_gte 1082 field lookup type, 811 DeleteView (built-in class), 680 distance_lt delimiter (SimpleArrayField attribute), 904 field lookup type, 811 delimiter (StringAgg attribute), 889 distance_lte DenseRank (class in django.db.models.functions), 1227 field lookup type, 811 desc() (Expression method), 1207 distinct (ArrayAgg attribute), 888 description (Field attribute), 1112 distinct (Count attribute), 1187 description (GDALBand attribute), 860 distinct (StringAgg attribute), 889 destroy_test_db() (in module distinct() (in module django.db.models.query.QuerySet), django.db.connection.creation), 361 1148 DetailView (built-in class), 676 divisibleby dict() (QueryDict method), 1236 template filter, 1333 dictsort django (OGRGeomType attribute), 851 template filter, 1332 django-admin command dictsortreversed changepassword, 996 template filter, 1333 check, 978 Difference (class in django.contrib.gis.db.models.functions), clearsessions, 997 816 collectstatic, 931 difference() (GEOSGeometry method), 830 compilemessages, 978 createcachetable, 979

    Index

    1817

    Django Documentation, Release 2.1.dev20171226153947

    createsuperuser, 996 dbshell, 979 diffsettings, 979 dumpdata, 980 findstatic, 933 flush, 981 help, 977 inspectdb, 981 loaddata, 982 makemessages, 984 makemigrations, 986 migrate, 987 ogrinspect, 873 ping_google, 924 remove_stale_contenttypes, 997 runserver, 933, 988 sendtestemail, 989 shell, 990 showmigrations, 990 sqlflush, 991 sqlmigrate, 991 sqlsequencereset, 991 squashmigrations, 991 startapp, 992 startproject, 993 test, 994 testserver, 995 version, 977 django.apps (module), 623 django.conf.settings.configure() (built-in function), 522 django.conf.urls (module), 1376 django.conf.urls.i18n (module), 461 django.contrib.admin (module), 692 django.contrib.admindocs (module), 699 django.contrib.auth (module), 408 django.contrib.auth.backends (module), 751 django.contrib.auth.forms (module), 380 django.contrib.auth.hashers (module), 389 django.contrib.auth.middleware (module), 1080 django.contrib.auth.password_validation (module), 389 django.contrib.auth.signals (module), 750 django.contrib.auth.views (module), 373 django.contrib.contenttypes (module), 753 django.contrib.contenttypes.admin (module), 758 django.contrib.contenttypes.fields (module), 755 django.contrib.contenttypes.forms (module), 758 django.contrib.flatpages (module), 759 django.contrib.gis (module), 764 django.contrib.gis.admin (module), 874 django.contrib.gis.db.backends (module), 793 django.contrib.gis.db.models (module), 789, 793 django.contrib.gis.db.models.functions (module), 798, 814 django.contrib.gis.feeds (module), 875

    1818

    django.contrib.gis.forms (module), 799 django.contrib.gis.forms.widgets (module), 800 django.contrib.gis.gdal (module), 839 django.contrib.gis.geoip2 (module), 865 django.contrib.gis.geos (module), 824 django.contrib.gis.measure (module), 821 django.contrib.gis.serializers.geojson (module), 872 django.contrib.gis.utils (module), 868 django.contrib.gis.utils.layermapping (module), 868 django.contrib.gis.utils.ogrinspect (module), 871 django.contrib.humanize (module), 878 django.contrib.messages (module), 881 django.contrib.messages.middleware (module), 1078 django.contrib.postgres (module), 887 django.contrib.postgres.aggregates (module), 888 django.contrib.postgres.forms.BaseRangeField (class in django.contrib.postgres.fields), 903 django.contrib.postgres.indexes (module), 908 django.contrib.postgres.validators (module), 915 django.contrib.redirects (module), 915 django.contrib.sessions (module), 214 django.contrib.sessions.middleware (module), 1080 django.contrib.sitemaps (module), 916 django.contrib.sites (module), 924 django.contrib.sites.middleware (module), 1080 django.contrib.staticfiles (module), 931 django.contrib.syndication (module), 937 django.core.cache.cache (built-in variable), 420 django.core.cache.caches (built-in variable), 420 django.core.cache.utils.make_template_fragment_key() (built-in function), 419 django.core.checks (module), 528 django.core.exceptions (module), 1002 django.core.files (module), 1006 django.core.files.storage (module), 1008 django.core.files.uploadedfile (module), 1011 django.core.files.uploadhandler (module), 1012 django.core.mail (module), 433 django.core.mail.outbox (in module django.core.mail), 350 django.core.management (module), 535 django.core.management.call_command() (built-in function), 1001 django.core.paginator (module), 497 django.core.serializers.get_serializer() (built-in function), 512 django.core.serializers.json.DjangoJSONEncoder (builtin class), 515 django.core.signals (module), 1299 django.core.signals.got_request_exception (built-in variable), 1299 django.core.signals.request_finished (built-in variable), 1299

    Index

    Django Documentation, Release 2.1.dev20171226153947

    django.core.signals.request_started (built-in variable), 1299 django.core.signing (module), 430 django.core.validators (module), 1391 django.db (module), 84 django.db.backends (module), 1300 django.db.backends.base.schema (module), 1243 django.db.backends.signals.connection_created (built-in variable), 1300 django.db.migrations (module), 309 django.db.migrations.operations (module), 1082 django.db.models (module), 84 django.db.models.fields (module), 1089 django.db.models.fields.related (module), 1104 django.db.models.functions (module), 1214 django.db.models.indexes (module), 1115 django.db.models.lookups (module), 1191 django.db.models.options (module), 1116 django.db.models.signals (module), 1293 django.db.models.signals.class_prepared (built-in variable), 1297 django.db.models.signals.m2m_changed (built-in variable), 1295 django.db.models.signals.post_delete (built-in variable), 1295 django.db.models.signals.post_init (built-in variable), 1294 django.db.models.signals.post_migrate (built-in variable), 1298 django.db.models.signals.post_save (built-in variable), 1294 django.db.models.signals.pre_delete (built-in variable), 1295 django.db.models.signals.pre_migrate (built-in variable), 1297 django.db.models.signals.pre_save (built-in variable), 1294 django.db.transaction (module), 146 django.dispatch (module), 524 django.forms (module), 1014 django.forms.fields (module), 1033 django.forms.formsets (module), 236, 1054 django.forms.models (module), 247, 1053 django.forms.renderers (module), 1054 django.forms.widgets (module), 1056 django.http (module), 1229 django.http.Http404 (built-in class), 199 django.middleware (module), 1076 django.middleware.cache (module), 1076 django.middleware.clickjacking (module), 690, 1081 django.middleware.common (module), 1076 django.middleware.csrf (module), 956, 1080 django.middleware.exception (module), 1076 django.middleware.gzip (module), 1077

    Index

    django.middleware.http (module), 1077 django.middleware.locale (module), 1077 django.middleware.security (module), 1078 django.shortcuts (module), 205 django.template (module), 272 django.template.backends (module), 275 django.template.backends.django (module), 275 django.template.backends.jinja2 (module), 276 django.template.loader (module), 273 django.template.response (module), 1363 django.test (module), 323 django.test.signals (module), 1299 django.test.signals.setting_changed (built-in variable), 1299 django.test.signals.template_rendered (built-in variable), 1300 django.test.utils (module), 360 django.test.utils.isolate_apps() (built-in function), 1745 django.urls (module), 1372 django.urls.conf (module), 1375 django.utils (module), 1378 django.utils.cache (module), 1378 django.utils.dateparse (module), 1379 django.utils.decorators (module), 1379 django.utils.deprecation.MiddlewareMixin (built-in class), 213 django.utils.encoding (module), 1380 django.utils.feedgenerator (module), 1381 django.utils.functional (module), 1383 django.utils.html (module), 1385 django.utils.http (module), 1386 django.utils.log (module), 487 django.utils.module_loading (module), 1387 django.utils.safestring (module), 1387 django.utils.text (module), 1388 django.utils.timezone (module), 1388 django.utils.translation (module), 443, 1390 django.views (module), 1396 django.views.decorators.cache (module), 201 django.views.decorators.cache.cache_page() (built-in function), 417 django.views.decorators.csrf (module), 959 django.views.decorators.gzip (module), 201 django.views.decorators.http (module), 200 django.views.decorators.vary (module), 201 django.views.generic.base.ContextMixin (built-in class), 661 django.views.generic.base.RedirectView (built-in class), 643 django.views.generic.base.TemplateResponseMixin (built-in class), 662 django.views.generic.base.TemplateView (built-in class), 642 django.views.generic.base.View (built-in class), 641

    1819

    Django Documentation, Release 2.1.dev20171226153947

    django.views.generic.dates (module), 651 dumps() (in module django.core.signing), 433 django.views.generic.detail.DetailView (built-in class), DurationField (class in django.db.models), 1097 645 DurationField (class in django.forms), 1042 django.views.generic.detail.SingleObjectMixin (built-in dwithin class), 663 field lookup type, 812 django.views.generic.detail.SingleObjectTemplateResponseMixin E (built-in class), 664 django.views.generic.edit.CreateView (built-in class), each_context() (AdminSite method), 740 649 earliest() (in module django.db.models.query.QuerySet), django.views.generic.edit.DeleteView (built-in class), 1173 650 editable (Field attribute), 1092 django.views.generic.edit.DeletionMixin (built-in class), ellipsoid (SpatialReference attribute), 854 670 email (models.User attribute), 746 django.views.generic.edit.FormMixin (built-in class), 668 EMAIL_BACKEND django.views.generic.edit.FormView (built-in class), 648 setting, 1262 django.views.generic.edit.ModelFormMixin (built-in EMAIL_FIELD (models.CustomUser attribute), 400 class), 669 EMAIL_FILE_PATH django.views.generic.edit.ProcessFormView (built-in setting, 1263 class), 669 EMAIL_HOST django.views.generic.edit.UpdateView (built-in class), setting, 1263 650 EMAIL_HOST_PASSWORD django.views.generic.list.BaseListView (built-in class), setting, 1263 647 EMAIL_HOST_USER django.views.generic.list.ListView (built-in class), 646 setting, 1263 django.views.generic.list.MultipleObjectMixin (built-in EMAIL_PORT class), 665 setting, 1263 django.views.generic.list.MultipleObjectTemplateResponseMixin EMAIL_SSL_CERTFILE (built-in class), 667 setting, 1264 django.views.i18n (module), 457 EMAIL_SSL_KEYFILE DJANGO_SETTINGS_MODULE, 23, 523, 581, 928, setting, 1264 976, 977, 1555 EMAIL_SUBJECT_PREFIX DjangoTemplates (class in django.forms.renderers), 1055 setting, 1263 DjangoTemplates (class in EMAIL_TIMEOUT django.template.backends.django), 275 setting, 1264 DO_NOTHING (in module django.db.models), 1107 EMAIL_USE_LOCALTIME domain (JavaScriptCatalog attribute), 457 setting, 1263 domain (models.Site attribute), 924 EMAIL_USE_SSL Don’t repeat yourself, 1401 setting, 1264 Driver (class in django.contrib.gis.gdal), 845 EMAIL_USE_TLS driver (GDALRaster attribute), 856 setting, 1264 driver_count (Driver attribute), 845 email_user() (models.User method), 748 DRY, 1401 EmailField (class in django.db.models), 1097 dumpdata EmailField (class in django.forms), 1043 django-admin command, 980 EmailInput (class in django.forms), 1063 dumpdata command line option EmailMessage (class in django.core.mail), 436 –all, -a, 980 EmailValidator (class in django.core.validators), 1393 –database DATABASE, 980 empty (GEOSGeometry attribute), 827 –exclude EXCLUDE, -e EXCLUDE, 980 empty_label (ModelChoiceField attribute), 1051 –format FORMAT, 980 empty_label (SelectDateWidget attribute), 1069 –indent INDENT, 980 empty_value (CharField attribute), 1040 –natural-foreign, 980 empty_value (TypedChoiceField attribute), 1040 –natural-primary, 980 empty_value_display (AdminSite attribute), 740 –output OUTPUT, -o OUTPUT, 981 empty_value_display (ModelAdmin attribute), 704 –pks PRIMARY_KEYS, 981 EmptyPage, 501 1820

    Index

    Django Documentation, Release 2.1.dev20171226153947

    EmptyResultSet, 1003 Enclosure (class in django.utils.feedgenerator), 1382 encode() (base_session.BaseSessionManager method), 224 encoder (JSONField attribute), 898 encoding (HttpRequest attribute), 1230 end_index() (Page method), 501 endswith field lookup type, 1180 Engine (class in django.template), 1349 engines (in module django.template.loader), 275 ensure_csrf_cookie() (in module django.views.decorators.csrf), 962 Envelope (class in django.contrib.gis.db.models.functions), 817 Envelope (class in django.contrib.gis.gdal), 851 envelope (GEOSGeometry attribute), 831 envelope (OGRGeometry attribute), 847 environment variable DJANGO_SETTINGS_MODULE, 23, 520, 523, 581, 928, 976, 977, 1555 PYTHONPATH, 1556 PYTHONSTARTUP, 990 PYTHONWARNINGS, 586 equals field lookup type, 805 equals() (GEOSGeometry method), 830 equals() (OGRGeometry method), 849 equals_exact() (GEOSGeometry method), 830 Error, 1005 Error (class in django.core.checks), 630 error_css_class (Form attribute), 1022 error_messages (Field attribute), 1038, 1092 errors (BoundField attribute), 1028 errors (Form attribute), 1015 escape template filter, 1334 escape() (in module django.utils.html), 1385 escape_uri_path() (in module django.utils.encoding), 1381 escapejs template filter, 1334 etag() (in module django.views.decorators.http), 201 ewkb (GEOSGeometry attribute), 829 ewkt (GEOSGeometry attribute), 828 ewkt (OGRGeometry attribute), 848 exact field lookup type, 805, 1177 ExceptionMiddleware (class in django.middleware.exception), 1076 exclude (ModelAdmin attribute), 705 exclude() (in module django.db.models.query.QuerySet), 1144 execute() (BaseCommand method), 539

    Index

    execute() (BaseDatabaseSchemaEditor method), 1244 execute_wrapper() (in module django.db.backends.base.DatabaseWrapper), 173 Exists (class in django.db.models), 1201 exists() (in module django.db.models.query.QuerySet), 1174 exists() (Storage method), 1009 expand_to_include() (Envelope method), 852 expire_date (base_session.AbstractBaseSession attribute), 224 Expression (class in django.db.models), 1206 ExpressionWrapper (class in django.db.models), 1200 extends template tag, 1313 Extent (class in django.contrib.gis.db.models), 812 extent (GDALRaster attribute), 858 extent (GEOSGeometry attribute), 832 extent (Layer attribute), 842 extent (OGRGeometry attribute), 847 Extent3D (class in django.contrib.gis.db.models), 813 exterior_ring (Polygon attribute), 850 extra (InlineModelAdmin attribute), 733 extra() (in module django.db.models.query.QuerySet), 1160 extra_context (django.views.generic.base.ContextMixin attribute), 661 extra_js (GeoModelAdmin attribute), 874 Extract (class in django.db.models.functions), 1216 ExtractDay (class in django.db.models.functions), 1218 ExtractHour (class in django.db.models.functions), 1219 ExtractMinute (class in django.db.models.functions), 1219 ExtractMonth (class in django.db.models.functions), 1218 ExtractQuarter (class in django.db.models.functions), 1218 ExtractSecond (class in django.db.models.functions), 1219 ExtractWeek (class in django.db.models.functions), 1218 ExtractWeekDay (class in django.db.models.functions), 1218 ExtractYear (class in django.db.models.functions), 1218

    F F (class in django.db.models), 1195 Feature (class in django.contrib.gis.gdal), 843 Feature release, 1775 Feed (class in django.contrib.gis.feeds), 875 FetchFromCacheMiddleware (class django.middleware.cache), 1076 fid (Feature attribute), 844 field, 1407 field (BoundField attribute), 1028

    in

    1821

    Django Documentation, Release 2.1.dev20171226153947

    Field (class in django.contrib.gis.gdal), 844 Field (class in django.db.models), 1112 Field (class in django.forms), 1033 field lookup type arrayfield.contained_by, 893 arrayfield.contains, 893 arrayfield.index, 894 arrayfield.len, 893 arrayfield.overlap, 893 arrayfield.slice, 894 bbcontains, 802 bboverlaps, 803 contained, 803 contains, 1178 contains_properly, 804 coveredby, 804 covers, 804 crosses, 805 date, 1181 day, 1182 disjoint, 805 distance_gt, 810 distance_gte, 811 distance_lt, 811 distance_lte, 811 dwithin, 812 endswith, 1180 equals, 805 exact, 805, 1177 gis-contains, 803 gt, 1179 gte, 1179 hour, 1184 hstorefield.contained_by, 896 hstorefield.contains, 896 hstorefield.has_any_keys, 897 hstorefield.has_key, 897 hstorefield.has_keys, 897 hstorefield.key, 896 hstorefield.keys, 897 hstorefield.values, 897 icontains, 1178 iendswith, 1181 iexact, 1177 in, 1178 intersects, 805 iregex, 1186 isnull, 1185 istartswith, 1180 isvalid, 806 jsonfield.contained_by, 899 jsonfield.contains, 899 jsonfield.has_any_keys, 899 jsonfield.has_key, 899

    1822

    jsonfield.has_keys, 899 jsonfield.key, 899 left, 808 lt, 1180 lte, 1180 minute, 1184 month, 1182 overlaps, 806 overlaps_above, 809 overlaps_below, 809 overlaps_left, 808 overlaps_right, 809 quarter, 1183 range, 1181 rangefield.adjacent_to, 902 rangefield.contained_by, 901 rangefield.contains, 901 rangefield.endswith, 903 rangefield.fully_gt, 902 rangefield.fully_lt, 902 rangefield.isempty, 903 rangefield.not_gt, 902 rangefield.not_lt, 902 rangefield.overlap, 902 rangefield.startswith, 903 regex, 1185 relate, 806 right, 808 same_as, 805 search, 911 second, 1185 startswith, 1180 strictly_above, 809 strictly_below, 810 time, 1184 touches, 807 trigram_similar, 909 unaccent, 909 week, 1183 week_day, 1183 within, 807 year, 1182 field_order (Form attribute), 1026 field_precisions (Layer attribute), 842 field_widths (Layer attribute), 842 FieldDoesNotExist, 1003 FieldError, 1004 FieldFile (class in django.db.models.fields.files), 1099 fields (ComboField attribute), 1048 fields (django.views.generic.edit.ModelFormMixin attribute), 669 fields (Feature attribute), 844 fields (Form attribute), 1018 fields (Index attribute), 1116

    Index

    Django Documentation, Release 2.1.dev20171226153947

    fields (Layer attribute), 841 fields (ModelAdmin attribute), 705 fields (MultiValueField attribute), 1049 fieldsets (ModelAdmin attribute), 706 File (class in django.core.files), 1006 file (File attribute), 1007 FILE_CHARSET setting, 1264 file_complete() (FileUploadHandler method), 1012 file_hash() (storage.ManifestStaticFilesStorage method), 935 file_permissions_mode (FileSystemStorage attribute), 1009 FILE_UPLOAD_DIRECTORY_PERMISSIONS setting, 1265 FILE_UPLOAD_HANDLERS setting, 1264 FILE_UPLOAD_MAX_MEMORY_SIZE setting, 1265 FILE_UPLOAD_PERMISSIONS setting, 1265 FILE_UPLOAD_TEMP_DIR setting, 1265 FileExtensionValidator (class in django.core.validators), 1395 FileField (class in django.db.models), 1097 FileField (class in django.forms), 1043 FileInput (class in django.forms), 1068 filepath_to_uri() (in module django.utils.encoding), 1381 FilePathField (class in django.db.models), 1101 FilePathField (class in django.forms), 1043 FileResponse (class in django.http), 1243 FILES (HttpRequest attribute), 1231 filesizeformat template filter, 1334 filesystem.Loader (class in django.template.loaders), 1360 FileSystemStorage (class in django.core.files.storage), 1009 FileUploadHandler (class in django.core.files.uploadhandler), 1012 filter template tag, 1314 filter() (django.template.Library method), 557 filter() (in module django.db.models.query.QuerySet), 1144 filter_horizontal (ModelAdmin attribute), 708 filter_vertical (ModelAdmin attribute), 708 filterable (Expression attribute), 1206 filterable (Window attribute), 1203 FilteredRelation (class in django.db.models), 1190 findstatic django-admin command, 933 findstatic –first

    Index

    findstatic command line option, 933 findstatic command line option findstatic –first, 933 first template filter, 1335 first() (in module django.db.models.query.QuerySet), 1173 FIRST_DAY_OF_WEEK setting, 1266 first_name (models.User attribute), 746 firstof template tag, 1314 FirstValue (class in django.db.models.functions), 1228 FixedOffset (class in django.utils.timezone), 1388 FIXTURE_DIRS setting, 1266 fixtures (TransactionTestCase attribute), 342 fk_name (InlineModelAdmin attribute), 732 flags (RegexValidator attribute), 1393 FlatPage (class in django.contrib.flatpages.models), 762 FlatpageFallbackMiddleware (class in django.contrib.flatpages.middleware), 760 FlatPageSitemap (class in django.contrib.flatpages.sitemaps), 763 flatten() (Context method), 1355 FloatField (class in django.db.models), 1101 FloatField (class in django.forms), 1044 floatformat template filter, 1335 FloatRangeField (class in django.contrib.postgres.fields), 900 FloatRangeField (class in django.contrib.postgres.forms), 907 flush django-admin command, 981 flush command line option –database DATABASE, 981 –noinput, –no-input, 981 flush() (backends.base.SessionBase method), 217 flush() (HttpResponse method), 1240 for template tag, 1315 for_concrete_model (GenericForeignKey attribute), 756 force_bytes() (in module django.utils.encoding), 1380 force_escape template filter, 1336 force_login() (Client method), 332 FORCE_SCRIPT_NAME setting, 1266 force_str() (in module django.utils.encoding), 1380 force_text() (in module django.utils.encoding), 1380 ForceRHR (class in django.contrib.gis.db.models.functions), 817 ForeignKey (class in django.db.models), 1104

    1823

    Django Documentation, Release 2.1.dev20171226153947

    form (BoundField attribute), 1029 fromstr() (in module django.contrib.gis.geos), 836 Form (class in django.forms), 1014 full_clean() (Model method), 1133 form (InlineModelAdmin attribute), 733 Func (class in django.db.models), 1197 form (ModelAdmin attribute), 708 func (ResolverMatch attribute), 1373 form_class (django.views.generic.edit.FormMixin at- function (Aggregate attribute), 1199 tribute), 668 function (Func attribute), 1197 form_field (RangeField attribute), 903 form_invalid() (django.views.generic.edit.FormMixin G method), 668 GDAL_LIBRARY_PATH form_invalid() (django.views.generic.edit.ModelFormMixin setting, 865 method), 669 GDALBand (class in django.contrib.gis.gdal), 860 FORM_RENDERER GDALException, 865 setting, 1266 GDALRaster (class in django.contrib.gis.gdal), 855 form_valid() (django.views.generic.edit.FormMixin generate_filename() (Storage method), 1010 method), 668 generic view, 1407 form_valid() (django.views.generic.edit.ModelFormMixin generic_inlineformset_factory() (in module method), 669 django.contrib.contenttypes.forms), 758 format (DateInput attribute), 1064 GenericForeignKey (class in format (DateTimeInput attribute), 1064 django.contrib.contenttypes.fields), 756 format (TimeInput attribute), 1064 GenericInlineModelAdmin (class in format file, 487 django.contrib.contenttypes.admin), 759 format_html() (in module django.utils.html), 1385 GenericIPAddressField (class in django.db.models), 1102 format_html_join() (in module django.utils.html), 1386 GenericIPAddressField (class in django.forms), 1045 format_lazy() (in module django.utils.text), 1388 GenericRelation (class in FORMAT_MODULE_PATH django.contrib.contenttypes.fields), 757 setting, 1266 GenericSitemap (class in django.contrib.sitemaps), 920 format_value() (Widget method), 1059 GenericStackedInline (class in formfield() (Field method), 1114 django.contrib.contenttypes.admin), 759 formfield_for_choice_field() (ModelAdmin method), 727 GenericTabularInline (class in formfield_for_foreignkey() (ModelAdmin method), 726 django.contrib.contenttypes.admin), 759 formfield_for_manytomany() (ModelAdmin method), GeoAtom1Feed (class in django.contrib.gis.feeds), 876 726 geographic (SpatialReference attribute), 854 formfield_overrides (ModelAdmin attribute), 709 geography (GeometryField attribute), 792 formset (InlineModelAdmin attribute), 733 GeoHash (class in django.contrib.gis.db.models.functions), formset_factory() (in module django.forms.formsets), 817 1054 GeoIP2 (class in django.contrib.gis.geoip2), 866 FormView (built-in class), 677 GeoIP2Exception, 868 frame_type (RowRange attribute), 1205 GEOIP_CITY frame_type (ValueRange attribute), 1204 setting, 868 from_bbox() (django.contrib.gis.gdal.OGRGeometry GEOIP_COUNTRY class method), 846 setting, 868 from_bbox() (django.contrib.gis.geos.Polygon class GEOIP_PATH method), 834 setting, 868 from_db() (django.db.models.Model class method), 1131 geojson (GEOSGeometry attribute), 829 from_db_value() (Field method), 1113 geom (Feature attribute), 843 from_esri() (SpatialReference method), 853 geom_count (OGRGeometry attribute), 846 from_gml() (django.contrib.gis.gdal.OGRGeometry class geom_name (OGRGeometry attribute), 847 method), 846 geom_type (BaseGeometryWidget attribute), 801 from_gml() (django.contrib.gis.geos.GEOSGeometry geom_type (Feature attribute), 843 class method), 827 geom_type (Field attribute), 799 from_queryset() (in module django.db.models), 138 geom_type (GEOSGeometry attribute), 827 from_string() (Engine method), 1350 geom_type (Layer attribute), 841 fromfile() (in module django.contrib.gis.geos), 836 geom_type (OGRGeometry attribute), 847 fromkeys() (django.http.QueryDict class method), 1235 geom_typeid (GEOSGeometry attribute), 827 1824

    Index

    Django Documentation, Release 2.1.dev20171226153947

    geometry() (Feed method), 875 get_by_natural_key() (models.BaseUserManager GeometryCollection (class in django.contrib.gis.gdal), method), 403 851 get_cache_key() (in module django.utils.cache), 1378 GeometryCollection (class in django.contrib.gis.geos), get_change_message() (LogEntry method), 744 835 get_changeform_initial_data() (ModelAdmin method), GeometryCollectionField (class in 729 django.contrib.gis.db.models), 790 get_changelist() (ModelAdmin method), 727 GeometryCollectionField (class in get_changelist_form() (ModelAdmin method), 727 django.contrib.gis.forms), 800 get_changelist_formset() (ModelAdmin method), 727 GeometryField (class in django.contrib.gis.db.models), get_connection() (in module django.core.mail), 439 789 get_contents() (Loader method), 1362 GeometryField (class in django.contrib.gis.forms), 800 get_context() (MultiWidget method), 1061 GeoModelAdmin (class in django.contrib.gis.admin), 874 get_context() (Widget method), 1059 GeoRSSFeed (class in django.contrib.gis.feeds), 876 get_context_data() (django.views.generic.base.ContextMixin geos (OGRGeometry attribute), 847 method), 661 geos() (GeoIP2 method), 868 get_context_data() (django.views.generic.detail.SingleObjectMixin GEOS_LIBRARY_PATH method), 664 setting, 839 get_context_data() (django.views.generic.edit.FormMixin GEOSException, 839 method), 668 GEOSGeometry (class in django.contrib.gis.geos), 826 get_context_data() (django.views.generic.list.MultipleObjectMixin geotransform (GDALRaster attribute), 857 method), 667 get (Feature attribute), 843 get_context_data() (Feed method), 939 GET (HttpRequest attribute), 1230 get_context_object_name() get() (backends.base.SessionBase method), 216 (django.views.generic.detail.SingleObjectMixin get() (Client method), 329 method), 664 get() (Context method), 1354 get_context_object_name() get() (django.views.generic.edit.ProcessFormView (django.views.generic.list.MultipleObjectMixin method), 670 method), 667 get() (django.views.generic.list.BaseListView method), get_created_time() (FileSystemStorage method), 1009 647 get_created_time() (Storage method), 1010 get() (in module django.db.models.query.QuerySet), 1167 get_current_language get() (QueryDict method), 1235 template tag, 455 get_absolute_url() (Model method), 1140 get_current_language_bidi get_accessed_time() (Storage method), 1009 template tag, 455 get_actions() (ModelAdmin method), 698 get_current_timezone get_all_permissions() (ModelBackend method), 752 template tag, 480 get_all_permissions() (models.PermissionsMixin get_current_timezone() (in module method), 404 django.utils.timezone), 1388 get_all_permissions() (models.User method), 748 get_current_timezone_name() (in module get_allow_empty() (django.views.generic.list.MultipleObjectMixin django.utils.timezone), 1389 method), 666 get_date_field() (DateMixin method), 673 get_allow_future() (DateMixin method), 673 get_date_list() (BaseDateListView method), 674 get_app_config() (apps method), 627 get_date_list_period() (BaseDateListView method), 674 get_app_configs() (apps method), 627 get_dated_items() (BaseDateListView method), 674 get_autocommit() (in module django.db.transaction), 152 get_dated_queryset() (BaseDateListView method), 674 get_autocomplete_fields() (ModelAdmin method), 723 get_day() (DayMixin method), 672 get_available_languages get_day_format() (DayMixin method), 672 template tag, 455 get_db_prep_save() (Field method), 1113 get_available_name() (in module get_db_prep_value() (Field method), 1113 django.core.files.storage), 573 get_decoded() (base_session.AbstractBaseSession get_available_name() (Storage method), 1009 method), 224 get_bound_field() (Field method), 1030 get_default() (Engine static method), 1350 get_by_natural_key() (ContentTypeManager method), get_default_timezone() (in module 755 django.utils.timezone), 1388

    Index

    1825

    Django Documentation, Release 2.1.dev20171226153947

    get_default_timezone_name() (in module get_initial() (django.views.generic.edit.FormMixin django.utils.timezone), 1388 method), 668 get_deferred_fields() (Model method), 1133 get_initial_for_field() (Form method), 1017 get_digit get_inline_instances() (ModelAdmin method), 724 template filter, 1336 get_internal_type() (Field method), 1112 get_edited_object() (LogEntry method), 744 get_json_data() (Form.errors method), 1016 get_email_field_name() (django.contrib.auth.models.AbstractBaseUser get_language() (in module django.utils.translation), 1391 class method), 401 get_language_bidi() (in module django.utils.translation), get_exclude() (ModelAdmin method), 724 1391 get_expire_at_browser_close() (back- get_language_from_request() (in module ends.base.SessionBase method), 218 django.utils.translation), 1391 get_expiry_age() (backends.base.SessionBase method), get_language_info 217 template tag, 456 get_expiry_date() (backends.base.SessionBase method), get_language_info() (in module django.utils.translation), 217 451 get_extra() (InlineModelAdmin method), 734 get_language_info_list get_field() (Options method), 1116 template tag, 456 get_fields() (Layer method), 843 get_latest_by (Options attribute), 1124 get_fields() (ModelAdmin method), 724 get_list_display() (ModelAdmin method), 723 get_fields() (Options method), 1117 get_list_display_links() (ModelAdmin method), 723 get_fieldsets() (ModelAdmin method), 724 get_list_filter() (ModelAdmin method), 724 get_fixed_timezone() (in module django.utils.timezone), get_list_or_404() (in module django.shortcuts), 209 1388 get_list_select_related() (ModelAdmin method), 724 get_flatpages get_login_url() (AccessMixin method), 372 template tag, 763 get_lookup() (in module django.db.models), 1192 get_FOO_display() (Model method), 1141 get_lookup() (lookups.RegisterLookupMixin method), get_for_id() (ContentTypeManager method), 755 1191 get_for_model() (ContentTypeManager method), 755 get_make_object_list() (YearArchiveView method), 653 get_for_models() (ContentTypeManager method), 755 get_max_age() (in module django.utils.cache), 1378 get_form() (django.views.generic.edit.FormMixin get_max_num() (InlineModelAdmin method), 734 method), 668 get_media_prefix get_form() (ModelAdmin method), 726 template tag, 1348 get_form_class() (django.views.generic.edit.FormMixin get_messages() (in module django.contrib.messages), 883 method), 668 get_min_num() (InlineModelAdmin method), 734 get_form_class() (django.views.generic.edit.ModelFormMixin get_model() (AppConfig method), 626 method), 669 get_model() (apps method), 627 get_form_kwargs() (django.views.generic.edit.FormMixin get_model_class() (django.contrib.sessions.backends.db.SessionStore method), 668 class method), 224 get_form_kwargs() (django.views.generic.edit.ModelFormMixin get_models() (AppConfig method), 626 method), 669 get_modified_time() (Storage method), 1010 get_formset() (InlineModelAdmin method), 734 get_month() (MonthMixin method), 671 get_formsets_with_inlines() (ModelAdmin method), 726 get_month_format() (MonthMixin method), 671 get_full_name() (models.CustomUser method), 401 get_next_by_FOO() (Model method), 1142 get_full_name() (models.User method), 748 get_next_day() (DayMixin method), 672 get_full_path() (HttpRequest method), 1233 get_next_month() (MonthMixin method), 671 get_full_path_info() (HttpRequest method), 1233 get_next_week() (WeekMixin method), 673 get_geoms() (Layer method), 843 get_next_year() (YearMixin method), 671 get_group_by_cols() (Expression method), 1207 get_object() (django.views.generic.detail.SingleObjectMixin get_group_permissions() (ModelBackend method), 751 method), 663 get_group_permissions() (models.PermissionsMixin get_object_for_this_type() (ContentType method), 754 method), 404 get_object_or_404() (in module django.shortcuts), 208 get_group_permissions() (models.User method), 748 get_or_create() (in module get_host() (HttpRequest method), 1232 django.db.models.query.QuerySet), 1168

    1826

    Index

    Django Documentation, Release 2.1.dev20171226153947

    get_ordering() (django.views.generic.list.MultipleObjectMixin get_static_prefix method), 666 template tag, 1347 get_ordering() (ModelAdmin method), 722 get_storage_class() (in module django.core.files.storage), get_page() (Paginator method), 500 1008 get_paginate_by() (django.views.generic.list.MultipleObjectMixin get_success_message() (views.SuccessMessageMixin method), 666 method), 886 get_paginate_orphans() (django.views.generic.list.MultipleObjectMixin get_success_url() (django.views.generic.edit.DeletionMixin method), 666 method), 670 get_paginator() (django.views.generic.list.MultipleObjectMixin get_success_url() (django.views.generic.edit.FormMixin method), 666 method), 668 get_paginator() (ModelAdmin method), 729 get_success_url() (django.views.generic.edit.ModelFormMixin get_password_validators() (in module method), 669 django.contrib.auth.password_validation), get_tag_uri() (in module django.utils.feedgenerator), 391 1381 get_permission_denied_message() (AccessMixin get_template() (Engine method), 1350 method), 372 get_template() (in module django.template.loader), 273 get_permission_required() (PermissionRequiredMixin get_template() (Loader method), 1362 method), 372 get_template_names() (django.views.generic.base.TemplateResponseMixin get_port() (HttpRequest method), 1233 method), 662 get_post_parameters() (SafeExceptionReporterFilter get_template_names() (django.views.generic.detail.SingleObjectTemplateRe method), 591 method), 664 get_prefix() (django.views.generic.edit.FormMixin get_template_names() (django.views.generic.list.MultipleObjectTemplateRe method), 668 method), 667 get_prep_value() (Field method), 1113 get_template_sources() (Loader method), 1362 get_prepopulated_fields() (ModelAdmin method), 723 get_test_func() (UserPassesTestMixin method), 370 get_prev_week() (WeekMixin method), 673 get_test_runner_kwargs() (DiscoverRunner method), 360 get_previous_by_FOO() (Model method), 1142 get_traceback_frame_variables() (SafeExceptionReget_previous_day() (DayMixin method), 672 porterFilter method), 591 get_previous_month() (MonthMixin method), 671 get_transform() (in module django.db.models), 1192 get_previous_year() (YearMixin method), 671 get_transform() (lookups.RegisterLookupMixin method), get_queryset() (django.views.generic.detail.SingleObjectMixin 1191 method), 663 get_urls() (ModelAdmin method), 724 get_queryset() (django.views.generic.list.MultipleObjectMixin get_user() (in module django.contrib.auth), 753 method), 666 get_user_model() (in module django.contrib.auth), 398 get_queryset() (ModelAdmin method), 728 get_user_permissions() (ModelBackend method), 751 get_readonly_fields() (ModelAdmin method), 723 get_username() (models.AbstractBaseUser method), 401 get_redirect_field_name() (AccessMixin method), 372 get_username() (models.User method), 747 get_redirect_url() (django.views.generic.base.RedirectView get_valid_name() (in module django.core.files.storage), method), 644 573 get_rollback() (in module django.db.transaction), 153 get_valid_name() (Storage method), 1010 get_script_prefix() (in module django.urls), 1374 get_version() (BaseCommand method), 539 get_search_fields() (ModelAdmin method), 724 get_week() (WeekMixin method), 672 get_search_results() (ModelAdmin method), 722 get_week_format() (WeekMixin method), 672 get_session_auth_hash() (models.AbstractBaseUser get_year() (YearMixin method), 671 method), 402 get_year_format() (YearMixin method), 670 get_session_store_class() getlist() (QueryDict method), 1236 (django.contrib.sessions.base_session.AbstractBaseSession gettext() (in module django.utils.translation), 1390 class method), 224 gettext_lazy() (in module django.utils.translation), 1390 get_short_name() (models.CustomUser method), 401 gettext_noop() (in module django.utils.translation), 1390 get_short_name() (models.User method), 748 getvalue() (HttpResponse method), 1240 get_signed_cookie() (HttpRequest method), 1233 GinIndex (class in django.contrib.postgres.indexes), 908 get_slug_field() (django.views.generic.detail.SingleObjectMixin gis-contains method), 664 field lookup type, 803 get_source_expressions() (Expression method), 1206 GistIndex (class in django.contrib.postgres.indexes), 908

    Index

    1827

    Django Documentation, Release 2.1.dev20171226153947

    gml (OGRGeometry attribute), 847 Greatest (class in django.db.models.functions), 1215 groups (models.User attribute), 746 gt field lookup type, 1179 gte field lookup type, 1179 gzip_page() (in module django.views.decorators.gzip), 201 GZipMiddleware (class in django.middleware.gzip), 1077

    django-admin command, 977 help (BaseCommand attribute), 538 help_text (BoundField attribute), 1029 help_text (Field attribute), 1037, 1093 hex (GEOSGeometry attribute), 829 hex (OGRGeometry attribute), 848 hexewkb (GEOSGeometry attribute), 829 hidden (Field attribute), 1114 HiddenInput (class in django.forms), 1063 history_view() (ModelAdmin method), 729 HOST H setting, 1253 hour handle() (BaseCommand method), 539 field lookup type, 1184 handle_app_config() (AppCommand method), 539 HStoreExtension (class in handle_label() (LabelCommand method), 540 django.contrib.postgres.operations), 911 handle_no_permission() (AccessMixin method), 372 HStoreField (class in django.contrib.postgres.fields), 895 handle_raw_input() (FileUploadHandler method), 1013 HStoreField (class in django.contrib.postgres.forms), 906 handler400 (in module django.conf.urls), 1377 hstorefield.contained_by handler403 (in module django.conf.urls), 1377 field lookup type, 896 handler404 (in module django.conf.urls), 1377 hstorefield.contains handler500 (in module django.conf.urls), 1377 field lookup type, 896 has_add_permission() (ModelAdmin method), 728 hstorefield.has_any_keys has_change_permission() (ModelAdmin method), 728 field lookup type, 897 has_changed() (Field method), 1039 hstorefield.has_key has_changed() (Form method), 1017 field lookup type, 897 has_delete_permission() (ModelAdmin method), 728 hstorefield.has_keys has_error() (Form method), 1016 field lookup type, 897 has_header() (HttpResponse method), 1239 hstorefield.key has_module_permission() (ModelAdmin method), 728 field lookup type, 896 has_module_perms() (ModelBackend method), 752 has_module_perms() (models.PermissionsMixin hstorefield.keys field lookup type, 897 method), 405 hstorefield.values has_module_perms() (models.User method), 748 field lookup type, 897 has_next() (Page method), 501 html_name (BoundField attribute), 1029 has_other_pages() (Page method), 501 html_safe() (in module django.utils.html), 1386 has_perm() (ModelBackend method), 752 http_date() (in module django.utils.http), 1386 has_perm() (models.PermissionsMixin method), 404 http_method_names (django.views.generic.base.View athas_perm() (models.User method), 748 tribute), 641 has_permission() (AdminSite method), 741 has_permission() (PermissionRequiredMixin method), http_method_not_allowed() (django.views.generic.base.View method), 372 642 has_perms() (models.PermissionsMixin method), 405 HttpRequest (class in django.http), 1229 has_perms() (models.User method), 748 HttpResponse (class in django.http), 1237 has_previous() (Page method), 501 has_usable_password() (models.AbstractBaseUser HttpResponseBadRequest (class in django.http), 1241 HttpResponseForbidden (class in django.http), 1241 method), 402 HttpResponseGone (class in django.http), 1241 has_usable_password() (models.User method), 748 HttpResponseNotAllowed (class in django.http), 1241 hasz (GEOSGeometry attribute), 828 HttpResponseNotFound (class in django.http), 1241 head() (Client method), 331 HttpResponseNotModified (class in django.http), 1240 height (GDALBand attribute), 860 HttpResponsePermanentRedirect (class in django.http), height (GDALRaster attribute), 857 1240 height (ImageFile attribute), 1008 HttpResponseRedirect (class in django.http), 1240 height_field (ImageField attribute), 1102 HttpResponseServerError (class in django.http), 1241 help 1828

    Index

    Django Documentation, Release 2.1.dev20171226153947

    I i18n (Sitemap attribute), 920 i18n_patterns() (in module django.conf.urls.i18n), 462 icontains field lookup type, 1178 id_for_label (BoundField attribute), 1029 id_for_label() (Widget method), 1059 identify_epsg() (SpatialReference method), 853 iendswith field lookup type, 1181 iexact field lookup type, 1177 if template tag, 1316 ifchanged template tag, 1320 IGNORABLE_404_URLS setting, 1267 ImageField (class in django.db.models), 1102 ImageField (class in django.forms), 1044 ImageFile (class in django.core.files.images), 1008 import_epsg() (SpatialReference method), 853 import_proj() (SpatialReference method), 853 import_string() (in module django.utils.module_loading), 1387 import_user_input() (SpatialReference method), 853 import_wkt() (SpatialReference method), 853 import_xml() (SpatialReference method), 853 ImproperlyConfigured, 1004 in field lookup type, 1178 in_bulk() (in module django.db.models.query.QuerySet), 1171 include template tag, 1321 include() (in module django.urls), 1376 inclusion_tag() (django.template.Library method), 562 Index (class in django.db.models), 1115 index (Feature attribute), 844 index_template (AdminSite attribute), 740 index_title (AdminSite attribute), 740 index_together (Options attribute), 1129 indexes (Options attribute), 1128 Info (class in django.core.checks), 630 info (GDALRaster attribute), 860 initial (django.views.generic.edit.FormMixin attribute), 668 initial (Field attribute), 1036 initial (Form attribute), 1017 initial (Migration attribute), 312 inlineformset_factory() (in module django.forms.models), 1054 InlineModelAdmin (class in django.contrib.admin), 731 inlines (ModelAdmin attribute), 709 Index

    InMemoryUploadedFile (class in django.core.files.uploadedfile), 1012 input_date_formats (SplitDateTimeField attribute), 1050 input_formats (DateField attribute), 1041 input_formats (DateTimeField attribute), 1041 input_formats (TimeField attribute), 1047 input_time_formats (SplitDateTimeField attribute), 1050 inspectdb django-admin command, 981 inspectdb command line option –database DATABASE, 982 INSTALLED_APPS setting, 1267 instance namespace, 195 int_list_validator() (in module django.core.validators), 1394 int_to_base36() (in module django.utils.http), 1387 intcomma template filter, 879 IntegerField (class in django.db.models), 1102 IntegerField (class in django.forms), 1045 IntegerRangeField (class in django.contrib.postgres.fields), 900 IntegerRangeField (class in django.contrib.postgres.forms), 907 IntegrityError, 1005 InterfaceError, 1005 INTERNAL_IPS setting, 1268 InternalError, 1005 internationalization, 486 interpolate() (GEOSGeometry method), 830 interpolate_normalized() (GEOSGeometry method), 830 Intersection (class in django.contrib.gis.db.models.functions), 818 intersection() (GEOSGeometry method), 830 intersection() (in module django.db.models.query.QuerySet), 1154 intersection() (OGRGeometry method), 849 intersects field lookup type, 805 intersects() (GEOSGeometry method), 830 intersects() (OGRGeometry method), 848 intersects() (PreparedGeometry method), 835 intword template filter, 879 InvalidPage, 500 inverse_flattening (SpatialReference attribute), 854 inverse_match (RegexValidator attribute), 1393 iregex field lookup type, 1186 iri_to_uri() (in module django.utils.encoding), 1380 iriencode template filter, 1336

    1829

    Django Documentation, Release 2.1.dev20171226153947

    is_active (in module django.contrib.auth), 404 is_active (models.CustomUser attribute), 401 is_active (models.User attribute), 746 is_active() (SafeExceptionReporterFilter method), 591 is_ajax() (HttpRequest method), 1234 is_anonymous (models.AbstractBaseUser attribute), 401 is_anonymous (models.User attribute), 747 is_authenticated (models.AbstractBaseUser attribute), 401 is_authenticated (models.User attribute), 747 is_aware() (in module django.utils.timezone), 1389 is_bound (Form attribute), 1014 is_hidden (BoundField attribute), 1029 is_installed() (apps method), 627 is_multipart() (Form method), 1032 is_naive() (in module django.utils.timezone), 1389 is_password_usable() (in module django.contrib.auth.hashers), 389 is_protected_type() (in module django.utils.encoding), 1380 is_relation (Field attribute), 1115 is_rendered (SimpleTemplateResponse attribute), 1364 is_secure() (HttpRequest method), 1234 is_staff (in module django.contrib.auth), 404 is_staff (models.User attribute), 746 is_superuser (models.PermissionsMixin attribute), 404 is_superuser (models.User attribute), 747 is_valid() (Form method), 1015 is_vsi_based (GDALRaster attribute), 860 isnull field lookup type, 1185 istartswith field lookup type, 1180 isvalid field lookup type, 806 IsValid (class in django.contrib.gis.db.models.functions), 818 item_attributes() (SyndicationFeed method), 1382 item_geometry() (Feed method), 875 items (Sitemap attribute), 918 items() (backends.base.SessionBase method), 217 items() (QueryDict method), 1235 iterator() (in module django.db.models.query.QuerySet), 1171

    J Java, 592 JavaScriptCatalog (class in django.views.i18n), 457 Jinja2 (class in django.forms.renderers), 1055 Jinja2 (class in django.template.backends.jinja2), 276 join template filter, 1336 json (GEOSGeometry attribute), 829 json (OGRGeometry attribute), 848 1830

    json() (Response method), 333 JSONBAgg (class in django.contrib.postgres.aggregates), 889 JSONCatalog (class in django.views.i18n), 460 JSONField (class in django.contrib.postgres.fields), 898 JSONField (class in django.contrib.postgres.forms), 906 jsonfield.contained_by field lookup type, 899 jsonfield.contains field lookup type, 899 jsonfield.has_any_keys field lookup type, 899 jsonfield.has_key field lookup type, 899 jsonfield.has_keys field lookup type, 899 jsonfield.key field lookup type, 899 JsonResponse (class in django.http), 1241 JVM, 592 Jython, 592

    K keep_lazy() (in module django.utils.functional), 1384 keep_lazy_text() (in module django.utils.functional), 1384 keys() (backends.base.SessionBase method), 217 KeysValidator (class in django.contrib.postgres.validators), 915 kml (GEOSGeometry attribute), 829 kml (OGRGeometry attribute), 848 kwargs (ResolverMatch attribute), 1373

    L label (AppConfig attribute), 625 label (BoundField attribute), 1029 label (Field attribute), 1035 label (LabelCommand attribute), 540 label (Options attribute), 1130 label_lower (Options attribute), 1130 label_suffix (Field attribute), 1035 label_suffix (Form attribute), 1025 label_tag() (BoundField method), 1030 LabelCommand (class in django.core.management), 540 Lag (class in django.db.models.functions), 1228 language template tag, 455 language code, 487 language_bidi template filter, 456 LANGUAGE_CODE setting, 1268 LANGUAGE_COOKIE_AGE setting, 1268 Index

    Django Documentation, Release 2.1.dev20171226153947

    LANGUAGE_COOKIE_DOMAIN setting, 1268 LANGUAGE_COOKIE_NAME setting, 1269 LANGUAGE_COOKIE_PATH setting, 1269 language_name template filter, 456 language_name_local template filter, 456 language_name_translated template filter, 456 LANGUAGE_SESSION_KEY (in module django.utils.translation), 1391 LANGUAGES setting, 1269 last template filter, 1336 last() (in module django.db.models.query.QuerySet), 1173 last_login (models.User attribute), 747 last_modified() (in module django.views.decorators.http), 201 last_name (models.User attribute), 746 lastmod (Sitemap attribute), 919 LastValue (class in django.db.models.functions), 1228 lat_lon() (GeoIP2 method), 867 latest() (in module django.db.models.query.QuerySet), 1172 latest_post_date() (SyndicationFeed method), 1382 Layer (class in django.contrib.gis.gdal), 841 layer_count (DataSource attribute), 840 layer_name (Feature attribute), 844 LayerMapping (class in django.contrib.gis.utils), 869 Lead (class in django.db.models.functions), 1228 learn_cache_key() (in module django.utils.cache), 1378 Least (class in django.db.models.functions), 1216 leave_locale_alone (BaseCommand attribute), 538 left field lookup type, 808 length template filter, 1337 Length (class in django.contrib.gis.db.models.functions), 818 Length (class in django.db.models.functions), 1225 length (GEOSGeometry attribute), 832 length_is template filter, 1337 lhs (Lookup attribute), 1193 lhs (Transform attribute), 1193 limit (Sitemap attribute), 919 limit_choices_to (ForeignKey attribute), 1107 limit_choices_to (ManyToManyField attribute), 1109 linear_name (SpatialReference attribute), 854

    Index

    linear_units (SpatialReference attribute), 854 LinearRing (class in django.contrib.gis.geos), 833 linebreaks template filter, 1337 linebreaksbr template filter, 1337 LineLocatePoint (class in django.contrib.gis.db.models.functions), 818 linenumbers template filter, 1337 LineString (class in django.contrib.gis.gdal), 850 LineString (class in django.contrib.gis.geos), 833 LineStringField (class in django.contrib.gis.db.models), 789 LineStringField (class in django.contrib.gis.forms), 800 list_display (ModelAdmin attribute), 709 list_display_links (ModelAdmin attribute), 713 list_editable (ModelAdmin attribute), 714 list_filter (ModelAdmin attribute), 714 list_max_show_all (ModelAdmin attribute), 716 list_per_page (ModelAdmin attribute), 717 list_select_related (ModelAdmin attribute), 717 listdir() (Storage method), 1010 lists() (QueryDict method), 1236 ListView (built-in class), 677 LiveServerTestCase (class in django.test), 339 ljust template filter, 1338 ll (Envelope attribute), 852 load template tag, 1321 loaddata django-admin command, 982 loaddata command line option –app APP_LABEL, 982 –database DATABASE, 982 –exclude EXCLUDE, -e EXCLUDE, 982 –format FORMAT, 982 –ignorenonexistent, -i, 982 Loader (class in django.template.loaders.base), 1362 loader (Origin attribute), 1363 loads() (in module django.core.signing), 433 local (SpatialReference attribute), 854 localdate() (in module django.utils.timezone), 1389 locale name, 487 LOCALE_PATHS setting, 1269 LocaleMiddleware (class in django.middleware.locale), 1077 localization, 486 localize template filter, 475 template tag, 475

    1831

    Django Documentation, Release 2.1.dev20171226153947

    localize (Field attribute), 1038 localtime template filter, 481 template tag, 480 localtime() (in module django.utils.timezone), 1389 location (FileSystemStorage attribute), 1009 location (Sitemap attribute), 918 locmem.Loader (class in django.template.loaders), 1361 LOGGING setting, 1270 LOGGING_CONFIG setting, 1270 login() (Client method), 332 login() (in module django.contrib.auth), 366 login_form (AdminSite attribute), 740 LOGIN_REDIRECT_URL setting, 1282 login_required() (in module django.contrib.auth.decorators), 368 login_template (AdminSite attribute), 740 LOGIN_URL setting, 1282 login_url (AccessMixin attribute), 372 LoginRequiredMixin (class in django.contrib.auth.mixins), 369 LoginView (class in django.contrib.auth.views), 374 logout() (Client method), 333 logout() (in module django.contrib.auth), 367 LOGOUT_REDIRECT_URL setting, 1282 logout_template (AdminSite attribute), 740 logout_then_login() (in module django.contrib.auth.views), 376 LogoutView (class in django.contrib.auth.views), 376 lon_lat() (GeoIP2 method), 867 Long-term support release, 1776 Lookup (class in django.db.models), 1193 lookup_allowed() (ModelAdmin method), 728 lookup_name (Lookup attribute), 1193 lookup_name (Transform attribute), 1193 lookups.RegisterLookupMixin (class in django.db.models), 1191 lorem template tag, 1322 lower template filter, 1338 Lower (class in django.db.models.functions), 1226 lt field lookup type, 1180 lte field lookup type, 1180

    M mail_admins() (in module django.core.mail), 435 1832

    mail_managers() (in module django.core.mail), 435 make_aware() (in module django.utils.timezone), 1389 make_list template filter, 1338 make_naive() (in module django.utils.timezone), 1390 make_object_list (YearArchiveView attribute), 653 make_password() (in module django.contrib.auth.hashers), 389 make_random_password() (models.BaseUserManager method), 403 MakeLine (class in django.contrib.gis.db.models), 813 makemessages django-admin command, 984 makemessages command line option –add-location [{full,file,never}], 986 –all, -a, 985 –domain DOMAIN, -d DOMAIN, 985 –exclude EXCLUDE, -x EXCLUDE, 985 –extension EXTENSIONS, -e EXTENSIONS, 985 –ignore PATTERN, -i PATTERN, 985 –keep-pot, 986 –locale LOCALE, -l LOCALE, 985 –no-default-ignore, 986 –no-location, 986 –no-wrap, 986 –symlinks, -s, 985 makemigrations django-admin command, 986 makemigrations command line option –check, 987 –dry-run, 986 –empty, 986 –merge, 987 –name NAME, -n NAME, 987 –noinput, –no-input, 986 MakeValid (class in django.contrib.gis.db.models.functions), 818 managed (Options attribute), 1125 Manager (class in django.db.models), 133 MANAGERS setting, 1270 managers.CurrentSiteManager (class in django.contrib.sites), 928 manifest_strict (storage.ManifestStaticFilesStorage attribute), 935 many_to_many (Field attribute), 1115 many_to_one (Field attribute), 1115 ManyToManyField (class in django.db.models), 1108 map_height (BaseGeometryWidget attribute), 801 map_height (GeoModelAdmin attribute), 874 map_srid (BaseGeometryWidget attribute), 801 map_template (GeoModelAdmin attribute), 874 map_width (BaseGeometryWidget attribute), 801 map_width (GeoModelAdmin attribute), 874

    Index

    Django Documentation, Release 2.1.dev20171226153947

    mapping() (in module django.contrib.gis.utils), 872 mark_safe() (in module django.utils.safestring), 1387 match (FilePathField attribute), 1044, 1101 Max (class in django.db.models), 1187 max (GDALBand attribute), 861 max_digits (DecimalField attribute), 1042, 1097 max_length (CharField attribute), 1039, 1095 max_length (SimpleArrayField attribute), 905 max_length (URLField attribute), 1048 max_num (InlineModelAdmin attribute), 733 max_post_process_passes (storage.ManifestStaticFilesStorage attribute), 935 max_value (DecimalField attribute), 1042 max_value (IntegerField attribute), 1045 max_x (Envelope attribute), 851 max_y (Envelope attribute), 852 MaxLengthValidator (class in django.core.validators), 1395 MaxValueValidator (class in django.core.validators), 1395 mean (GDALBand attribute), 861 MEDIA_ROOT setting, 1270 MEDIA_URL setting, 1270 MemoryFileUploadHandler (class in django.core.files.uploadhandler), 1012 MemSize (class in django.contrib.gis.db.models.functions), 819 merged (MultiLineString attribute), 834 message (EmailValidator attribute), 1393 message (ProhibitNullCharactersValidator attribute), 1396 message (RegexValidator attribute), 1393 message file, 487 MESSAGE_LEVEL setting, 1283 MESSAGE_STORAGE setting, 1283 MESSAGE_TAGS setting, 1283 message_user() (ModelAdmin method), 729 MessageMiddleware (class in django.contrib.messages.middleware), 1078 META (HttpRequest attribute), 1231 metadata (GDALBand attribute), 862 metadata (GDALRaster attribute), 860 method (HttpRequest attribute), 1230 method_decorator() (in module django.utils.decorators), 1379 MIDDLEWARE setting, 1271

    Index

    middleware.RedirectFallbackMiddleware (class in django.contrib.redirects), 916 MiddlewareNotUsed, 1004 migrate django-admin command, 987 migrate command line option –database DATABASE, 987 –fake, 987 –fake-initial, 987 –noinput, –no-input, 987 –run-syncdb, 987 MIGRATION_MODULES setting, 1271 Min (class in django.db.models), 1188 min (GDALBand attribute), 861 min_length (CharField attribute), 1039 min_length (SimpleArrayField attribute), 905 min_length (URLField attribute), 1048 min_num (InlineModelAdmin attribute), 733 min_value (DecimalField attribute), 1042 min_value (IntegerField attribute), 1045 min_x (Envelope attribute), 851 min_y (Envelope attribute), 851 MinimumLengthValidator (class in django.contrib.auth.password_validation), 390 MinLengthValidator (class in django.core.validators), 1395 minute field lookup type, 1184 MinValueValidator (class in django.core.validators), 1395 missing_args_message (BaseCommand attribute), 538 mode (File attribute), 1007 model, 1407 Model (class in django.db.models), 1130 model (ContentType attribute), 754 model (django.views.generic.detail.SingleObjectMixin attribute), 663 model (django.views.generic.edit.ModelFormMixin attribute), 669 model (django.views.generic.list.MultipleObjectMixin attribute), 665 model (Field attribute), 1115 model (InlineModelAdmin attribute), 732 Model.DoesNotExist, 1142 model_class() (ContentType method), 754 ModelAdmin (class in django.contrib.admin), 702 ModelBackend (class in django.contrib.auth.backends), 751 ModelChoiceField (class in django.forms), 1051 ModelForm (class in django.forms), 247 modelform_factory() (in module django.forms.models), 1053

    1833

    Django Documentation, Release 2.1.dev20171226153947

    modelformset_factory() (in module django.forms.models), 1053 ModelMultipleChoiceField (class in django.forms), 1052 models.AbstractBaseUser (class in django.contrib.auth), 401 models.AbstractUser (class in django.contrib.auth), 402 models.AnonymousUser (class in django.contrib.auth), 749 models.BaseInlineFormSet (class in django.forms), 263 models.BaseModelFormSet (class in django.forms), 258 models.BaseUserManager (class in django.contrib.auth), 403 models.CustomUser (class in django.contrib.auth), 400, 404 models.CustomUserManager (class in django.contrib.auth), 402 models.Group (class in django.contrib.auth), 750 models.LogEntry (class in django.contrib.admin), 743 models.Permission (class in django.contrib.auth), 749 models.PermissionsMixin (class in django.contrib.auth), 404 models.ProtectedError, 1005 models.Redirect (class in django.contrib.redirects), 916 models.Site (class in django.contrib.sites), 924 models.User (class in django.contrib.auth), 746, 747 models.UserManager (class in django.contrib.auth), 749 models_module (AppConfig attribute), 626 modifiable (GeoModelAdmin attribute), 874 modify_settings() (in module django.test), 344 modify_settings() (SimpleTestCase method), 344 module (AppConfig attribute), 626 month field lookup type, 1182 month (MonthMixin attribute), 671 MONTH_DAY_FORMAT setting, 1271 month_format (MonthMixin attribute), 671 MonthArchiveView (built-in class), 683 MonthArchiveView (class in django.views.generic.dates), 654 MonthMixin (class in django.views.generic.dates), 671 months (SelectDateWidget attribute), 1069 MTV, 1407 multi_db (TransactionTestCase attribute), 343 MultiLineString (class in django.contrib.gis.geos), 834 MultiLineStringField (class in django.contrib.gis.db.models), 790 MultiLineStringField (class in django.contrib.gis.forms), 800 multiple_chunks() (File method), 1007 multiple_chunks() (UploadedFile method), 1011 MultipleChoiceField (class in django.forms), 1045 MultipleHiddenInput (class in django.forms), 1068 MultipleObjectsReturned, 1003

    1834

    MultiPoint (class in django.contrib.gis.geos), 834 MultiPointField (class in django.contrib.gis.db.models), 790 MultiPointField (class in django.contrib.gis.forms), 800 MultiPolygon (class in django.contrib.gis.geos), 835 MultiPolygonField (class in django.contrib.gis.db.models), 790 MultiPolygonField (class in django.contrib.gis.forms), 800 MultiValueField (class in django.forms), 1049 MultiWidget (class in django.forms), 1060 MVC, 1407

    N NAME setting, 1253 name (AppConfig attribute), 625 name (BoundField attribute), 1029 name (ContentType attribute), 754 name (CreateExtension attribute), 910 name (DataSource attribute), 840 name (Field attribute), 844 name (FieldFile attribute), 1099 name (File attribute), 1006 name (GDALRaster attribute), 856 name (Index attribute), 1116 name (Layer attribute), 841 name (models.Group attribute), 750 name (models.Permission attribute), 749 name (models.Site attribute), 924 name (OGRGeomType attribute), 851 name (Origin attribute), 1363 name (SpatialReference attribute), 854 name (UploadedFile attribute), 1011 namespace (ResolverMatch attribute), 1374 namespaces (ResolverMatch attribute), 1374 naturalday template filter, 879 naturaltime template filter, 880 never_cache() (in module django.views.decorators.cache), 201 new_file() (FileUploadHandler method), 1013 new_objects (models.BaseModelFormSet attribute), 260 next_page_number() (Page method), 501 ngettext() (in module django.utils.translation), 1390 ngettext_lazy() (in module django.utils.translation), 1390 nodata_value (GDALBand attribute), 861 non_atomic_requests() (in module django.db.transaction), 146 NON_FIELD_ERRORS (in module django.core.exceptions), 1004 non_field_errors() (Form method), 1016

    Index

    Django Documentation, Release 2.1.dev20171226153947

    none() (in module django.db.models.query.QuerySet), object_id (LogEntry attribute), 743 1153 object_list (Page attribute), 501 noop (RunSQL attribute), 1085 object_repr (LogEntry attribute), 743 noop() (RunPython static method), 1087 ObjectDoesNotExist, 1002 NoReverseMatch, 1005 objects (Model attribute), 1122 normalize() (GEOSGeometry method), 832 ogr (GEOSGeometry attribute), 829 normalize_email() (django.contrib.auth.models.BaseUserManager OGRGeometry (class in django.contrib.gis.gdal), 846 class method), 403 OGRGeomType (class in django.contrib.gis.gdal), 851 normalize_username() (django.contrib.auth.models.AbstractBaseUser ogrinspect class method), 401 django-admin command, 873 NotSupportedError, 1005 ogrinspect command line option now –blank BLANK, 873 template tag, 1322 –decimal DECIMAL, 873 Now (class in django.db.models.functions), 1220 –geom-name GEOM_NAME, 873 now() (in module django.utils.timezone), 1389 –layer LAYER_KEY, 873 npgettext() (in module django.utils.translation), 1390 –mapping, 873 npgettext_lazy() (in module django.utils.translation), –multi-geom, 873 1390 –name-field NAME_FIELD, 873 NthValue (class in django.db.models.functions), 1228 –no-imports, 873 Ntile (class in django.db.models.functions), 1228 –null NULL, 873 null (Field attribute), 1089 –srid SRID, 873 NullBooleanField (class in django.db.models), 1102 on_commit() (in module django.db.transaction), 149 NullBooleanField (class in django.forms), 1046 on_delete (ForeignKey attribute), 1106 NullBooleanSelect (class in django.forms), 1065 one_to_many (Field attribute), 1115 num (OGRGeomType attribute), 851 one_to_one (Field attribute), 1115 num_coords (GEOSGeometry attribute), 828 OneToOneField (class in django.db.models), 1111 num_coords (OGRGeometry attribute), 847 only() (in module django.db.models.query.QuerySet), num_feat (Layer attribute), 841 1164 num_fields (Feature attribute), 844 open() (django.contrib.gis.geoip2.GeoIP2 class method), num_fields (Layer attribute), 841 867 num_geom (GEOSGeometry attribute), 828 open() (FieldFile method), 1100 num_interior_rings (Polygon attribute), 834 open() (File method), 1007 num_items() (SyndicationFeed method), 1382 open() (Storage method), 1010 num_pages (Paginator attribute), 500 openlayers_url (GeoModelAdmin attribute), 874 num_points (OGRGeometry attribute), 847 OpenLayersWidget (class in number (Page attribute), 501 django.contrib.gis.forms.widgets), 801 NUMBER_GROUPING OperationalError, 1005 setting, 1272 OPTIONS NumberInput (class in django.forms), 1062 setting, 1254 NumericPasswordValidator (class in Options (class in django.db.models.options), 1116 django.contrib.auth.password_validation), options() (Client method), 331 391 options() (django.views.generic.base.View method), 642 NumGeometries (class in order_by() (in module django.contrib.gis.db.models.functions), django.db.models.query.QuerySet), 1146 819 order_fields() (Form method), 1026 NumPoints (class in django.contrib.gis.db.models.functions),order_with_respect_to (Options attribute), 1125 819 ordered (QuerySet attribute), 1144 ordering (django.views.generic.list.MultipleObjectMixin O attribute), 666 ordering (ModelAdmin attribute), 717 object (django.views.generic.edit.CreateView attribute), ordering (Options attribute), 1126 649 ordinal object (django.views.generic.edit.UpdateView attribute), template filter, 880 650 Origin (class in django.template.base), 1363 object_history_template (ModelAdmin attribute), 721 Index

    1835

    Django Documentation, Release 2.1.dev20171226153947

    origin (GDALRaster attribute), 858 OSMGeoAdmin (class in django.contrib.gis.admin), 874 OSMWidget (class in django.contrib.gis.forms.widgets), 801 outdim (WKBWriter attribute), 837 outdim (WKTWriter attribute), 838 OuterRef (class in django.db.models), 1201 output_field (in module django.db.models), 1192 output_field (Transform attribute), 1193 output_transaction (BaseCommand attribute), 538 overlaps field lookup type, 806 overlaps() (GEOSGeometry method), 830 overlaps() (OGRGeometry method), 849 overlaps() (PreparedGeometry method), 836 overlaps_above field lookup type, 809 overlaps_below field lookup type, 809 overlaps_left field lookup type, 808 overlaps_right field lookup type, 809 override() (in module django.utils.timezone), 1389 override() (in module django.utils.translation), 1391 override_settings() (in module django.test), 344

    password_change_done_template (AdminSite attribute), 740 password_change_template (AdminSite attribute), 740 password_changed() (in module django.contrib.auth.password_validation), 391 PASSWORD_HASHERS setting, 1282 PASSWORD_RESET_TIMEOUT_DAYS setting, 1282 password_validators_help_text_html() (in module django.contrib.auth.password_validation), 391 password_validators_help_texts() (in module django.contrib.auth.password_validation), 391 PasswordChangeDoneView (class in django.contrib.auth.views), 377 PasswordChangeForm (class in django.contrib.auth.forms), 381 PasswordChangeView (class in django.contrib.auth.views), 377 PasswordInput (class in django.forms), 1063 PasswordResetCompleteView (class in django.contrib.auth.views), 379 PasswordResetConfirmView (class in django.contrib.auth.views), 379 PasswordResetDoneView (class in P django.contrib.auth.views), 378 PasswordResetForm (class in django.contrib.auth.forms), packages (JavaScriptCatalog attribute), 457 381 Page (class in django.core.paginator), 501 PasswordResetView (class in django.contrib.auth.views), page() (Paginator method), 500 377 page_kwarg (django.views.generic.list.MultipleObjectMixin Patch release, 1775 attribute), 666 patch() (Client method), 332 page_range (Paginator attribute), 500 patch_cache_control() (in module django.utils.cache), PageNotAnInteger, 501 1378 paginate_by (django.views.generic.list.MultipleObjectMixin patch_response_headers() (in module django.utils.cache), attribute), 666 1378 paginate_orphans (django.views.generic.list.MultipleObjectMixin patch_vary_headers() (in module django.utils.cache), attribute), 666 paginate_queryset() (django.views.generic.list.MultipleObjectMixin 1378 path (AppConfig attribute), 625 method), 666 path (FilePathField attribute), 1043, 1101 Paginator (class in django.core.paginator), 499 path (HttpRequest attribute), 1230 paginator (ModelAdmin attribute), 717 path() (in module django.urls), 1375 paginator (Page attribute), 501 path() (Storage method), 1010 paginator_class (django.views.generic.list.MultipleObjectMixin path_info (HttpRequest attribute), 1230 attribute), 666 pattern_name (django.views.generic.base.RedirectView parent_link (OneToOneField attribute), 1112 attribute), 644 parse_date() (in module django.utils.dateparse), 1379 PercentRank (class in django.db.models.functions), 1229 parse_datetime() (in module django.utils.dateparse), 1379 Perimeter (class in django.contrib.gis.db.models.functions), parse_duration() (in module django.utils.dateparse), 1379 819 parse_time() (in module django.utils.dateparse), 1379 permanent (django.views.generic.base.RedirectView atPASSWORD tribute), 644 setting, 1254 permission_denied_message (AccessMixin attribute), password (models.User attribute), 746 1836

    Index

    Django Documentation, Release 2.1.dev20171226153947

    372 template filter, 1339 permission_required() (in module pre_init (django.db.models.signals attribute), 1293 django.contrib.auth.decorators), 371 pre_save() (Field method), 1113 PermissionDenied, 1004 precision (Field attribute), 845 PermissionRequiredMixin (class in precision (WKTWriter attribute), 839 django.contrib.auth.mixins), 371 Prefetch (class in django.db.models), 1189 permissions (models.Group attribute), 750 prefetch_related() (in module permissions (Options attribute), 1127 django.db.models.query.QuerySet), 1156 PersistentRemoteUserMiddleware (class in prefetch_related_objects() (in module django.db.models), django.contrib.auth.middleware), 1080 1190 pgettext() (in module django.utils.translation), 1390 prefix (django.views.generic.edit.FormMixin attribute), pgettext_lazy() (in module django.utils.translation), 1390 668 phone2numeric prefix (Form attribute), 1033 template filter, 1338 prepared (GEOSGeometry attribute), 832 ping_google PreparedGeometry (class in django.contrib.gis.geos), 835 django-admin command, 924 PREPEND_WWW ping_google() (in module django.contrib.sitemaps), 923 setting, 1272 pixel_count (GDALBand attribute), 860 prepopulated_fields (ModelAdmin attribute), 717 pk (Model attribute), 1136 preserve_filters (ModelAdmin attribute), 717 pk_url_kwarg (django.views.generic.detail.SingleObjectMixin pretty_wkt (SpatialReference attribute), 854 attribute), 663 previous_page_number() (Page method), 501 pluralize primary_key (Field attribute), 1093 template filter, 1339 priority (Sitemap attribute), 919 Point (class in django.contrib.gis.gdal), 850 process_exception(), 212 Point (class in django.contrib.gis.geos), 832 process_lhs() (Lookup method), 1193 point_count (OGRGeometry attribute), 846 process_rhs() (Lookup method), 1193 point_on_surface (GEOSGeometry attribute), 831 process_template_response(), 212 PointField (class in django.contrib.gis.db.models), 789 process_view(), 211 PointField (class in django.contrib.gis.forms), 800 ProgrammingError, 1005 PointOnSurface (class in ProhibitNullCharactersValidator (class in django.contrib.gis.db.models.functions), django.core.validators), 1396 819 proj (SpatialReference attribute), 854 Polygon (class in django.contrib.gis.gdal), 850 proj4 (SpatialReference attribute), 855 Polygon (class in django.contrib.gis.geos), 833 project, 1407 PolygonField (class in django.contrib.gis.db.models), 790 project() (GEOSGeometry method), 830 PolygonField (class in django.contrib.gis.forms), 800 project_normalized() (GEOSGeometry method), 830 pop() (backends.base.SessionBase method), 217 projected (SpatialReference attribute), 854 pop() (Context method), 1354 property, 1407 pop() (QueryDict method), 1236 PROTECT (in module django.db.models), 1106 popitem() (QueryDict method), 1236 protocol (GenericIPAddressField attribute), 1045, 1102 popup_response_template (ModelAdmin attribute), 721 protocol (Sitemap attribute), 919 PORT proxy (Options attribute), 1128 setting, 1254 push() (Context method), 1354 PositiveIntegerField (class in django.db.models), 1103 put() (Client method), 331 PositiveSmallIntegerField (class in django.db.models), put() (django.views.generic.edit.ProcessFormView 1103 method), 670 POST (HttpRequest attribute), 1230 Python Enhancement Proposals post() (Client method), 330 PEP 20, 1401 post() (django.views.generic.edit.ProcessFormView PEP 234, 1171 method), 670 PEP 249, 145, 149, 152, 968, 1005, 1172, 1413 post_process() (storage.StaticFilesStorage method), 934 PEP 257, 1735 POSTGIS_VERSION PEP 3134, 1005 setting, 876 PEP 318, 344 pprint PEP 3333, 82, 614, 1232

    Index

    1837

    Django Documentation, Release 2.1.dev20171226153947

    PEP 343, 343 PEP 420, 627 PEP 440, 977, 1458 PEP 487, 1412 PEP 8, 1725, 1735 python_2_unicode_compatible() (in django.utils.encoding), 1380 PYTHONPATH, 1556 PYTHONSTARTUP, 990 PYTHONWARNINGS, 586

    field lookup type, 902 rangefield.isempty field lookup type, 903 rangefield.not_gt field lookup type, 902 module rangefield.not_lt field lookup type, 902 rangefield.overlap field lookup type, 902 rangefield.startswith field lookup type, 903 Q RangeMaxValueValidator (class in django.contrib.postgres.validators), 915 Q (class in django.db.models), 1189 RangeMinValueValidator (class in quarter django.contrib.postgres.validators), 915 field lookup type, 1183 RangeWidget (class in django.contrib.postgres.forms), query_pk_and_slug (django.views.generic.detail.SingleObjectMixin 907 attribute), 663 query_string (django.views.generic.base.RedirectView Rank (class in django.db.models.functions), 1229 RasterField (class in django.contrib.gis.db.models), 790 attribute), 644 raw() (in module django.db.models.query.QuerySet), QueryDict (class in django.http), 1234 1166 queryset, 1407 raw() (Manager method), 140 QuerySet (class in django.db.models.query), 1144 queryset (django.views.generic.detail.SingleObjectMixin raw_id_fields (InlineModelAdmin attribute), 733 raw_id_fields (ModelAdmin attribute), 718 attribute), 663 queryset (django.views.generic.list.MultipleObjectMixin RawSQL (class in django.db.models.expressions), 1203 re_path() (in module django.urls), 1375 attribute), 665 read() (HttpRequest method), 1234 queryset (ModelChoiceField attribute), 1051 read() (UploadedFile method), 1011 queryset (ModelMultipleChoiceField attribute), 1052 readable() (HttpResponse method), 1240 readline() (HttpRequest method), 1234 R readlines() (HttpRequest method), 1234 radio_fields (ModelAdmin attribute), 718 readonly_fields (ModelAdmin attribute), 719 RadioSelect (class in django.forms), 1066 ready (apps attribute), 627 raise_exception (AccessMixin attribute), 372 ready() (AppConfig method), 626 random reason_phrase (HttpResponse attribute), 1238 template filter, 1339 RandomUUID (class in reason_phrase (StreamingHttpResponse attribute), 1243 receive_data_chunk() (FileUploadHandler method), 1012 django.contrib.postgres.functions), 907 receiver() (in module django.dispatch), 525 range recursive (FilePathField attribute), 1044, 1101 field lookup type, 1181 range_type (django.contrib.postgres.forms.BaseRangeField redirect() (in module django.shortcuts), 207 redirect_field_name (AccessMixin attribute), 372 attribute), 904 redirect_to_login() (in module range_type (RangeField attribute), 903 django.contrib.auth.views), 379 RangeField (class in django.contrib.postgres.fields), 903 RedirectView (built-in class), 675 rangefield.adjacent_to refresh_from_db() (Model method), 1132 field lookup type, 902 regex rangefield.contained_by field lookup type, 1185 field lookup type, 901 regex (RegexField attribute), 1046 rangefield.contains regex (RegexValidator attribute), 1392 field lookup type, 901 RegexField (class in django.forms), 1046 rangefield.endswith RegexValidator (class in django.core.validators), 1392 field lookup type, 903 register() (AdminSite method), 741 rangefield.fully_gt register() (in module django.contrib.admin), 703 field lookup type, 902 register() (in module django.core.checks), 529 rangefield.fully_lt 1838

    Index

    Django Documentation, Release 2.1.dev20171226153947

    register_converter() (in module django.urls), 1376 1084 register_lookup() (django.db.models.lookups.RegisterLookupMixin RenameField (class in django.db.migrations.operations), class method), 1191 1084 RegrAvgX (class in django.contrib.postgres.aggregates), RenameModel (class in django.db.migrations.operations), 889 1083 RegrAvgY (class in django.contrib.postgres.aggregates), render() (in module django.shortcuts), 205 889 render() (SimpleTemplateResponse method), 1364 RegrCount (class in django.contrib.postgres.aggregates), render() (Template method), 273, 1351 890 render() (Widget method), 1060 RegrIntercept (class in render_to_response() (django.views.generic.base.TemplateResponseMixin django.contrib.postgres.aggregates), 890 method), 662 regroup render_to_response() (in module django.shortcuts), 206 template tag, 1323 render_to_string() (in module django.template.loader), RegrR2 (class in django.contrib.postgres.aggregates), 890 275 RegrSlope (class in django.contrib.postgres.aggregates), render_value (PasswordInput attribute), 1063 890 rendered_content (SimpleTemplateResponse attribute), RegrSXX (class in django.contrib.postgres.aggregates), 1364 890 request (Response attribute), 334 RegrSXY (class in django.contrib.postgres.aggregates), RequestContext (class in django.template), 1356 890 RequestFactory (class in django.test), 352 RegrSYY (class in django.contrib.postgres.aggregates), requests.RequestSite (class in django.contrib.sites), 930 890 require_all_fields (MultiValueField attribute), 1049 rel_db_type() (Field method), 1113 require_GET() (in module django.views.decorators.http), relabeled_clone() (Expression method), 1206 200 relate require_http_methods() (in module field lookup type, 806 django.views.decorators.http), 200 relate() (GEOSGeometry method), 831 require_POST() (in module relate_pattern() (GEOSGeometry method), 830 django.views.decorators.http), 200 related_model (Field attribute), 1115 require_safe() (in module django.views.decorators.http), related_name (ForeignKey attribute), 1107 200 related_name (ManyToManyField attribute), 1109 required (Field attribute), 1034 related_query_name (ForeignKey attribute), 1107 required_css_class (Form attribute), 1022 related_query_name (GenericRelation attribute), 757 required_db_features (Options attribute), 1128 related_query_name (ManyToManyField attribute), 1109 required_db_vendor (Options attribute), 1128 RelatedManager (class in REQUIRED_FIELDS (models.CustomUser attribute), django.db.models.fields.related), 1120 400 relation_name (FilteredRelation attribute), 1190 RequireDebugFalse (class in django.utils.log), 496 RemoteUserBackend (class in RequireDebugTrue (class in django.utils.log), 497 django.contrib.auth.backends), 752 requires_csrf_token() (in module RemoteUserMiddleware (class in django.views.decorators.csrf), 961 django.contrib.auth.middleware), 1080 requires_migrations_checks (BaseCommand attribute), remove() (RelatedManager method), 1121 538 remove_field() (BaseDatabaseSchemaEditor method), requires_system_checks (BaseCommand attribute), 538 1245 reset_sequences (TransactionTestCase attribute), 356 remove_index() (BaseDatabaseSchemaEditor method), resetcycle 1244 template tag, 1325 remove_stale_contenttypes resolve() (in module django.urls), 1373 django-admin command, 997 resolve_context() (SimpleTemplateResponse method), remove_stale_contenttypes command line option 1364 –database DATABASE, 997 resolve_expression() (Expression method), 1206 remove_trailing_nulls (SplitArrayField attribute), 905 resolve_template() (SimpleTemplateResponse method), RemoveField (class in django.db.migrations.operations), 1364 1084 Resolver404, 1005 RemoveIndex (class in django.db.migrations.operations), resolver_match (HttpRequest attribute), 1231

    Index

    1839

    Django Documentation, Release 2.1.dev20171226153947

    resolver_match (Response attribute), 334 rhs (Lookup attribute), 1193 ResolverMatch (class in django.urls), 1373 right Response (class in django.test), 333 field lookup type, 808 response_add() (ModelAdmin method), 729 ring (GEOSGeometry attribute), 828 response_change() (ModelAdmin method), 729 rjust response_class (django.views.generic.base.TemplateResponseMixin template filter, 1339 attribute), 662 rollback() (in module django.db.transaction), 152 response_delete() (ModelAdmin method), 729 root_attributes() (SyndicationFeed method), 1382 response_gone_class (middle- ROOT_URLCONF ware.RedirectFallbackMiddleware attribute), setting, 1272 916 RowNumber (class in django.db.models.functions), 1229 response_redirect_class (CommonMiddleware attribute), RowRange (class in django.db.models.expressions), 1205 1076 Rss201rev2Feed (class in django.utils.feedgenerator), response_redirect_class (LocaleMiddleware attribute), 1382 1077 RssFeed (class in django.utils.feedgenerator), 1382 response_redirect_class (middle- RssUserland091Feed (class in ware.RedirectFallbackMiddleware attribute), django.utils.feedgenerator), 1383 916 run_checks() (DiscoverRunner method), 360 Reverse (class in django.contrib.gis.db.models.functions), run_suite() (DiscoverRunner method), 360 820 run_tests() (DiscoverRunner method), 359 reverse() (in module django.db.models.query.QuerySet), RunPython (class in django.db.migrations.operations), 1147 1086 reverse() (in module django.urls), 1372 runserver reverse_lazy() (in module django.urls), 1373 django-admin command, 933, 988 reverse_ordering() (Expression method), 1207 runserver command line option RFC –insecure, 934 RFC 1034, 1454, 1483 –ipv6, -6, 988 RFC 1123, 1386 –noreload, 988 RFC 2046#section-5.2.1, 438 –nostatic, 933 RFC 2109, 1239, 1285 –nothreading, 988 RFC 2396, 1141 RunSQL (class in django.db.migrations.operations), 1085 RFC 2616, 1441, 1485, 1636 S RFC 2732, 1393 RFC 3987#section-3.1, 1369, 1381 safe RFC 3987#section-3.2, 1369, 1381 template filter, 1340 RFC 4291#section-2.2, 1045, 1102 SafeExceptionReporterFilter (class in RFC 5322, 1331 django.views.debug), 591 RFC 6265, 1239, 1454, 1468, 1496 safeseq RFC 7231, 960, 1485 template filter, 1340 RFC 7231#section-4.2.1, 956, 1169 SafeString (class in django.utils.safestring), 1387 RFC 7231#section-4.3.4, 430 SafeText (class in django.utils.safestring), 1387 RFC 7231#section-4.3.8, 332 same_as RFC 7231#section-6, 1238, 1239, 1243 field lookup type, 805 RFC 7231#section-6.1, 1238, 1243 sample (CovarPop attribute), 889 RFC 7231#section-6.5.3, 1397 sample (StdDev attribute), 1188 RFC 7231#section-7.1.1.1, 1386 sample (Variance attribute), 1188 RFC 7231#section-7.1.4, 425, 1378 save() (base_session.BaseSessionManager method), 224 RFC 7232, 1441 save() (FieldFile method), 1100 RFC 7232#section-2.1, 1077 save() (File method), 1008 RFC 7232#section-4.1, 428 save() (LayerMapping method), 870 RFC 7234, 426 save() (Model method), 1135 RFC 7234#section-4.2.2, 1441 save() (Storage method), 1010 RFC 7234#section-5.2.2.8, 426 save_as (ModelAdmin attribute), 719 RFC 7239#page-7, 1280 save_as_continue (ModelAdmin attribute), 719 1840

    Index

    Django Documentation, Release 2.1.dev20171226153947

    save_formset() (ModelAdmin method), 722 save_model() (ModelAdmin method), 722 save_on_top (ModelAdmin attribute), 720 save_related() (ModelAdmin method), 723 savepoint() (in module django.db.transaction), 153 savepoint_commit() (in module django.db.transaction), 153 savepoint_rollback() (in module django.db.transaction), 153 Scale (class in django.contrib.gis.db.models.functions), 820 scale (GDALRaster attribute), 858 scheme (HttpRequest attribute), 1230 schemes (URLValidator attribute), 1393 search field lookup type, 911 search_fields (ModelAdmin attribute), 720 SearchQuery (class in django.contrib.postgres.search), 912 SearchRank (class in django.contrib.postgres.search), 912 SearchVector (class in django.contrib.postgres.search), 911 SearchVectorField (class in django.contrib.postgres.search), 913 second field lookup type, 1185 SECRET_KEY setting, 1272 SECURE_BROWSER_XSS_FILTER setting, 1273 SECURE_CONTENT_TYPE_NOSNIFF setting, 1273 SECURE_HSTS_INCLUDE_SUBDOMAINS setting, 1273 SECURE_HSTS_PRELOAD setting, 1273 SECURE_HSTS_SECONDS setting, 1274 SECURE_PROXY_SSL_HEADER setting, 1274 SECURE_REDIRECT_EXEMPT setting, 1275 SECURE_SSL_HOST setting, 1275 SECURE_SSL_REDIRECT setting, 1275 SecurityMiddleware (class in django.middleware.security), 1078 seekable() (HttpResponse method), 1240 Select (class in django.forms), 1065 select_for_update() (in module django.db.models.query.QuerySet), 1165 select_on_save (Options attribute), 1128

    Index

    select_related() (in module django.db.models.query.QuerySet), 1154 select_template() (Engine method), 1350 select_template() (in module django.template.loader), 273 SelectDateWidget (class in django.forms), 1069 SelectMultiple (class in django.forms), 1066 semi_major (SpatialReference attribute), 854 semi_minor (SpatialReference attribute), 854 send() (Signal method), 527 send_mail() (AdminEmailHandler method), 496 send_mail() (in module django.core.mail), 433 send_mail() (PasswordResetForm method), 381 send_mass_mail() (in module django.core.mail), 434 send_robust() (Signal method), 527 sendtestemail django-admin command, 989 sendtestemail command line option –admins, 989 –managers, 989 sensitive_post_parameters() (in module django.views.decorators.debug), 590 sensitive_variables() (in module django.views.decorators.debug), 589 SeparateDatabaseAndState (class in django.db.migrations.operations), 1087 SERIALIZATION_MODULES setting, 1275 serializers.JSONSerializer (class in django.contrib.sessions), 218 serializers.PickleSerializer (class in django.contrib.sessions), 218 SERVER_EMAIL setting, 1275 session (Client attribute), 335 session (HttpRequest attribute), 1232 SESSION_CACHE_ALIAS setting, 1284 SESSION_COOKIE_AGE setting, 1284 SESSION_COOKIE_DOMAIN setting, 1284 SESSION_COOKIE_HTTPONLY setting, 1285 SESSION_COOKIE_NAME setting, 1285 SESSION_COOKIE_PATH setting, 1285 SESSION_COOKIE_SECURE setting, 1285 session_data (base_session.AbstractBaseSession attribute), 224 SESSION_ENGINE setting, 1285

    1841

    Django Documentation, Release 2.1.dev20171226153947

    SESSION_EXPIRE_AT_BROWSER_CLOSE setting, 1286 SESSION_FILE_PATH setting, 1286 session_key (base_session.AbstractBaseSession attribute), 224 SESSION_SAVE_EVERY_REQUEST setting, 1286 SESSION_SERIALIZER setting, 1286 SessionMiddleware (class in django.contrib.sessions.middleware), 1080 SET() (in module django.db.models), 1106 set() (RelatedManager method), 1122 set_autocommit() (in module django.db.transaction), 152 set_cookie() (HttpResponse method), 1239 SET_DEFAULT (in module django.db.models), 1106 set_expiry() (backends.base.SessionBase method), 217 set_language() (in module django.views.i18n), 468 SET_NULL (in module django.db.models), 1106 set_password() (models.AbstractBaseUser method), 401 set_password() (models.User method), 748 set_rollback() (in module django.db.transaction), 153 set_signed_cookie() (HttpResponse method), 1239 set_source_expressions() (Expression method), 1206 set_test_cookie() (backends.base.SessionBase method), 217 set_unusable_password() (models.AbstractBaseUser method), 402 set_unusable_password() (models.User method), 748 setdefault() (backends.base.SessionBase method), 217 setdefault() (Context method), 1354 setdefault() (HttpResponse method), 1239 setdefault() (QueryDict method), 1235 setlist() (QueryDict method), 1236 setlistdefault() (QueryDict method), 1236 SetPasswordForm (class in django.contrib.auth.forms), 381 setting ABSOLUTE_URL_OVERRIDES, 1246 ADMINS, 1246 ALLOWED_HOSTS, 1247 APPEND_SLASH, 1247 AUTH_PASSWORD_VALIDATORS, 1283 AUTH_USER_MODEL, 1281 AUTHENTICATION_BACKENDS, 1281 CACHE_MIDDLEWARE_ALIAS, 1249 CACHE_MIDDLEWARE_KEY_PREFIX, 1249 CACHE_MIDDLEWARE_SECONDS, 1249 CACHES, 1247 CACHES-BACKEND, 1248 CACHES-KEY_FUNCTION, 1248 CACHES-KEY_PREFIX, 1248 CACHES-LOCATION, 1248

    1842

    CACHES-OPTIONS, 1249 CACHES-TIMEOUT, 1249 CACHES-VERSION, 1249 CONN_MAX_AGE, 1253 CSRF_COOKIE_AGE, 1250 CSRF_COOKIE_DOMAIN, 1250 CSRF_COOKIE_HTTPONLY, 1250 CSRF_COOKIE_NAME, 1250 CSRF_COOKIE_PATH, 1251 CSRF_COOKIE_SECURE, 1251 CSRF_FAILURE_VIEW, 1251 CSRF_HEADER_NAME, 1251 CSRF_TRUSTED_ORIGINS, 1252 CSRF_USE_SESSIONS, 1251 DATA_UPLOAD_MAX_MEMORY_SIZE, 1258 DATA_UPLOAD_MAX_NUMBER_FIELDS, 1259 DATABASE-ATOMIC_REQUESTS, 1252 DATABASE-AUTOCOMMIT, 1253 DATABASE-DISABLE_SERVER_SIDE_CURSORS, 1254 DATABASE-ENGINE, 1253 DATABASE-TEST, 1255 DATABASE-TIME_ZONE, 1254 DATABASE_ROUTERS, 1259 DATABASES, 1252 DATAFILE, 1257 DATAFILE_EXTSIZE, 1258 DATAFILE_MAXSIZE, 1257 DATAFILE_SIZE, 1258 DATAFILE_TMP, 1257 DATAFILE_TMP_EXTSIZE, 1258 DATAFILE_TMP_MAXSIZE, 1258 DATAFILE_TMP_SIZE, 1258 DATE_FORMAT, 1259 DATE_INPUT_FORMATS, 1259 DATETIME_FORMAT, 1260 DATETIME_INPUT_FORMATS, 1260 DEBUG, 1260 DEBUG_PROPAGATE_EXCEPTIONS, 1261 DECIMAL_SEPARATOR, 1261 DEFAULT_CHARSET, 1261 DEFAULT_CONTENT_TYPE, 1261 DEFAULT_EXCEPTION_REPORTER_FILTER, 1262 DEFAULT_FILE_STORAGE, 1262 DEFAULT_FROM_EMAIL, 1262 DEFAULT_INDEX_TABLESPACE, 1262 DEFAULT_TABLESPACE, 1262 DISALLOWED_USER_AGENTS, 1262 EMAIL_BACKEND, 1262 EMAIL_FILE_PATH, 1263 EMAIL_HOST, 1263 EMAIL_HOST_PASSWORD, 1263

    Index

    Django Documentation, Release 2.1.dev20171226153947

    EMAIL_HOST_USER, 1263 EMAIL_PORT, 1263 EMAIL_SSL_CERTFILE, 1264 EMAIL_SSL_KEYFILE, 1264 EMAIL_SUBJECT_PREFIX, 1263 EMAIL_TIMEOUT, 1264 EMAIL_USE_LOCALTIME, 1263 EMAIL_USE_SSL, 1264 EMAIL_USE_TLS, 1264 FILE_CHARSET, 1264 FILE_UPLOAD_DIRECTORY_PERMISSIONS, 1265 FILE_UPLOAD_HANDLERS, 1264 FILE_UPLOAD_MAX_MEMORY_SIZE, 1265 FILE_UPLOAD_PERMISSIONS, 1265 FILE_UPLOAD_TEMP_DIR, 1265 FIRST_DAY_OF_WEEK, 1266 FIXTURE_DIRS, 1266 FORCE_SCRIPT_NAME, 1266 FORM_RENDERER, 1266 FORMAT_MODULE_PATH, 1266 GDAL_LIBRARY_PATH, 865 GEOIP_CITY, 868 GEOIP_COUNTRY, 868 GEOIP_PATH, 868 GEOS_LIBRARY_PATH, 839 HOST, 1253 IGNORABLE_404_URLS, 1267 INSTALLED_APPS, 1267 INTERNAL_IPS, 1268 LANGUAGE_CODE, 1268 LANGUAGE_COOKIE_AGE, 1268 LANGUAGE_COOKIE_DOMAIN, 1268 LANGUAGE_COOKIE_NAME, 1269 LANGUAGE_COOKIE_PATH, 1269 LANGUAGES, 1269 LOCALE_PATHS, 1269 LOGGING, 1270 LOGGING_CONFIG, 1270 LOGIN_REDIRECT_URL, 1282 LOGIN_URL, 1282 LOGOUT_REDIRECT_URL, 1282 MANAGERS, 1270 MEDIA_ROOT, 1270 MEDIA_URL, 1270 MESSAGE_LEVEL, 1283 MESSAGE_STORAGE, 1283 MESSAGE_TAGS, 1283 MIDDLEWARE, 1271 MIGRATION_MODULES, 1271 MONTH_DAY_FORMAT, 1271 NAME, 1253 NUMBER_GROUPING, 1272 OPTIONS, 1254

    Index

    PASSWORD, 1254 PASSWORD_HASHERS, 1282 PASSWORD_RESET_TIMEOUT_DAYS, 1282 PORT, 1254 POSTGIS_VERSION, 876 PREPEND_WWW, 1272 ROOT_URLCONF, 1272 SECRET_KEY, 1272 SECURE_BROWSER_XSS_FILTER, 1273 SECURE_CONTENT_TYPE_NOSNIFF, 1273 SECURE_HSTS_INCLUDE_SUBDOMAINS, 1273 SECURE_HSTS_PRELOAD, 1273 SECURE_HSTS_SECONDS, 1274 SECURE_PROXY_SSL_HEADER, 1274 SECURE_REDIRECT_EXEMPT, 1275 SECURE_SSL_HOST, 1275 SECURE_SSL_REDIRECT, 1275 SERIALIZATION_MODULES, 1275 SERVER_EMAIL, 1275 SESSION_CACHE_ALIAS, 1284 SESSION_COOKIE_AGE, 1284 SESSION_COOKIE_DOMAIN, 1284 SESSION_COOKIE_HTTPONLY, 1285 SESSION_COOKIE_NAME, 1285 SESSION_COOKIE_PATH, 1285 SESSION_COOKIE_SECURE, 1285 SESSION_ENGINE, 1285 SESSION_EXPIRE_AT_BROWSER_CLOSE, 1286 SESSION_FILE_PATH, 1286 SESSION_SAVE_EVERY_REQUEST, 1286 SESSION_SERIALIZER, 1286 SHORT_DATE_FORMAT, 1276 SHORT_DATETIME_FORMAT, 1276 SIGNING_BACKEND, 1276 SILENCED_SYSTEM_CHECKS, 1276 SITE_ID, 1286 STATIC_ROOT, 1287 STATIC_URL, 1287 STATICFILES_DIRS, 1287 STATICFILES_FINDERS, 1288 STATICFILES_STORAGE, 1288 TEMPLATES, 1276 TEMPLATES-APP_DIRS, 1277 TEMPLATES-BACKEND, 1277 TEMPLATES-DIRS, 1277 TEMPLATES-NAME, 1277 TEMPLATES-OPTIONS, 1277 TEST_CHARSET, 1255 TEST_COLLATION, 1255 TEST_CREATE, 1256 TEST_DEPENDENCIES, 1255 TEST_MIRROR, 1255

    1843

    Django Documentation, Release 2.1.dev20171226153947

    TEST_NAME, 1256 TEST_NON_SERIALIZED_APPS, 1278 TEST_PASSWD, 1257 TEST_RUNNER, 1278 TEST_SERIALIZE, 1256 TEST_TBLSPACE, 1257 TEST_TBLSPACE_TMP, 1257 TEST_TEMPLATE, 1256 TEST_USER, 1256 TEST_USER_CREATE, 1256 THOUSAND_SEPARATOR, 1278 TIME_FORMAT, 1278 TIME_INPUT_FORMATS, 1278 TIME_ZONE, 1279 USE_I18N, 1279 USE_L10N, 1279 USE_THOUSAND_SEPARATOR, 1280 USE_TZ, 1280 USE_X_FORWARDED_HOST, 1280 USE_X_FORWARDED_PORT, 1280 USER, 1254 WSGI_APPLICATION, 1280 X_FRAME_OPTIONS, 1281 YEAR_MONTH_FORMAT, 1281 settings() (SimpleTestCase method), 343 setup() (in module django), 628 setup_databases() (DiscoverRunner method), 360 setup_databases() (in module django.test.utils), 360 setup_test_environment() (DiscoverRunner method), 359 setup_test_environment() (in module django.test.utils), 360 setUpTestData() (django.test.TestCase class method), 338 shell django-admin command, 990 shell (Polygon attribute), 850 shell command line option –command COMMAND, -c COMMAND, 990 –interface {ipython,bpython,python}, -i {ipython,bpython,python}, 990 –nostartup, 990 SHORT_DATE_FORMAT setting, 1276 SHORT_DATETIME_FORMAT setting, 1276 shortcuts, 205 shortcuts.get_current_site() (in module django.contrib.sites), 931 show_change_link (InlineModelAdmin attribute), 734 show_full_result_count (ModelAdmin attribute), 720 showmigrations django-admin command, 990 showmigrations command line option –database DATABASE, 991 –list, -l, 990

    1844

    –plan, -p, 990 sign() (TimestampSigner method), 432 Signal (class in django.dispatch), 527 Signer (class in django.core.signing), 431 SIGNING_BACKEND setting, 1276 SILENCED_SYSTEM_CHECKS setting, 1276 simple (GEOSGeometry attribute), 828 simple_tag() (django.template.Library method), 561 SimpleArrayField (class in django.contrib.postgres.forms), 904 SimpleTemplateResponse (class in django.template.response), 1363 SimpleTestCase (class in django.test), 336 simplify() (GEOSGeometry method), 831 site (HttpRequest attribute), 1232 site_header (AdminSite attribute), 739 SITE_ID setting, 1286 site_title (AdminSite attribute), 740 site_url (AdminSite attribute), 740 Sitemap (class in django.contrib.sitemaps), 918 size (ArrayField attribute), 892 size (FieldFile attribute), 1100 size (File attribute), 1007 size (SplitArrayField attribute), 905 size (UploadedFile attribute), 1011 size() (Storage method), 1010 skew (GDALRaster attribute), 858 skipIfDBFeature() (in module django.test), 352 skipUnlessDBFeature() (in module django.test), 352 slice template filter, 1340 slug, 1407 slug_field (django.views.generic.detail.SingleObjectMixin attribute), 663 slug_url_kwarg (django.views.generic.detail.SingleObjectMixin attribute), 663 SlugField (class in django.db.models), 1103 SlugField (class in django.forms), 1047 slugify template filter, 1340 slugify() (in module django.utils.text), 1388 SmallIntegerField (class in django.db.models), 1103 smart_bytes() (in module django.utils.encoding), 1380 smart_str() (in module django.utils.encoding), 1380 smart_text() (in module django.utils.encoding), 1380 SnapToGrid (class in django.contrib.gis.db.models.functions), 820 spaceless template tag, 1326 spatial_filter (Layer attribute), 842 spatial_index (BaseSpatialField attribute), 791

    Index

    Django Documentation, Release 2.1.dev20171226153947

    SpatialReference (class in django.contrib.gis.gdal), 852 SplitArrayField (class in django.contrib.postgres.forms), 905 SplitDateTimeField (class in django.forms), 1050 SplitDateTimeWidget (class in django.forms), 1068 SplitHiddenDateTimeWidget (class in django.forms), 1069 sqlflush django-admin command, 991 sqlflush command line option –database DATABASE, 991 sqlmigrate django-admin command, 991 sqlmigrate command line option –backwards, 991 –database DATABASE, 991 sqlsequencereset django-admin command, 991 sqlsequencereset command line option –database DATABASE, 991 squashmigrations django-admin command, 991 squashmigrations command line option –no-optimize, 992 –noinput, –no-input, 992 –squashed-name SQUASHED_NAME, 992 srid (BaseSpatialField attribute), 790 srid (Field attribute), 799 srid (GDALRaster attribute), 857 srid (GEOSGeometry attribute), 828 srid (OGRGeometry attribute), 847 srid (SpatialReference attribute), 854 srid (WKBWriter attribute), 838 srs (GDALRaster attribute), 857 srs (GEOSGeometry attribute), 832 srs (Layer attribute), 842 srs (OGRGeometry attribute), 847 SRSException, 865 StackedInline (class in django.contrib.admin), 731 staff_member_required() (in module django.contrib.admin.views.decorators), 745 start_index() (Page method), 501 startapp django-admin command, 992 startapp command line option –extension EXTENSIONS, -e EXTENSIONS, 992 –name FILES, -n FILES, 992 –template TEMPLATE, 992 startproject django-admin command, 993 startproject command line option –extension EXTENSIONS, -e EXTENSIONS, 993 –name FILES, -n FILES, 993 –template TEMPLATE, 993

    Index

    startswith field lookup type, 1180 static template tag, 1347 static() (in module django.template.context_processors), 1358 static.serve() (in module django.views), 1396 static.static() (in module django.conf.urls), 1376 STATIC_ROOT setting, 1287 STATIC_URL setting, 1287 STATICFILES_DIRS setting, 1287 STATICFILES_FINDERS setting, 1288 STATICFILES_STORAGE setting, 1288 statistics() (GDALBand method), 860 status_code (HttpResponse attribute), 1238 status_code (Response attribute), 334 status_code (StreamingHttpResponse attribute), 1243 std (GDALBand attribute), 861 StdDev (class in django.db.models), 1188 Storage (class in django.core.files.storage), 1009 storage (FileField attribute), 1098 storage.base.BaseStorage (class in django.contrib.messages), 882 storage.base.Message (class in django.contrib.messages), 884 storage.CachedStaticFilesStorage (class in django.contrib.staticfiles), 935 storage.cookie.CookieStorage (class in django.contrib.messages), 881 storage.fallback.FallbackStorage (class in django.contrib.messages), 882 storage.ManifestStaticFilesStorage (class in django.contrib.staticfiles), 934 storage.session.SessionStorage (class in django.contrib.messages), 881 storage.StaticFilesStorage (class in django.contrib.staticfiles), 934 streaming (HttpResponse attribute), 1238 streaming (StreamingHttpResponse attribute), 1243 streaming_content (StreamingHttpResponse attribute), 1243 StreamingHttpResponse (class in django.http), 1242 strictly_above field lookup type, 809 strictly_below field lookup type, 810 StrIndex (class in django.db.models.functions), 1226 StringAgg (class in django.contrib.postgres.aggregates), 889

    1845

    Django Documentation, Release 2.1.dev20171226153947

    stringfilter() (django.template.defaultfilters method), 558 stringformat template filter, 1341 strip (CharField attribute), 1039 strip (RegexField attribute), 1047 strip_tags() (in module django.utils.html), 1386 striptags template filter, 1341 style (BaseCommand attribute), 538 Subquery (class in django.db.models), 1200 Substr (class in django.db.models.functions), 1227 success_url (django.views.generic.edit.DeletionMixin attribute), 670 success_url (django.views.generic.edit.FormMixin attribute), 668 success_url (django.views.generic.edit.ModelFormMixin attribute), 669 suite_result() (DiscoverRunner method), 360 Sum (class in django.db.models), 1188 supports_3d (BaseGeometryWidget attribute), 801 supports_microseconds (Widget attribute), 1059 SuspiciousOperation, 1003 swappable (ForeignKey attribute), 1108 swappable (ManyToManyField attribute), 1111 sym_difference() (GEOSGeometry method), 831 sym_difference() (OGRGeometry method), 849 SymDifference (class in django.contrib.gis.db.models.functions), 820 symmetrical (ManyToManyField attribute), 1109 SyndicationFeed (class in django.utils.feedgenerator), 1382

    T TabularInline (class in django.contrib.admin), 731 teardown_databases() (DiscoverRunner method), 360 teardown_databases() (in module django.test.utils), 360 teardown_test_environment() (DiscoverRunner method), 360 teardown_test_environment() (in module django.test.utils), 360 tell() (HttpResponse method), 1240 template, 1408 template (Aggregate attribute), 1198 Template (class in django.template), 1350 template (Func attribute), 1197 template (InlineModelAdmin attribute), 733 template (Window attribute), 1203 template filter add, 1329 addslashes, 1329 apnumber, 878 capfirst, 1330 center, 1330 1846

    cut, 1330 date, 1330 default, 1332 default_if_none, 1332 dictsort, 1332 dictsortreversed, 1333 divisibleby, 1333 escape, 1334 escapejs, 1334 filesizeformat, 1334 first, 1335 floatformat, 1335 force_escape, 1336 get_digit, 1336 intcomma, 879 intword, 879 iriencode, 1336 join, 1336 language_bidi, 456 language_name, 456 language_name_local, 456 language_name_translated, 456 last, 1336 length, 1337 length_is, 1337 linebreaks, 1337 linebreaksbr, 1337 linenumbers, 1337 ljust, 1338 localize, 475 localtime, 481 lower, 1338 make_list, 1338 naturalday, 879 naturaltime, 880 ordinal, 880 phone2numeric, 1338 pluralize, 1339 pprint, 1339 random, 1339 rjust, 1339 safe, 1340 safeseq, 1340 slice, 1340 slugify, 1340 stringformat, 1341 striptags, 1341 time, 1341 timesince, 1342 timeuntil, 1342 timezone, 481 title, 1342 truncatechars, 1343 truncatechars_html, 1343

    Index

    Django Documentation, Release 2.1.dev20171226153947

    truncatewords, 1343 truncatewords_html, 1343 unlocalize, 475 unordered_list, 1344 upper, 1344 urlencode, 1344 urlize, 1344 urlizetrunc, 1345 utc, 481 wordcount, 1345 wordwrap, 1346 yesno, 1346 template tag autoescape, 1311 block, 1311 blocktrans, 452 cache, 418 comment, 1311 csrf_token, 1311 cycle, 1311 debug, 1313 extends, 1313 filter, 1314 firstof, 1314 for, 1315 get_available_languages, 455 get_current_language, 455 get_current_language_bidi, 455 get_current_timezone, 480 get_flatpages, 763 get_language_info, 456 get_language_info_list, 456 get_media_prefix, 1348 get_static_prefix, 1347 if, 1316 ifchanged, 1320 include, 1321 language, 455 load, 1321 localize, 475 localtime, 480 lorem, 1322 now, 1322 regroup, 1323 resetcycle, 1325 spaceless, 1326 static, 1347 templatetag, 1326 timezone, 480 trans, 451 url, 1327 verbatim, 1328 widthratio, 1328 with, 1329

    Index

    template_engine (django.views.generic.base.TemplateResponseMixin attribute), 662 template_name (BaseGeometryWidget attribute), 801 template_name (django.views.generic.base.TemplateResponseMixin attribute), 662 template_name (Origin attribute), 1363 template_name (OSMWidget attribute), 801 template_name (SimpleTemplateResponse attribute), 1363 template_name_field (django.views.generic.detail.SingleObjectTemplateRes attribute), 664 template_name_suffix (django.views.generic.detail.SingleObjectTemplateRe attribute), 664 template_name_suffix (django.views.generic.edit.CreateView attribute), 649 template_name_suffix (django.views.generic.edit.DeleteView attribute), 651 template_name_suffix (django.views.generic.edit.UpdateView attribute), 650 template_name_suffix (django.views.generic.list.MultipleObjectTemplateRe attribute), 667 TemplateDoesNotExist, 273 TemplateResponse (class in django.template.response), 1365 TEMPLATES setting, 1276 templates (Response attribute), 334 TEMPLATES-APP_DIRS setting, 1277 TEMPLATES-BACKEND setting, 1277 TEMPLATES-DIRS setting, 1277 TEMPLATES-NAME setting, 1277 TEMPLATES-OPTIONS setting, 1277 TemplatesSetting (class in django.forms.renderers), 1055 TemplateSyntaxError, 273 templatetag template tag, 1326 TemplateView (built-in class), 675 templatize() (in module django.utils.translation), 1391 temporary_file_path() (TemporaryUploadedFile method), 1012 TemporaryFileUploadHandler (class in django.core.files.uploadhandler), 1012 TemporaryUploadedFile (class in django.core.files.uploadedfile), 1012 test django-admin command, 994 test command line option –debug-mode, 994 –debug-sql, -d, 994

    1847

    Django Documentation, Release 2.1.dev20171226153947

    –exclude-tag EXCLUDE_TAGS, 995 –failfast, 994 –keepdb, -k, 994 –noinput, –no-input, 994 –parallel [N], 994 –reverse, -r, 994 –tag TAGS, 995 –testrunner TESTRUNNER, 994 test_capability() (Layer method), 843 TEST_CHARSET setting, 1255 TEST_COLLATION setting, 1255 test_cookie_worked() (backends.base.SessionBase method), 217 TEST_CREATE setting, 1256 TEST_DEPENDENCIES setting, 1255 test_func() (UserPassesTestMixin method), 370 test_loader (DiscoverRunner attribute), 359 TEST_MIRROR setting, 1255 TEST_NAME setting, 1256 TEST_NON_SERIALIZED_APPS setting, 1278 TEST_PASSWD setting, 1257 TEST_RUNNER setting, 1278 test_runner (DiscoverRunner attribute), 359 TEST_SERIALIZE setting, 1256 test_suite (DiscoverRunner attribute), 359 TEST_TBLSPACE setting, 1257 TEST_TBLSPACE_TMP setting, 1257 TEST_TEMPLATE setting, 1256 TEST_USER setting, 1256 TEST_USER_CREATE setting, 1256 TestCase (class in django.test), 338 testing.StaticLiveServerTestCase (class in django.contrib.staticfiles), 937 testserver django-admin command, 995 testserver command line option –addrport ADDRPORT, 996 –noinput, –no-input, 996 Textarea (class in django.forms), 1065

    1848

    TextField (class in django.db.models), 1103 TextInput (class in django.forms), 1062 THOUSAND_SEPARATOR setting, 1278 through (ManyToManyField attribute), 1109 through_fields (ManyToManyField attribute), 1110 time field lookup type, 1184 template filter, 1341 time_attrs (SplitDateTimeWidget attribute), 1069 TIME_FORMAT setting, 1278 time_format (SplitDateTimeWidget attribute), 1068 TIME_INPUT_FORMATS setting, 1278 TIME_ZONE setting, 1279 TimeField (class in django.db.models), 1104 TimeField (class in django.forms), 1047 TimeInput (class in django.forms), 1064 timesince template filter, 1342 TimestampSigner (class in django.core.signing), 432 timeuntil template filter, 1342 timezone template filter, 481 template tag, 480 title template filter, 1342 to_esri() (SpatialReference method), 853 to_field (ForeignKey attribute), 1108 to_field_name (ModelChoiceField attribute), 1051 to_field_name (ModelMultipleChoiceField attribute), 1052 to_locale() (in module django.utils.translation), 1391 to_python() (Field method), 1114 TodayArchiveView (built-in class), 687 TodayArchiveView (class in django.views.generic.dates), 659 total_error_count() (BaseFormSet method), 239 touches field lookup type, 807 touches() (GEOSGeometry method), 830 touches() (OGRGeometry method), 849 touches() (PreparedGeometry method), 836 trace() (Client method), 332 trans template tag, 451 TransactionManagementError, 1006 TransactionNow (class in django.contrib.postgres.functions), 908 TransactionTestCase (class in django.test), 338

    Index

    Django Documentation, Release 2.1.dev20171226153947

    Transform (class in django.contrib.gis.db.models.functions), field lookup type, 909 820 UnaccentExtension (class in Transform (class in django.db.models), 1192 django.contrib.postgres.operations), 911 transform() (GDALRaster method), 859 unary_union (GEOSGeometry attribute), 831 transform() (GEOSGeometry method), 832 ungettext() (in module django.utils.translation), 1390 transform() (OGRGeometry method), 848 ungettext_lazy() (in module django.utils.translation), Translate (class in django.contrib.gis.db.models.functions), 1390 821 Union (class in django.contrib.gis.db.models), 813 translation string, 487 Union (class in django.contrib.gis.db.models.functions), trigram_similar 821 field lookup type, 909 union() (GEOSGeometry method), 831 TrigramDistance (class in union() (in module django.db.models.query.QuerySet), django.contrib.postgres.search), 914 1153 TrigramExtension (class in union() (OGRGeometry method), 849 django.contrib.postgres.operations), 911 unique (Field attribute), 1093 TrigramSimilarity (class in unique_for_date (Field attribute), 1093 django.contrib.postgres.search), 914 unique_for_month (Field attribute), 1094 trim (WKTWriter attribute), 838 unique_for_year (Field attribute), 1094 Trunc (class in django.db.models.functions), 1220 unique_together (Options attribute), 1129 truncatechars unit_attname() (django.contrib.gis.measure.Area class template filter, 1343 method), 823 truncatechars_html unit_attname() (django.contrib.gis.measure.Distance template filter, 1343 class method), 823 truncatewords units (SpatialReference attribute), 854 template filter, 1343 unlocalize truncatewords_html template filter, 475 template filter, 1343 unordered_list TruncDate (class in django.db.models.functions), 1223 template filter, 1344 TruncDay (class in django.db.models.functions), 1223 unpack_ipv4 (GenericIPAddressField attribute), 1045, TruncHour (class in django.db.models.functions), 1223, 1102 1224 UnreadablePostError, 1006 TruncMinute (class in django.db.models.functions), 1223, unsign() (TimestampSigner method), 432 1224 update() (Context method), 1355 TruncMonth (class in django.db.models.functions), 1222 update() (in module django.db.models.query.QuerySet), TruncQuarter (class in django.db.models.functions), 1222 1175 TruncSecond (class in django.db.models.functions), update() (QueryDict method), 1235 1223, 1224 update_or_create() (in module TruncTime (class in django.db.models.functions), 1223 django.db.models.query.QuerySet), 1169 TruncYear (class in django.db.models.functions), 1222 update_session_auth_hash() (in module tuple (Envelope attribute), 852 django.contrib.auth), 373 tuple (OGRGeometry attribute), 849 UpdateCacheMiddleware (class in type (Field attribute), 844 django.middleware.cache), 1076 type_name (Field attribute), 844 UpdateView (built-in class), 679 TypedChoiceField (class in django.forms), 1040 upload_complete() (FileUploadHandler method), 1013 TypedMultipleChoiceField (class in django.forms), 1046 upload_to (FileField attribute), 1098 tz() (in module django.template.context_processors), UploadedFile (class in django.core.files.uploadedfile), 1359 1011 upper U template filter, 1344 Upper (class in django.db.models.functions), 1227 ugettext() (in module django.utils.translation), 1390 ur (Envelope attribute), 852 ugettext_lazy() (in module django.utils.translation), 1390 uri_to_iri() (in module django.utils.encoding), 1381 ugettext_noop() (in module django.utils.translation), url 1390 template tag, 1327 unaccent Index

    1849

    Django Documentation, Release 2.1.dev20171226153947

    url (django.views.generic.base.RedirectView attribute), 644 url (FieldFile attribute), 1100 url (HttpResponseRedirect attribute), 1240 url() (in module django.conf.urls), 1377 url() (Storage method), 1010 url_name (ResolverMatch attribute), 1373 urlconf (HttpRequest attribute), 1232 urlencode template filter, 1344 urlencode() (in module django.utils.http), 1386 urlencode() (QueryDict method), 1237 URLField (class in django.db.models), 1104 URLField (class in django.forms), 1047 URLInput (class in django.forms), 1063 urlize template filter, 1344 urlizetrunc template filter, 1345 urls definitive, 1402 urls.staticfiles_urlpatterns() (in module django.contrib.staticfiles), 937 urlsafe_base64_decode() (in module django.utils.http), 1387 urlsafe_base64_encode() (in module django.utils.http), 1387 URLValidator (class in django.core.validators), 1393 USE_I18N setting, 1279 USE_L10N setting, 1279 use_required_attribute (Form attribute), 1025 use_required_attribute() (Widget method), 1060 USE_THOUSAND_SEPARATOR setting, 1280 USE_TZ setting, 1280 USE_X_FORWARDED_HOST setting, 1280 USE_X_FORWARDED_PORT setting, 1280 USER setting, 1254 user (HttpRequest attribute), 1232 user (LogEntry attribute), 743 user_can_authenticate() (ModelBackend method), 752 user_can_authenticate() (RemoteUserBackend method), 752 user_logged_in() (in module django.contrib.auth.signals), 750 user_logged_out() (in module django.contrib.auth.signals), 751

    1850

    user_login_failed() (in module django.contrib.auth.signals), 751 user_passes_test() (in module django.contrib.auth.decorators), 369 user_permissions (models.User attribute), 746 UserAttributeSimilarityValidator (class in django.contrib.auth.password_validation), 390 UserChangeForm (class in django.contrib.auth.forms), 381 UserCreationForm (class in django.contrib.auth.forms), 381 username (models.User attribute), 746 USERNAME_FIELD (models.CustomUser attribute), 400 username_validator (models.User attribute), 747 UserPassesTestMixin (class in django.contrib.auth.mixins), 370 using() (in module django.db.models.query.QuerySet), 1165 utc template filter, 481 utc (in module django.utils.timezone), 1388 UUIDField (class in django.db.models), 1104 UUIDField (class in django.forms), 1048

    V valid (GEOSGeometry attribute), 828 valid_reason (GEOSGeometry attribute), 828 validate() (SpatialReference method), 853 validate_comma_separated_integer_list (in module django.core.validators), 1394 validate_email (in module django.core.validators), 1394 validate_image_file_extension (in module django.core.validators), 1395 validate_ipv46_address (in module django.core.validators), 1394 validate_ipv4_address (in module django.core.validators), 1394 validate_ipv6_address (in module django.core.validators), 1394 validate_password() (in module django.contrib.auth.password_validation), 391 validate_slug (in module django.core.validators), 1394 validate_unicode_slug (in module django.core.validators), 1394 validate_unique() (Model method), 1135 ValidationError, 1004 validators (Field attribute), 1038, 1094 validators.ASCIIUsernameValidator (class in django.contrib.auth), 750 validators.UnicodeUsernameValidator (class in django.contrib.auth), 750 Index

    Django Documentation, Release 2.1.dev20171226153947

    Value (class in django.db.models), 1199 value (Field attribute), 845 value() (BoundField method), 1030 value_from_datadict() (Widget method), 1060 value_omitted_from_data() (Widget method), 1060 value_to_string() (Field method), 1114 ValueRange (class in django.db.models.expressions), 1204 values() (in module django.db.models.query.QuerySet), 1149 values() (QueryDict method), 1236 values_list() (in module django.db.models.query.QuerySet), 1151 Variance (class in django.db.models), 1188 vary_on_cookie() (in module django.views.decorators.vary), 201 vary_on_headers() (in module django.views.decorators.vary), 201 verbatim template tag, 1328 verbose_name (AppConfig attribute), 625 verbose_name (Field attribute), 1094 verbose_name (InlineModelAdmin attribute), 733 verbose_name (Options attribute), 1129 verbose_name_plural (InlineModelAdmin attribute), 734 verbose_name_plural (Options attribute), 1130 version django-admin command, 977 view, 1408 View (built-in class), 674 view_name (ResolverMatch attribute), 1374 view_on_site (ModelAdmin attribute), 721 ViewDoesNotExist, 1004 views.Feed (class in django.contrib.syndication), 943 views.index() (in module django.contrib.sitemaps), 921 views.serve() (in module django.contrib.staticfiles), 936 views.sitemap() (in module django.contrib.sitemaps), 917 views.SuccessMessageMixin (class in django.contrib.messages), 886 vsi_buffer (GDALRaster attribute), 860

    W

    WeekMixin (class in django.views.generic.dates), 672 When (class in django.db.models.expressions), 1210 whitelist (EmailValidator attribute), 1393 Widget (class in django.forms), 1059 widget (Field attribute), 1037 widget (MultiValueField attribute), 1050 widgets (MultiWidget attribute), 1060 width (Field attribute), 845 width (GDALBand attribute), 860 width (GDALRaster attribute), 857 width (ImageFile attribute), 1008 width_field (ImageField attribute), 1102 widthratio template tag, 1328 Window (class in django.db.models.expressions), 1203 window_compatible (Aggregate attribute), 1199 window_compatible (Expression attribute), 1206 with template tag, 1329 within field lookup type, 807 within() (GEOSGeometry method), 830 within() (OGRGeometry method), 849 within() (PreparedGeometry method), 836 wkb (GEOSGeometry attribute), 829 wkb (OGRGeometry attribute), 848 wkb_size (OGRGeometry attribute), 848 WKBReader (class in django.contrib.gis.geos), 836 WKBWriter (class in django.contrib.gis.geos), 837 wkt (Envelope attribute), 852 wkt (GEOSGeometry attribute), 829 wkt (OGRGeometry attribute), 848 wkt (SpatialReference attribute), 854 WKTReader (class in django.contrib.gis.geos), 836 WKTWriter (class in django.contrib.gis.geos), 838 wordcount template filter, 1345 wordwrap template filter, 1346 writable() (HttpResponse method), 1240 write() (HttpResponse method), 1240 write() (SyndicationFeed method), 1382 write() (WKBWriter method), 837 write() (WKTWriter method), 838 write_hex() (WKBWriter method), 837 writelines() (HttpResponse method), 1240 writeString() (SyndicationFeed method), 1382 WSGI_APPLICATION setting, 1280 wsgi_request (Response attribute), 334

    W3CGeoFeed (class in django.contrib.gis.feeds), 876 Warning (class in django.core.checks), 630 warp() (GDALRaster method), 859 week field lookup type, 1183 week (WeekMixin attribute), 672 week_day field lookup type, 1183 week_format (WeekMixin attribute), 672 X WeekArchiveView (built-in class), 684 WeekArchiveView (class in django.views.generic.dates), x (LineString attribute), 850 656 x (Point attribute), 850 Index

    1851

    Django Documentation, Release 2.1.dev20171226153947

    X_FRAME_OPTIONS setting, 1281 XFrameOptionsMiddleware (class django.middleware.clickjacking), 1081 xml suckiness of, 1403 xml (SpatialReference attribute), 855

    in

    Y y (LineString attribute), 850 y (Point attribute), 850 year field lookup type, 1182 year (YearMixin attribute), 670 year_format (YearMixin attribute), 670 YEAR_MONTH_FORMAT setting, 1281 YearArchiveView (built-in class), 682 YearArchiveView (class in django.views.generic.dates), 653 YearMixin (class in django.views.generic.dates), 670 years (SelectDateWidget attribute), 1069 yesno template filter, 1346

    Z z (LineString attribute), 850 z (Point attribute), 850

    1852

    Index

    Smile Life

    When life gives you a hundred reasons to cry, show life that you have a thousand reasons to smile

    Get in touch

    © Copyright 2015 - 2024 PDFFOX.COM - All rights reserved.

    Subject:
    Message:
    Sender: ˓→
    ˓→Cc myself:
    Subject:
    Message:
    Sender:
    Cc myself:
    Subject: ˓→...
    Message: ˓→...
    Sender: ˓→ ...
    Cc myself: ... >>> f['subject'].label_tag() Subject: >>> f['subject'].label_tag(attrs={'class': 'foo'}) Subject:

    Configuring form elements’ HTML id attributes and tags Form.auto_id By default, the form rendering methods include: • HTML id attributes on the form elements. • The corresponding tags around the labels. An HTML tag designates which label text is associated with which form element. This small enhancement makes forms more usable and more accessible to assistive devices. It’s always a good idea to use tags. The id attribute values are generated by prepending id_ to the form field names. This behavior is configurable, though, if you want to change the id convention or remove HTML id attributes and tags entirely. Use the auto_id argument to the Form constructor to control the id and label behavior. This argument must be True, False or a string. If auto_id is False, then the form output will not include tags nor id attributes: >>> f = ContactForm(auto_id=False) >>> print(f.as_table())
    Subject: ˓→
    Message:
    Sender:
    Cc myself:
    Subject:
    Message:
    Sender:
    Cc myself:
    Subject:
    Message:
    Sender:
    Cc myself:
    Message:
    Sender:
    • Enter a valid email address.
    Cc myself:
    Your name:
    Your website:
    Comment:
    Url:
    Comment:
    Url:
    • Enter a valid URL.
    Comment:
    • This field is required.
    ˓→
    ˓→
    Subject: ˓→
    100 characters max.
    Message:
    Sender:
    A valid ˓→email address, please.
    Cc myself:
    Url:
    Comment:
    Name:
    Url:
    Comment:

    .../td .../td

    .../td >...
    ... ...
    ... ...