summaryrefslogtreecommitdiff
path: root/docs/ref
diff options
context:
space:
mode:
Diffstat (limited to 'docs/ref')
-rw-r--r--docs/ref/class-based-views/base.txt5
-rw-r--r--docs/ref/class-based-views/generic-date-based.txt7
-rw-r--r--docs/ref/class-based-views/generic-display.txt1
-rw-r--r--docs/ref/class-based-views/generic-editing.txt4
-rw-r--r--docs/ref/class-based-views/index.txt2
-rw-r--r--docs/ref/class-based-views/mixins-editing.txt2
-rw-r--r--docs/ref/class-based-views/mixins-simple.txt11
-rw-r--r--docs/ref/contrib/admin/admindocs.txt11
-rw-r--r--docs/ref/contrib/admin/index.txt199
-rw-r--r--docs/ref/contrib/contenttypes.txt19
-rw-r--r--docs/ref/contrib/csrf.txt3
-rw-r--r--docs/ref/contrib/formtools/form-preview.txt1
-rw-r--r--docs/ref/contrib/formtools/form-wizard.txt11
-rw-r--r--docs/ref/contrib/gis/geoip.txt4
-rwxr-xr-xdocs/ref/contrib/gis/install/create_template_postgis-1.5.sh10
-rw-r--r--docs/ref/contrib/messages.txt1
-rw-r--r--docs/ref/contrib/sitemaps.txt40
-rw-r--r--docs/ref/contrib/syndication.txt34
-rw-r--r--docs/ref/databases.txt13
-rw-r--r--docs/ref/django-admin.txt11
-rw-r--r--docs/ref/exceptions.txt29
-rw-r--r--docs/ref/forms/api.txt101
-rw-r--r--docs/ref/forms/fields.txt8
-rw-r--r--docs/ref/forms/models.txt18
-rw-r--r--docs/ref/forms/validation.txt9
-rw-r--r--docs/ref/forms/widgets.txt3
-rw-r--r--docs/ref/middleware.txt13
-rw-r--r--docs/ref/models/fields.txt32
-rw-r--r--docs/ref/models/instances.txt10
-rw-r--r--docs/ref/models/options.txt6
-rw-r--r--docs/ref/models/querysets.txt92
-rw-r--r--docs/ref/models/relations.txt8
-rw-r--r--docs/ref/request-response.txt50
-rw-r--r--docs/ref/settings.txt33
-rw-r--r--docs/ref/signals.txt47
-rw-r--r--docs/ref/template-response.txt3
-rw-r--r--docs/ref/templates/api.txt7
-rw-r--r--docs/ref/templates/builtins.txt2
-rw-r--r--docs/ref/utils.txt28
39 files changed, 694 insertions, 194 deletions
diff --git a/docs/ref/class-based-views/base.txt b/docs/ref/class-based-views/base.txt
index ee0bf0f225..319bd4ebfe 100644
--- a/docs/ref/class-based-views/base.txt
+++ b/docs/ref/class-based-views/base.txt
@@ -55,7 +55,7 @@ View
Default::
- ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
+ ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
**Methods**
@@ -114,7 +114,6 @@ TemplateView
This view inherits methods and attributes from the following views:
- * :class:`django.views.generic.base.TemplateView`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.base.View`
@@ -208,7 +207,7 @@ RedirectView
urlpatterns = patterns('',
- url(r'r^(?P<pk>\d+)/$', ArticleCounterRedirectView.as_view(), name='article-counter'),
+ url(r'^(?P<pk>\d+)/$', ArticleCounterRedirectView.as_view(), name='article-counter'),
url(r'^go-to-django/$', RedirectView.as_view(url='http://djangoproject.com'), name='go-to-django'),
)
diff --git a/docs/ref/class-based-views/generic-date-based.txt b/docs/ref/class-based-views/generic-date-based.txt
index 4dcb788779..1ebee254b1 100644
--- a/docs/ref/class-based-views/generic-date-based.txt
+++ b/docs/ref/class-based-views/generic-date-based.txt
@@ -33,7 +33,6 @@ ArchiveIndexView
**Ancestors (MRO)**
- * :class:`django.views.generic.dates.ArchiveIndexView`
* :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.dates.BaseArchiveIndexView`
@@ -100,7 +99,6 @@ YearArchiveView
**Ancestors (MRO)**
- * :class:`django.views.generic.dates.YearArchiveView`
* :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.dates.BaseYearArchiveView`
@@ -216,7 +214,6 @@ MonthArchiveView
**Ancestors (MRO)**
- * :class:`django.views.generic.dates.MonthArchiveView`
* :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.dates.BaseMonthArchiveView`
@@ -317,7 +314,6 @@ WeekArchiveView
**Ancestors (MRO)**
- * :class:`django.views.generic.dates.WeekArchiveView`
* :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.dates.BaseWeekArchiveView`
@@ -422,7 +418,6 @@ DayArchiveView
**Ancestors (MRO)**
- * :class:`django.views.generic.dates.DayArchiveView`
* :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.dates.BaseDayArchiveView`
@@ -526,7 +521,6 @@ TodayArchiveView
**Ancestors (MRO)**
- * :class:`django.views.generic.dates.TodayArchiveView`
* :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.dates.BaseTodayArchiveView`
@@ -585,7 +579,6 @@ DateDetailView
**Ancestors (MRO)**
- * :class:`django.views.generic.dates.DateDetailView`
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.dates.BaseDateDetailView`
diff --git a/docs/ref/class-based-views/generic-display.txt b/docs/ref/class-based-views/generic-display.txt
index b827c0005c..c133134d65 100644
--- a/docs/ref/class-based-views/generic-display.txt
+++ b/docs/ref/class-based-views/generic-display.txt
@@ -77,7 +77,6 @@ ListView
This view inherits methods and attributes from the following views:
- * :class:`django.views.generic.list.ListView`
* :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.list.BaseListView`
diff --git a/docs/ref/class-based-views/generic-editing.txt b/docs/ref/class-based-views/generic-editing.txt
index 555ba40cfb..c1fb2dcca9 100644
--- a/docs/ref/class-based-views/generic-editing.txt
+++ b/docs/ref/class-based-views/generic-editing.txt
@@ -36,7 +36,6 @@ FormView
This view inherits methods and attributes from the following views:
- * :class:`django.views.generic.edit.FormView`
* :class:`django.views.generic.base.TemplateResponseMixin`
* ``django.views.generic.edit.BaseFormView``
* :class:`django.views.generic.edit.FormMixin`
@@ -83,7 +82,6 @@ CreateView
This view inherits methods and attributes from the following views:
- * :class:`django.views.generic.edit.CreateView`
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* ``django.views.generic.edit.BaseCreateView``
@@ -126,7 +124,6 @@ UpdateView
This view inherits methods and attributes from the following views:
- * :class:`django.views.generic.edit.UpdateView`
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* ``django.views.generic.edit.BaseUpdateView``
@@ -169,7 +166,6 @@ DeleteView
This view inherits methods and attributes from the following views:
- * :class:`django.views.generic.edit.DeleteView`
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* ``django.views.generic.edit.BaseDeleteView``
diff --git a/docs/ref/class-based-views/index.txt b/docs/ref/class-based-views/index.txt
index a027953416..821edc0874 100644
--- a/docs/ref/class-based-views/index.txt
+++ b/docs/ref/class-based-views/index.txt
@@ -32,7 +32,7 @@ A class-based view is deployed into a URL pattern using the
.. admonition:: Thread safety with view arguments
Arguments passed to a view are shared between every instance of a view.
- This means that you shoudn't use a list, dictionary, or any other
+ This means that you shouldn't use a list, dictionary, or any other
mutable object as an argument to a view. If you do and the shared object
is modified, the actions of one user visiting your view could have an
effect on subsequent users visiting the same view.
diff --git a/docs/ref/class-based-views/mixins-editing.txt b/docs/ref/class-based-views/mixins-editing.txt
index 51d8628818..48d363b3b2 100644
--- a/docs/ref/class-based-views/mixins-editing.txt
+++ b/docs/ref/class-based-views/mixins-editing.txt
@@ -125,7 +125,7 @@ ModelFormMixin
This is a required attribute if you are generating the form class
automatically (e.g. using ``model``). Omitting this attribute will
- result in all fields being used, but this behaviour is deprecated
+ result in all fields being used, but this behavior is deprecated
and will be removed in Django 1.8.
.. attribute:: success_url
diff --git a/docs/ref/class-based-views/mixins-simple.txt b/docs/ref/class-based-views/mixins-simple.txt
index 6796675529..377c85cc3b 100644
--- a/docs/ref/class-based-views/mixins-simple.txt
+++ b/docs/ref/class-based-views/mixins-simple.txt
@@ -60,6 +60,17 @@ TemplateResponseMixin
altered later (e.g. in
:ref:`template response middleware <template-response-middleware>`).
+ .. admonition:: Context processors
+
+ ``TemplateResponse`` uses :class:`~django.template.RequestContext`
+ which means that callables defined in
+ :setting:`TEMPLATE_CONTEXT_PROCESSORS` may overwrite template
+ variables defined in your views. For example, if you subclass
+ :class:`DetailView <django.views.generic.detail.DetailView>` and
+ set ``context_object_name`` to ``user``, the
+ ``django.contrib.auth.context_processors.auth`` context processor
+ will happily overwrite your variable with current user.
+
If you need custom template loading or custom context object
instantiation, create a ``TemplateResponse`` subclass and assign it to
``response_class``.
diff --git a/docs/ref/contrib/admin/admindocs.txt b/docs/ref/contrib/admin/admindocs.txt
index 394d078e5b..6deb7bdbf8 100644
--- a/docs/ref/contrib/admin/admindocs.txt
+++ b/docs/ref/contrib/admin/admindocs.txt
@@ -30,8 +30,8 @@ the following:
* Install the docutils Python module (http://docutils.sf.net/).
* **Optional:** Linking to templates requires the :setting:`ADMIN_FOR`
setting to be configured.
-* **Optional:** Using the admindocs bookmarklets requires the
- :mod:`XViewMiddleware<django.middleware.doc>` to be installed.
+* **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
@@ -156,7 +156,6 @@ Edit this object
Using these bookmarklets requires that you are either logged into the
:mod:`Django admin <django.contrib.admin>` as a
:class:`~django.contrib.auth.models.User` with
-:attr:`~django.contrib.auth.models.User.is_staff` set to `True`, or
-that the :mod:`django.middleware.doc` middleware and
-:mod:`XViewMiddleware <django.middleware.doc>` are installed and you
-are accessing the site from an IP address listed in :setting:`INTERNAL_IPS`.
+:attr:`~django.contrib.auth.models.User.is_staff` set to `True`, or that the
+``XViewMiddleware`` is installed and you are accessing the site from an IP
+address listed in :setting:`INTERNAL_IPS`.
diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt
index 67e498ee91..7377f11a63 100644
--- a/docs/ref/contrib/admin/index.txt
+++ b/docs/ref/contrib/admin/index.txt
@@ -108,6 +108,8 @@ The ``ModelAdmin`` is very flexible. It has several options for dealing with
customizing the interface. All options are defined on the ``ModelAdmin``
subclass::
+ from django.contrib import admin
+
class AuthorAdmin(admin.ModelAdmin):
date_hierarchy = 'pub_date'
@@ -157,6 +159,8 @@ subclass::
For example, let's consider the following model::
+ from django.db import models
+
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3)
@@ -166,6 +170,8 @@ subclass::
and ``title`` fields, you would specify ``fields`` or ``exclude`` like
this::
+ from django.contrib import admin
+
class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title')
@@ -234,6 +240,8 @@ subclass::
A full example, taken from the
:class:`django.contrib.flatpages.models.FlatPage` model::
+ from django.contrib import admin
+
class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
@@ -356,6 +364,10 @@ subclass::
If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
option then ``ModelAdmin`` takes precedence::
+ from django import forms
+ from django.contrib import admin
+ from myapp.models import Person
+
class PersonForm(forms.ModelForm):
class Meta:
@@ -452,13 +464,16 @@ subclass::
list_display = ('upper_case_name',)
def upper_case_name(self, obj):
- return ("%s %s" % (obj.first_name, obj.last_name)).upper()
+ return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'
* A string representing an attribute on the model. This behaves almost
the same as the callable, but ``self`` in this context is the model
instance. Here's a full model example::
+ from django.db import models
+ from django.contrib import admin
+
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
@@ -494,6 +509,8 @@ subclass::
Here's a full example model::
+ from django.db import models
+ from django.contrib import admin
from django.utils.html import format_html
class Person(models.Model):
@@ -519,6 +536,9 @@ subclass::
Here's a full example model::
+ from django.db import models
+ from django.contrib import admin
+
class Person(models.Model):
first_name = models.CharField(max_length=50)
birthday = models.DateField()
@@ -547,6 +567,8 @@ subclass::
For example::
+ from django.db import models
+ from django.contrib import admin
from django.utils.html import format_html
class Person(models.Model):
@@ -567,6 +589,27 @@ subclass::
The above will tell Django to order by the ``first_name`` field when
trying to sort by ``colored_first_name`` in the admin.
+ * Elements of ``list_display`` can also be properties. Please note however,
+ that due to the way properties work in Python, setting
+ ``short_description`` on a property is only possible when using the
+ ``property()`` function and **not** with the ``@property`` decorator.
+
+ For example::
+
+ class Person(object):
+ first_name = models.CharField(max_length=50)
+ last_name = models.CharField(max_length=50)
+
+ def my_property(self):
+ return self.first_name + ' ' + self.last_name
+ my_property.short_description = "Full name of the person"
+
+ full_name = property(my_property)
+
+ class PersonAdmin(admin.ModelAdmin):
+ list_display = ('full_name',)
+
+
* .. versionadded:: 1.6
The field names in ``list_display`` will also appear as CSS classes in
@@ -634,13 +677,13 @@ subclass::
``BooleanField``, ``CharField``, ``DateField``, ``DateTimeField``,
``IntegerField``, ``ForeignKey`` or ``ManyToManyField``, for example::
- class PersonAdmin(ModelAdmin):
+ class PersonAdmin(admin.ModelAdmin):
list_filter = ('is_staff', 'company')
Field names in ``list_filter`` can also span relations
using the ``__`` lookup, for example::
- class PersonAdmin(UserAdmin):
+ class PersonAdmin(admin.UserAdmin):
list_filter = ('company__name',)
* a class inheriting from ``django.contrib.admin.SimpleListFilter``,
@@ -650,10 +693,10 @@ subclass::
from datetime import date
+ from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
- from django.contrib.admin import SimpleListFilter
- class DecadeBornListFilter(SimpleListFilter):
+ class DecadeBornListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('decade born')
@@ -689,7 +732,7 @@ subclass::
return queryset.filter(birthday__gte=date(1990, 1, 1),
birthday__lte=date(1999, 12, 31))
- class PersonAdmin(ModelAdmin):
+ class PersonAdmin(admin.ModelAdmin):
list_filter = (DecadeBornListFilter,)
.. note::
@@ -732,11 +775,9 @@ subclass::
element is a class inheriting from
``django.contrib.admin.FieldListFilter``, for example::
- from django.contrib.admin import BooleanFieldListFilter
-
- class PersonAdmin(ModelAdmin):
+ class PersonAdmin(admin.ModelAdmin):
list_filter = (
- ('is_staff', BooleanFieldListFilter),
+ ('is_staff', admin.BooleanFieldListFilter),
)
.. note::
@@ -746,7 +787,7 @@ subclass::
It is possible to specify a custom template for rendering a list filter::
- class FilterWithCustomTemplate(SimpleListFilter):
+ class FilterWithCustomTemplate(admin.SimpleListFilter):
template = "custom_template.html"
See the default template provided by django (``admin/filter.html``) for
@@ -771,12 +812,24 @@ subclass::
the list of objects on the admin change list page. This can save you a
bunch of database queries.
- The value should be either ``True`` or ``False``. Default is ``False``.
+ .. versionchanged:: dev
+
+ The value should be either a boolean, a list or a tuple. Default is
+ ``False``.
+
+ When value is ``True``, ``select_related()`` will always be called. When
+ value is set to ``False``, Django will look at ``list_display`` and call
+ ``select_related()`` if any ``ForeignKey`` is present.
- Note that Django will use
- :meth:`~django.db.models.query.QuerySet.select_related`,
- regardless of this setting if one of the ``list_display`` fields is a
- ``ForeignKey``.
+ If you need more fine-grained control, use a tuple (or list) as value for
+ ``list_select_related``. Empty tuple will prevent Django from calling
+ ``select_related`` at all. Any other tuple will be passed directly to
+ ``select_related`` as parameters. For example::
+
+ class ArticleAdmin(admin.ModelAdmin):
+ list_select_related = ('author', 'category')
+
+ will call ``select_related('author', 'category')``.
.. attribute:: ModelAdmin.ordering
@@ -876,10 +929,11 @@ subclass::
the admin interface to provide feedback on the status of the objects being
edited, for example::
+ from django.contrib import admin
from django.utils.html import format_html_join
from django.utils.safestring import mark_safe
- class PersonAdmin(ModelAdmin):
+ class PersonAdmin(admin.ModelAdmin):
readonly_fields = ('address_report',)
def address_report(self, instance):
@@ -984,6 +1038,10 @@ subclass::
Performs a full-text match. This is like the default search method but
uses an index. Currently this is only available for MySQL.
+ If you need to customize search you can use
+ :meth:`ModelAdmin.get_search_results` to provide additional or alternate
+ search behavior.
+
Custom template options
~~~~~~~~~~~~~~~~~~~~~~~
@@ -1038,6 +1096,8 @@ templates used by the :class:`ModelAdmin` views:
For example to attach ``request.user`` to the object prior to saving::
+ from django.contrib import admin
+
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = request.user
@@ -1071,7 +1131,7 @@ templates used by the :class:`ModelAdmin` views:
is expected to return a ``list`` or ``tuple`` for ordering similar
to the :attr:`ordering` attribute. For example::
- class PersonAdmin(ModelAdmin):
+ class PersonAdmin(admin.ModelAdmin):
def get_ordering(self, request):
if request.user.is_superuser:
@@ -1079,6 +1139,39 @@ templates used by the :class:`ModelAdmin` views:
else:
return ['name']
+.. method:: ModelAdmin.get_search_results(self, request, queryset, search_term)
+
+ .. versionadded:: 1.6
+
+ The ``get_search_results`` method modifies the list of objects displayed in
+ to those that match the provided search term. It accepts the request, a
+ queryset that applies the current filters, and the user-provided search term.
+ It returns a tuple containing a queryset modified to implement the search, and
+ a boolean indicating if the results may contain duplicates.
+
+ The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`.
+
+ This method may be overridden with your own custom search method. For
+ example, you might wish to search by an integer field, or use an external
+ tool such as Solr or Haystack. You must establish if the queryset changes
+ implemented by your search method may introduce duplicates into the results,
+ and return ``True`` in the second element of the return value.
+
+ For example, to enable search by integer field, you could use::
+
+ class PersonAdmin(admin.ModelAdmin):
+ list_display = ('name', 'age')
+ search_fields = ('name',)
+
+ def get_search_results(self, request, queryset, search_term):
+ queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
+ try:
+ search_term_as_int = int(search_term)
+ queryset |= self.model.objects.filter(age=search_term_as_int)
+ except:
+ pass
+ return queryset, use_distinct
+
.. method:: ModelAdmin.save_related(self, request, form, formsets, change)
The ``save_related`` method is given the ``HttpRequest``, the parent
@@ -1298,6 +1391,8 @@ templates used by the :class:`ModelAdmin` views:
Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
on the changelist page. To use a custom form, for example::
+ from django import forms
+
class MyForm(forms.ModelForm):
pass
@@ -1539,6 +1634,8 @@ information.
The admin interface has the ability to edit models on the same page as a
parent model. These are called inlines. Suppose you have these two models::
+ from django.db import models
+
class Author(models.Model):
name = models.CharField(max_length=100)
@@ -1549,6 +1646,8 @@ information.
You can edit the books authored by an author on the author page. You add
inlines to a model by specifying them in a ``ModelAdmin.inlines``::
+ from django.contrib import admin
+
class BookInline(admin.TabularInline):
model = Book
@@ -1629,6 +1728,11 @@ The ``InlineModelAdmin`` class adds:
The dynamic link will not appear if the number of currently displayed forms
exceeds ``max_num``, or if the user does not have JavaScript enabled.
+ .. versionadded:: 1.6
+
+ :meth:`InlineModelAdmin.get_extra` also allows you to customize the number
+ of extra forms.
+
.. _ref-contrib-admin-inline-max-num:
.. attribute:: InlineModelAdmin.max_num
@@ -1637,6 +1741,11 @@ The ``InlineModelAdmin`` class adds:
doesn't directly correlate to the number of objects, but can if the value
is small enough. See :ref:`model-formsets-max-num` for more information.
+ .. versionadded:: 1.6
+
+ :meth:`InlineModelAdmin.get_max_num` also allows you to customize the
+ maximum number of extra forms.
+
.. attribute:: InlineModelAdmin.raw_id_fields
By default, Django's admin uses a select-box interface (<select>) for
@@ -1676,12 +1785,55 @@ The ``InlineModelAdmin`` class adds:
Returns a ``BaseInlineFormSet`` class for use in admin add/change views.
See the example for :class:`ModelAdmin.get_formsets`.
+.. method:: InlineModelAdmin.get_extra(self, request, obj=None, **kwargs)
+
+ .. versionadded:: 1.6
+
+ Returns the number of extra inline forms to use. By default, returns the
+ :attr:`InlineModelAdmin.extra` attribute.
+
+ Override this method to programmatically determine the number of extra
+ inline forms. For example, this may be based on the model instance
+ (passed as the keyword argument ``obj``)::
+
+ class BinaryTreeAdmin(admin.TabularInline):
+ model = BinaryTree
+
+ def get_extra(self, request, obj=None, **kwargs):
+ extra = 2
+ if obj:
+ return extra - obj.binarytree_set.count()
+ return extra
+
+.. method:: InlineModelAdmin.get_max_num(self, request, obj=None, **kwargs)
+
+ .. versionadded:: 1.6
+
+ Returns the maximum number of extra inline forms to use. By default,
+ returns the :attr:`InlineModelAdmin.max_num` attribute.
+
+ Override this method to programmatically determine the maximum number of
+ inline forms. For example, this may be based on the model instance
+ (passed as the keyword argument ``obj``)::
+
+ class BinaryTreeAdmin(admin.TabularInline):
+ model = BinaryTree
+
+ def get_max_num(self, request, obj=None, **kwargs):
+ max_num = 10
+ if obj.parent:
+ return max_num - 5
+ return max_num
+
+
Working with a model with two or more foreign keys to the same parent model
---------------------------------------------------------------------------
It is sometimes possible to have more than one foreign key to the same model.
Take this model for instance::
+ from django.db import models
+
class Friendship(models.Model):
to_person = models.ForeignKey(Person, related_name="friends")
from_person = models.ForeignKey(Person, related_name="from_friends")
@@ -1690,6 +1842,9 @@ If you wanted to display an inline on the ``Person`` admin add/change pages
you need to explicitly define the foreign key since it is unable to do so
automatically::
+ from django.contrib import admin
+ from myapp.models import Friendship
+
class FriendshipInline(admin.TabularInline):
model = Friendship
fk_name = "to_person"
@@ -1712,6 +1867,8 @@ widgets with inlines.
Suppose we have the following models::
+ from django.db import models
+
class Person(models.Model):
name = models.CharField(max_length=128)
@@ -1722,6 +1879,8 @@ Suppose we have the following models::
If you want to display many-to-many relations using an inline, you can do
so by defining an ``InlineModelAdmin`` object for the relationship::
+ from django.contrib import admin
+
class MembershipInline(admin.TabularInline):
model = Group.members.through
@@ -1768,6 +1927,8 @@ However, we still want to be able to edit that information inline. Fortunately,
this is easy to do with inline admin models. Suppose we have the following
models::
+ from django.db import models
+
class Person(models.Model):
name = models.CharField(max_length=128)
@@ -1816,6 +1977,8 @@ Using generic relations as an inline
It is possible to use an inline with generically related objects. Let's say
you have the following models::
+ from django.db import models
+
class Image(models.Model):
image = models.ImageField(upload_to="images")
content_type = models.ForeignKey(ContentType)
diff --git a/docs/ref/contrib/contenttypes.txt b/docs/ref/contrib/contenttypes.txt
index 4fa119bc70..de9c5dcbd6 100644
--- a/docs/ref/contrib/contenttypes.txt
+++ b/docs/ref/contrib/contenttypes.txt
@@ -303,6 +303,15 @@ model:
:class:`~django.contrib.contenttypes.generic.GenericForeignKey` will
look for.
+ .. attribute:: GenericForeignKey.for_concrete_model
+
+ .. versionadded:: 1.6
+
+ If ``False``, the field will be able to reference proxy models. Default
+ is ``True``. This mirrors the ``for_concrete_model`` argument to
+ :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`.
+
+
.. admonition:: Primary key type compatibility
The "object_id" field doesn't have to be the same type as the
@@ -329,7 +338,7 @@ model:
.. admonition:: Serializing references to ``ContentType`` objects
If you're serializing data (for example, when generating
- :class:`~django.test.TestCase.fixtures`) from a model that implements
+ :class:`~django.test.TransactionTestCase.fixtures`) from a model that implements
generic relations, you should probably be using a natural key to uniquely
identify related :class:`~django.contrib.contenttypes.models.ContentType`
objects. See :ref:`natural keys<topics-serialization-natural-keys>` and
@@ -492,7 +501,7 @@ information.
Subclasses of :class:`GenericInlineModelAdmin` with stacked and tabular
layouts, respectively.
-.. function:: generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False)
+.. function:: generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True)
Returns a ``GenericInlineFormSet`` using
:func:`~django.forms.models.modelformset_factory`.
@@ -502,3 +511,9 @@ information.
are similar to those documented in
:func:`~django.forms.models.modelformset_factory` and
:func:`~django.forms.models.inlineformset_factory`.
+
+ .. versionadded:: 1.6
+
+ The ``for_concrete_model`` argument corresponds to the
+ :class:`~django.contrib.contenttypes.generic.GenericForeignKey.for_concrete_model`
+ argument on ``GenericForeignKey``.
diff --git a/docs/ref/contrib/csrf.txt b/docs/ref/contrib/csrf.txt
index 968ef0b07b..f8b3cf2646 100644
--- a/docs/ref/contrib/csrf.txt
+++ b/docs/ref/contrib/csrf.txt
@@ -120,7 +120,7 @@ Acquiring the token is straightforward:
var csrftoken = getCookie('csrftoken');
The above code could be simplified by using the `jQuery cookie plugin
-<http://plugins.jquery.com/project/Cookie>`_ to replace ``getCookie``:
+<http://plugins.jquery.com/cookie/>`_ to replace ``getCookie``:
.. code-block:: javascript
@@ -384,6 +384,7 @@ Utilities
the middleware. Example::
from django.views.decorators.csrf import csrf_exempt
+ from django.http import HttpResponse
@csrf_exempt
def my_view(request):
diff --git a/docs/ref/contrib/formtools/form-preview.txt b/docs/ref/contrib/formtools/form-preview.txt
index 011e72c2e0..b86cc4dc90 100644
--- a/docs/ref/contrib/formtools/form-preview.txt
+++ b/docs/ref/contrib/formtools/form-preview.txt
@@ -53,6 +53,7 @@ How to use ``FormPreview``
overrides the ``done()`` method::
from django.contrib.formtools.preview import FormPreview
+ from django.http import HttpResponseRedirect
from myapp.models import SomeModel
class SomeModelFormPreview(FormPreview):
diff --git a/docs/ref/contrib/formtools/form-wizard.txt b/docs/ref/contrib/formtools/form-wizard.txt
index f85ae8356d..7795a32c09 100644
--- a/docs/ref/contrib/formtools/form-wizard.txt
+++ b/docs/ref/contrib/formtools/form-wizard.txt
@@ -420,8 +420,10 @@ Advanced ``WizardView`` methods
.. method:: WizardView.get_form(step=None, data=None, files=None)
This method constructs the form for a given ``step``. If no ``step`` is
- defined, the current step will be determined automatically.
- The method gets three arguments:
+ defined, the current step will be determined automatically. If you override
+ ``get_form``, however, you will need to set ``step`` yourself using
+ ``self.steps.current`` as in the example below. The method gets three
+ arguments:
* ``step`` -- The step for which the form instance should be generated.
* ``data`` -- Gets passed to the form's data argument
@@ -433,6 +435,11 @@ Advanced ``WizardView`` methods
def get_form(self, step=None, data=None, files=None):
form = super(MyWizard, self).get_form(step, data, files)
+
+ # determine the step if not given
+ if step is None:
+ step = self.steps.current
+
if step == '1':
form.user = self.request.user
return form
diff --git a/docs/ref/contrib/gis/geoip.txt b/docs/ref/contrib/gis/geoip.txt
index 2444849a19..b6aca6b211 100644
--- a/docs/ref/contrib/gis/geoip.txt
+++ b/docs/ref/contrib/gis/geoip.txt
@@ -8,8 +8,7 @@ Geolocation with GeoIP
:synopsis: High-level Python interface for MaxMind's GeoIP C library.
The :class:`GeoIP` object is a ctypes wrapper for the
-`MaxMind GeoIP C API`__. [#]_ This interface is a BSD-licensed alternative
-to the GPL-licensed `Python GeoIP`__ interface provided by MaxMind.
+`MaxMind GeoIP C API`__. [#]_
In order to perform IP-based geolocation, the :class:`GeoIP` object requires
the GeoIP C libary and either the GeoIP `Country`__ or `City`__
@@ -20,7 +19,6 @@ you set :setting:`GEOIP_PATH` with in your settings. See the example and
reference below for more details.
__ http://www.maxmind.com/app/c
-__ http://www.maxmind.com/app/python
__ http://www.maxmind.com/app/country
__ http://www.maxmind.com/app/city
__ http://www.maxmind.com/download/geoip/database/
diff --git a/docs/ref/contrib/gis/install/create_template_postgis-1.5.sh b/docs/ref/contrib/gis/install/create_template_postgis-1.5.sh
index 081b5f2656..67c82a8b25 100755
--- a/docs/ref/contrib/gis/install/create_template_postgis-1.5.sh
+++ b/docs/ref/contrib/gis/install/create_template_postgis-1.5.sh
@@ -1,9 +1,15 @@
#!/usr/bin/env bash
-POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib/postgis-1.5
+if [[ `uname -r | grep el6` ]]; then
+ POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib/postgis
+ POSTGIS_SQL_FILE=$POSTGIS_SQL_PATH/postgis-64.sql
+else
+ POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib/postgis-1.5
+ POSTGIS_SQL_FILE=$POSTGIS_SQL_PATH/postgis.sql
+fi
createdb -E UTF8 template_postgis # Create the template spatial database.
createlang -d template_postgis plpgsql # Adding PLPGSQL language support.
psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';"
-psql -d template_postgis -f $POSTGIS_SQL_PATH/postgis.sql # Loading the PostGIS SQL routines
+psql -d template_postgis -f $POSTGIS_SQL_FILE # Loading the PostGIS SQL routines
psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql
psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables.
psql -d template_postgis -c "GRANT ALL ON geography_columns TO PUBLIC;"
diff --git a/docs/ref/contrib/messages.txt b/docs/ref/contrib/messages.txt
index 0a376bca18..608c37bb7f 100644
--- a/docs/ref/contrib/messages.txt
+++ b/docs/ref/contrib/messages.txt
@@ -373,4 +373,3 @@ behavior:
* :setting:`MESSAGE_LEVEL`
* :setting:`MESSAGE_STORAGE`
* :setting:`MESSAGE_TAGS`
-* :ref:`SESSION_COOKIE_DOMAIN<messages-session_cookie_domain>`
diff --git a/docs/ref/contrib/sitemaps.txt b/docs/ref/contrib/sitemaps.txt
index d37ee83378..56a15cb9e0 100644
--- a/docs/ref/contrib/sitemaps.txt
+++ b/docs/ref/contrib/sitemaps.txt
@@ -280,6 +280,46 @@ Here's an example of a :doc:`URLconf </topics/http/urls>` using both::
.. _URLconf: ../url_dispatch/
+Sitemap for static views
+========================
+
+Often you want the search engine crawlers to index views which are neither
+object detail pages nor flatpages. The solution is to explicitly list URL
+names for these views in ``items`` and call
+:func:`~django.core.urlresolvers.reverse` in the ``location`` method of
+the sitemap. For example::
+
+ # sitemaps.py
+ from django.contrib import sitemaps
+ from django.core.urlresolvers import reverse
+
+ class StaticViewSitemap(sitemaps.Sitemap):
+ priority = 0.5
+ changefreq = 'daily'
+
+ def items(self):
+ return ['main', 'about', 'license']
+
+ def location(self, item):
+ return reverse(item)
+
+ # urls.py
+ from django.conf.urls import patterns, url
+ from .sitemaps import StaticViewSitemap
+
+ sitemaps = {
+ 'static': StaticViewSitemap,
+ }
+
+ urlpatterns = patterns('',
+ url(r'^$', 'views.main', name='main'),
+ url(r'^about/$', 'views.about', name='about'),
+ url(r'^license/$', 'views.license', name='license'),
+ # ...
+ url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})
+ )
+
+
Creating a sitemap index
========================
diff --git a/docs/ref/contrib/syndication.txt b/docs/ref/contrib/syndication.txt
index 02159c415b..51d038d187 100644
--- a/docs/ref/contrib/syndication.txt
+++ b/docs/ref/contrib/syndication.txt
@@ -137,25 +137,29 @@ into those elements.
See `a complex example`_ below that uses a description template.
- There is also a way to pass additional information to title and description
- templates, if you need to supply more than the two variables mentioned
- before. You can provide your implementation of ``get_context_data`` method
- in your Feed subclass. For example::
+ .. method:: Feed.get_context_data(self, **kwargs)
- from mysite.models import Article
- from django.contrib.syndication.views import Feed
+ .. versionadded:: 1.6
- class ArticlesFeed(Feed):
- title = "My articles"
- description_template = "feeds/articles.html"
+ There is also a way to pass additional information to title and description
+ templates, if you need to supply more than the two variables mentioned
+ before. You can provide your implementation of ``get_context_data`` method
+ in your ``Feed`` subclass. For example::
- def items(self):
- return Article.objects.order_by('-pub_date')[:5]
+ from mysite.models import Article
+ from django.contrib.syndication.views import Feed
- def get_context_data(self, **kwargs):
- context = super(ArticlesFeed, self).get_context_data(**kwargs)
- context['foo'] = 'bar'
- return context
+ class ArticlesFeed(Feed):
+ title = "My articles"
+ description_template = "feeds/articles.html"
+
+ def items(self):
+ return Article.objects.order_by('-pub_date')[:5]
+
+ def get_context_data(self, **kwargs):
+ context = super(ArticlesFeed, self).get_context_data(**kwargs)
+ context['foo'] = 'bar'
+ return context
And the template:
diff --git a/docs/ref/databases.txt b/docs/ref/databases.txt
index 7555acaaba..a648ac1709 100644
--- a/docs/ref/databases.txt
+++ b/docs/ref/databases.txt
@@ -135,16 +135,17 @@ configuration in :setting:`DATABASES`::
Since Django 1.6, autocommit is turned on by default. This configuration is
ignored and can be safely removed.
+.. _database-isolation-level:
+
Isolation level
---------------
.. versionadded:: 1.6
Like PostgreSQL itself, Django defaults to the ``READ COMMITTED`` `isolation
-level <postgresql-isolation-levels>`_. If you need a higher isolation level
-such as ``REPEATABLE READ`` or ``SERIALIZABLE``, set it in the
-:setting:`OPTIONS` part of your database configuration in
-:setting:`DATABASES`::
+level`_. If you need a higher isolation level such as ``REPEATABLE READ`` or
+``SERIALIZABLE``, set it in the :setting:`OPTIONS` part of your database
+configuration in :setting:`DATABASES`::
import psycopg2.extensions
@@ -161,7 +162,7 @@ such as ``REPEATABLE READ`` or ``SERIALIZABLE``, set it in the
handle exceptions raised on serialization failures. This option is
designed for advanced uses.
-.. _postgresql-isolation-levels: http://www.postgresql.org/docs/current/static/transaction-iso.html
+.. _isolation level: http://www.postgresql.org/docs/current/static/transaction-iso.html
Indexes for ``varchar`` and ``text`` columns
--------------------------------------------
@@ -803,5 +804,5 @@ the support channels provided by each 3rd party project.
.. _IBM DB2: http://code.google.com/p/ibm-db/
.. _Microsoft SQL Server 2005: http://code.google.com/p/django-mssql/
.. _Firebird: http://code.google.com/p/django-firebird/
-.. _ODBC: http://code.google.com/p/django-pyodbc/
+.. _ODBC: https://github.com/aurorasoftware/django-pyodbc/
.. _ADSDB: http://code.google.com/p/adsdb-django/
diff --git a/docs/ref/django-admin.txt b/docs/ref/django-admin.txt
index 2f2880679c..e21e3d2766 100644
--- a/docs/ref/django-admin.txt
+++ b/docs/ref/django-admin.txt
@@ -227,6 +227,15 @@ a natural key definition. If you are dumping ``contrib.auth`` ``Permission``
objects or ``contrib.contenttypes`` ``ContentType`` objects, you should
probably be using this flag.
+.. versionadded:: 1.6
+
+.. django-admin-option:: --pks
+
+By default, ``dumpdata`` will output all the records of the model, but
+you can use the ``--pks`` option to specify a comma seperated list of
+primary keys on which to filter. This is only available when dumping
+one model.
+
flush
-----
@@ -1314,6 +1323,8 @@ clearsessions
.. django-admin:: clearsessions
+.. versionadded:: 1.5
+
Can be run as a cron job or directly to clean out expired sessions.
``django.contrib.sitemaps``
diff --git a/docs/ref/exceptions.txt b/docs/ref/exceptions.txt
index f9a1715180..b15bbea8fa 100644
--- a/docs/ref/exceptions.txt
+++ b/docs/ref/exceptions.txt
@@ -44,9 +44,24 @@ SuspiciousOperation
-------------------
.. exception:: SuspiciousOperation
- The :exc:`SuspiciousOperation` exception is raised when a user has performed
- an operation that should be considered suspicious from a security perspective,
- such as tampering with a session cookie.
+ The :exc:`SuspiciousOperation` exception is raised when a user has
+ performed an operation that should be considered suspicious from a security
+ perspective, such as tampering with a session cookie. Subclasses of
+ SuspiciousOperation include:
+
+ * DisallowedHost
+ * DisallowedModelAdminLookup
+ * DisallowedRedirect
+ * InvalidSessionKey
+ * SuspiciousFileOperation
+ * SuspiciousMultipartForm
+ * SuspiciousSession
+ * WizardViewCookieModified
+
+ If a ``SuspiciousOperation`` exception reaches the WSGI handler level it is
+ logged at the ``Error`` level and results in
+ a :class:`~django.http.HttpResponseBadRequest`. See the :doc:`logging
+ documentation </topics/logging/>` for more information.
PermissionDenied
----------------
@@ -137,10 +152,16 @@ The Django wrappers for database exceptions behave exactly the same as
the underlying database exceptions. See :pep:`249`, the Python Database API
Specification v2.0, for further information.
+As per :pep:`3134`, a ``__cause__`` attribute is set with the original
+(underlying) database exception, allowing access to any additional
+information provided. (Note that this attribute is available under
+both Python 2 and Python 3, although :pep:`3134` normally only applies
+to Python 3.)
+
.. versionchanged:: 1.6
Previous version of Django only wrapped ``DatabaseError`` and
- ``IntegrityError``.
+ ``IntegrityError``, and did not provide ``__cause__``.
.. exception:: models.ProtectedError
diff --git a/docs/ref/forms/api.txt b/docs/ref/forms/api.txt
index 34ed2e493e..67e3aab712 100644
--- a/docs/ref/forms/api.txt
+++ b/docs/ref/forms/api.txt
@@ -154,6 +154,7 @@ you include ``initial`` when instantiating the ``Form``, then the latter
at the field level and at the form instance level, and the latter gets
precedence::
+ >>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='class')
... url = forms.URLField()
@@ -238,6 +239,7 @@ When the ``Form`` is valid, ``cleaned_data`` will include a key and value for
fields. In this example, the data dictionary doesn't include a value for the
``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
+ >>> from django.forms import Form
>>> class OptionalPersonForm(Form):
... first_name = CharField()
... last_name = CharField()
@@ -327,54 +329,54 @@ a form object, and each rendering method returns a Unicode object.
.. method:: Form.as_p
- ``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
- containing one field::
+``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
+containing one field::
- >>> f = ContactForm()
- >>> f.as_p()
- u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
- >>> print(f.as_p())
- <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
- <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
- <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p>
- <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
+ >>> f = ContactForm()
+ >>> f.as_p()
+ u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
+ >>> print(f.as_p())
+ <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
+ <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
+ <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p>
+ <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
``as_ul()``
~~~~~~~~~~~
.. method:: Form.as_ul
- ``as_ul()`` renders the form as a series of ``<li>`` tags, with each
- ``<li>`` containing one field. It does *not* include the ``<ul>`` or
- ``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for
- flexibility::
+``as_ul()`` renders the form as a series of ``<li>`` tags, with each
+``<li>`` containing one field. It does *not* include the ``<ul>`` or
+``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for
+flexibility::
- >>> f = ContactForm()
- >>> f.as_ul()
- u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
- >>> print(f.as_ul())
- <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
- <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
- <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>
- <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
+ >>> f = ContactForm()
+ >>> f.as_ul()
+ u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
+ >>> print(f.as_ul())
+ <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
+ <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
+ <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>
+ <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
``as_table()``
~~~~~~~~~~~~~~
.. method:: Form.as_table
- Finally, ``as_table()`` outputs the form as an HTML ``<table>``. This is
- exactly the same as ``print``. In fact, when you ``print`` a form object,
- it calls its ``as_table()`` method behind the scenes::
+Finally, ``as_table()`` outputs the form as an HTML ``<table>``. 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()
- u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
- >>> print(f.as_table())
- <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
- <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
- <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
- <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
+ >>> f = ContactForm()
+ >>> f.as_table()
+ u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
+ >>> print(f.as_table())
+ <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
+ <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
+ <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
+ <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
Styling required or erroneous form rows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -391,6 +393,8 @@ attributes to required rows or to rows with errors: simply set the
:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
attributes::
+ from django.forms import Form
+
class ContactForm(Form):
error_css_class = 'error'
required_css_class = 'required'
@@ -621,23 +625,23 @@ For a field's list of errors, access the field's ``errors`` attribute.
.. attribute:: BoundField.errors
- A list-like object that is displayed as an HTML ``<ul class="errorlist">``
- when printed::
+A list-like object that is displayed as an HTML ``<ul class="errorlist">``
+when printed::
- >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
- >>> f = ContactForm(data, auto_id=False)
- >>> print(f['message'])
- <input type="text" name="message" />
- >>> f['message'].errors
- [u'This field is required.']
- >>> print(f['message'].errors)
- <ul class="errorlist"><li>This field is required.</li></ul>
- >>> f['subject'].errors
- []
- >>> print(f['subject'].errors)
+ >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
+ >>> f = ContactForm(data, auto_id=False)
+ >>> print(f['message'])
+ <input type="text" name="message" />
+ >>> f['message'].errors
+ [u'This field is required.']
+ >>> print(f['message'].errors)
+ <ul class="errorlist"><li>This field is required.</li></ul>
+ >>> f['subject'].errors
+ []
+ >>> print(f['subject'].errors)
- >>> str(f['subject'].errors)
- ''
+ >>> str(f['subject'].errors)
+ ''
.. method:: BoundField.label_tag(contents=None, attrs=None)
@@ -779,6 +783,7 @@ example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
(in that order), and its field list includes the fields from the parent
classes::
+ >>> from django.forms import Form
>>> class PersonForm(Form):
... first_name = CharField()
... last_name = CharField()
diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt
index 8e1a4b34d1..69e3aa71ad 100644
--- a/docs/ref/forms/fields.txt
+++ b/docs/ref/forms/fields.txt
@@ -48,6 +48,7 @@ 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')
u'foo'
@@ -107,6 +108,7 @@ 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 Web site', required=False)
@@ -130,6 +132,7 @@ To specify dynamic initial data, see the :attr:`Form.initial` parameter.
The use-case for this is when you want to display an "empty" form in which a
field is initialized to a particular value. For example::
+ >>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
@@ -205,6 +208,7 @@ methods (e.g., ``as_ul()``).
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()
@@ -236,6 +240,7 @@ 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):
@@ -853,6 +858,7 @@ Slightly complex built-in ``Field`` classes
The list of fields that should be used to validate the field's value (in
the order in which they are provided).
+ >>> from django.forms import ComboField
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
>>> f.clean('test@example.com')
u'test@example.com'
@@ -1001,6 +1007,8 @@ objects (in the case of ``ModelMultipleChoiceField``) into the
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
diff --git a/docs/ref/forms/models.txt b/docs/ref/forms/models.txt
index 9b3480758a..b54056af0c 100644
--- a/docs/ref/forms/models.txt
+++ b/docs/ref/forms/models.txt
@@ -5,7 +5,7 @@ Model Form Functions
.. module:: django.forms.models
:synopsis: Django's functions for building model forms and formsets.
-.. function:: modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None)
+.. function:: modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None)
Returns a :class:`~django.forms.ModelForm` class for the given ``model``.
You can optionally pass a ``form`` argument to use as a starting point for
@@ -20,6 +20,8 @@ Model Form Functions
``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.
+
``formfield_callback`` is a callable that takes a model field and returns
a form field.
@@ -31,14 +33,16 @@ Model Form Functions
``fields`` or ``exclude``, or the corresponding attributes on the form's
inner ``Meta`` class. See :ref:`modelforms-selecting-fields` for more
information. Omitting any definition of the fields to use will result in all
- fields being used, but this behaviour is deprecated.
+ fields being used, but this behavior is deprecated.
+
+ The ``localized_fields`` parameter was added.
-.. function:: 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)
+.. function:: 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)
Returns a ``FormSet`` class for the given ``model`` class.
Arguments ``model``, ``form``, ``fields``, ``exclude``,
- ``formfield_callback`` and ``widgets`` are all passed through to
+ ``formfield_callback``, ``widgets`` and ``localized_fields`` are all passed through to
:func:`~django.forms.models.modelform_factory`.
Arguments ``formset``, ``extra``, ``max_num``, ``can_order``,
@@ -50,9 +54,9 @@ Model Form Functions
.. versionchanged:: 1.6
- The ``widgets`` and the ``validate_max`` parameters were added.
+ The ``widgets``, ``validate_max`` and ``localized_fields`` parameters were added.
-.. function:: 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)
+.. function:: 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)
Returns an ``InlineFormSet`` using :func:`modelformset_factory` with
defaults of ``formset=BaseInlineFormSet``, ``can_delete=True``, and
@@ -65,4 +69,4 @@ Model Form Functions
.. versionchanged:: 1.6
- The ``widgets`` and the ``validate_max`` parameters were added.
+ The ``widgets``, ``validate_max`` and ``localized_fields`` parameters were added.
diff --git a/docs/ref/forms/validation.txt b/docs/ref/forms/validation.txt
index 3aaa69b6ea..87c9764f64 100644
--- a/docs/ref/forms/validation.txt
+++ b/docs/ref/forms/validation.txt
@@ -183,6 +183,9 @@ the ``default_validators`` attribute.
Simple validators can be used to validate values inside the field, let's have
a look at Django's ``SlugField``::
+ from django.forms import CharField
+ from django.core import validators
+
class SlugField(CharField):
default_validators = [validators.validate_slug]
@@ -252,6 +255,8 @@ we want to make sure that the ``recipients`` field always contains the address
don't want to put it into the general ``MultiEmailField`` class. Instead, we
write a cleaning method that operates on the ``recipients`` field, like so::
+ from django import forms
+
class ContactForm(forms.Form):
# Everything as before.
...
@@ -289,6 +294,8 @@ common method is to display the error at the top of the form. To create such
an error, you can raise a ``ValidationError`` from the ``clean()`` method. For
example::
+ from django import forms
+
class ContactForm(forms.Form):
# Everything as before.
...
@@ -321,6 +328,8 @@ here and leaving it up to you and your designers to work out what works
effectively in your particular situation. Our new code (replacing the previous
sample) looks like this::
+ from django import forms
+
class ContactForm(forms.Form):
# Everything as before.
...
diff --git a/docs/ref/forms/widgets.txt b/docs/ref/forms/widgets.txt
index 678f2e6949..0f6917d44c 100644
--- a/docs/ref/forms/widgets.txt
+++ b/docs/ref/forms/widgets.txt
@@ -201,6 +201,7 @@ foundation for custom widgets.
.. code-block:: python
+ >>> from django import forms
>>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',})
>>> name.render('name', 'A name')
u'<input title="Your name" type="text" name="name" value="A name" size="10" />'
@@ -249,6 +250,8 @@ foundation for custom widgets.
:class:`~datetime.datetime` value into a list with date and time split
into two separate values::
+ from django.forms import MultiWidget
+
class SplitDateTimeWidget(MultiWidget):
# ...
diff --git a/docs/ref/middleware.txt b/docs/ref/middleware.txt
index 03885a2215..4898bab636 100644
--- a/docs/ref/middleware.txt
+++ b/docs/ref/middleware.txt
@@ -71,19 +71,6 @@ Adds a few conveniences for perfectionists:
* Sends broken link notification emails to :setting:`MANAGERS` (see
:doc:`/howto/error-reporting`).
-View metadata middleware
-------------------------
-
-.. module:: django.middleware.doc
- :synopsis: Middleware to help your app self-document.
-
-.. class:: XViewMiddleware
-
-Sends custom ``X-View`` HTTP headers to HEAD requests that come from IP
-addresses defined in the :setting:`INTERNAL_IPS` setting. This is used by
-Django's :doc:`automatic documentation system </ref/contrib/admin/admindocs>`.
-Depends on :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`.
-
GZip middleware
---------------
diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt
index 99ba78cb09..8146dfd341 100644
--- a/docs/ref/models/fields.txt
+++ b/docs/ref/models/fields.txt
@@ -80,9 +80,10 @@ If a field has ``blank=False``, the field will be required.
.. attribute:: Field.choices
-An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
-field. If this is given, the default form widget will be a select box with
-these choices instead of the standard text field.
+An iterable (e.g., a list or tuple) consisting itself of iterables of exactly
+two items (e.g. ``[(A, B), (A, B) ...]``) to use as choices for this field. If
+this is given, the default form widget will be a select box with these choices
+instead of the standard text field.
The first element in each tuple is the actual value to be stored, and the
second element is the human-readable name. For example::
@@ -97,6 +98,8 @@ second element is the human-readable name. For example::
Generally, it's best to define choices inside a model class, and to
define a suitably-named constant for each value::
+ from django.db import models
+
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
@@ -290,7 +293,12 @@ records with the same ``title`` and ``pub_date``.
Note that if you set this to point to a :class:`DateTimeField`, only the date
portion of the field will be considered.
-This is enforced by model validation but not at the database level.
+This is enforced by :meth:`Model.validate_unique()` during model validation
+but not at the database level. If any :attr:`~Field.unique_for_date` constraint
+involves fields that are not part of a :class:`~django.forms.ModelForm` (for
+example, if one of the fields is listed in ``exclude`` or has
+:attr:`editable=False<Field.editable>`), :meth:`Model.validate_unique()` will
+skip validation for that particular constraint.
``unique_for_month``
--------------------
@@ -365,7 +373,7 @@ to filter a queryset on a ``BinaryField`` value.
Although you might think about storing files in the database, consider that
it is bad design in 99% of the cases. This field is *not* a replacement for
- proper :doc`static files </howto/static-files>` handling.
+ proper :doc:`static files </howto/static-files/index>` handling.
``BooleanField``
----------------
@@ -889,7 +897,8 @@ The value ``0`` is accepted for backward compatibility reasons.
.. class:: PositiveSmallIntegerField([**options])
Like a :class:`PositiveIntegerField`, but only allows values under a certain
-(database-dependent) point.
+(database-dependent) point. Values up to 32767 are safe in all databases
+supported by Django.
``SlugField``
-------------
@@ -917,7 +926,8 @@ of some other value. You can do this automatically in the admin using
.. class:: SmallIntegerField([**options])
Like an :class:`IntegerField`, but only allows values under a certain
-(database-dependent) point.
+(database-dependent) point. Values from -32768 to 32767 are safe in all databases
+supported by Django.
``TextField``
-------------
@@ -994,12 +1004,15 @@ relationship with itself -- use ``models.ForeignKey('self')``.
If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself::
+ from django.db import models
+
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
+ pass
To refer to models defined in another application, you can explicitly specify
a model with the full application label. For example, if the ``Manufacturer``
@@ -1132,6 +1145,9 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in
necessary to avoid executing queries at the time your models.py is
imported::
+ from django.db import models
+ from django.contrib.auth.models import User
+
def get_sentinel_user():
return User.objects.get_or_create(username='deleted')[0]
@@ -1204,6 +1220,8 @@ that control how the relationship functions.
Only used in the definition of ManyToManyFields on self. Consider the
following model::
+ from django.db import models
+
class Person(models.Model):
friends = models.ManyToManyField("self")
diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt
index b4b162a9ea..f989ff1bec 100644
--- a/docs/ref/models/instances.txt
+++ b/docs/ref/models/instances.txt
@@ -34,6 +34,8 @@ that, you need to :meth:`~Model.save()`.
1. Add a classmethod on the model class::
+ from django.db import models
+
class Book(models.Model):
title = models.CharField(max_length=100)
@@ -105,6 +107,7 @@ individually.
You'll need to call ``full_clean`` manually when you want to run one-step model
validation for your own manually created models. For example::
+ from django.core.exceptions import ValidationError
try:
article.full_clean()
except ValidationError as e:
@@ -132,6 +135,7 @@ automatically provide a value for a field, or to do validation that requires
access to more than a single field::
def clean(self):
+ import datetime
from django.core.exceptions import ValidationError
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
@@ -434,6 +438,8 @@ representation of the model from the ``__unicode__()`` method.
For example::
+ from django.db import models
+
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@@ -460,6 +466,9 @@ Thus, you should return a nice, human-readable string for the object's
The previous :meth:`~Model.__unicode__()` example could be similarly written
using ``__str__()`` like this::
+ from django.db import models
+ from django.utils.encoding import force_bytes
+
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
@@ -490,6 +499,7 @@ function is usually the best approach.)
For example::
def get_absolute_url(self):
+ from django.core.urlresolvers import reverse
return reverse('people.views.details', args=[str(self.id)])
One place Django uses ``get_absolute_url()`` is in the admin app. If an object
diff --git a/docs/ref/models/options.txt b/docs/ref/models/options.txt
index 5f9316bd2a..90099d13a3 100644
--- a/docs/ref/models/options.txt
+++ b/docs/ref/models/options.txt
@@ -145,6 +145,12 @@ Django quotes column and table names behind the scenes.
and a question has more than one answer, and the order of answers matters, you'd
do this::
+ from django.db import models
+
+ class Question(models.Model):
+ text = models.TextField()
+ # ...
+
class Answer(models.Model):
question = models.ForeignKey(Question)
# ...
diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt
index ffada19082..2788143899 100644
--- a/docs/ref/models/querysets.txt
+++ b/docs/ref/models/querysets.txt
@@ -232,6 +232,7 @@ the model field that is being aggregated.
For example, if you were manipulating a list of blogs, you may want
to determine how many entries have been made in each blog::
+ >>> from django.db.models import Count
>>> q = Blog.objects.annotate(Count('entry'))
# The name of the first blog
>>> q[0].name
@@ -544,6 +545,11 @@ It is an error to pass in ``flat`` when there is more than one field.
If you don't pass any values to ``values_list()``, it will return all the
fields in the model, in the order they were declared.
+Note that this method returns a ``ValuesListQuerySet``. This class behaves
+like a list. Most of the time this is enough, but if you require an actual
+Python list object, you can simply call ``list()`` on it, which will evaluate
+the queryset.
+
dates
~~~~~
@@ -694,6 +700,8 @@ And here's ``select_related`` lookup::
``select_related()`` follows foreign keys as far as possible. If you have the
following models::
+ from django.db import models
+
class City(models.Model):
# ...
pass
@@ -766,6 +774,13 @@ You can also refer to the reverse direction of a
is defined. Instead of specifying the field name, use the :attr:`related_name
<django.db.models.ForeignKey.related_name>` for the field on the related object.
+.. versionadded:: 1.6
+
+If you need to clear the list of related fields added by past calls of
+``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::
+
+ >>> without_relations = queryset.select_related(None)
+
.. deprecated:: 1.5
The ``depth`` parameter to ``select_related()`` has been deprecated. You
should replace it with the use of the ``(*fields)`` listing specific
@@ -809,6 +824,8 @@ that are supported by ``select_related``. It also supports prefetching of
For example, suppose you have these models::
+ from django.db import models
+
class Topping(models.Model):
name = models.CharField(max_length=30)
@@ -1333,8 +1350,12 @@ get_or_create
.. method:: get_or_create(**kwargs)
-A convenience method for looking up an object with the given kwargs, creating
-one if necessary.
+A convenience method for looking up an object with the given kwargs (may be
+empty if your model has defaults for all fields), creating one if necessary.
+
+.. versionchanged:: 1.6
+
+ Older versions of Django required ``kwargs``.
Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
created object and ``created`` is a boolean specifying whether a new object was
@@ -1399,6 +1420,41 @@ has a side effect on your data. For more, see `Safe methods`_ in the HTTP spec.
.. _Safe methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
+.. warning::
+
+ You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField`
+ attributes and reverse relations. In that case you will restrict the queries
+ inside the context of that relation. That could lead you to some integrity
+ problems if you don't use it consistently.
+
+ Being the following models::
+
+ class Chapter(models.Model):
+ title = models.CharField(max_length=255, unique=True)
+
+ class Book(models.Model):
+ title = models.CharField(max_length=256)
+ chapters = models.ManyToManyField(Chapter)
+
+ You can use ``get_or_create()`` through Book's chapters field, but it only
+ fetches inside the context of that book::
+
+ >>> book = Book.objects.create(title="Ulysses")
+ >>> book.chapters.get_or_create(title="Telemachus")
+ (<Chapter: Telemachus>, True)
+ >>> book.chapters.get_or_create(title="Telemachus")
+ (<Chapter: Telemachus>, False)
+ >>> Chapter.objects.create(title="Chapter 1")
+ <Chapter: 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.
+
+
bulk_create
~~~~~~~~~~~
@@ -1540,6 +1596,36 @@ earliest
Works otherwise like :meth:`~django.db.models.query.QuerySet.latest` except
the direction is changed.
+first
+~~~~~
+.. method:: first()
+
+.. versionadded:: 1.6
+
+Returns the first object matched by the queryset, or ``None`` if there
+is no matching object. If the ``QuerySet`` has no ordering defined, then the
+queryset is automatically ordered by the primary key.
+
+Example::
+
+ p = Article.objects.order_by('title', 'pub_date').first()
+
+Note that ``first()`` is a convenience method, the following code sample is
+equivalent to the above example::
+
+ try:
+ p = Article.objects.order_by('title', 'pub_date')[0]
+ except IndexError:
+ p = None
+
+last
+~~~~
+.. method:: last()
+
+.. versionadded:: 1.6
+
+Works like :meth:`first()`, but returns the last object in the queryset.
+
aggregate
~~~~~~~~~
@@ -1560,6 +1646,7 @@ aggregated.
For example, when you are working with blog entries, you may want to know the
number of authors that have contributed blog entries::
+ >>> from django.db.models import Count
>>> q = Blog.objects.aggregate(Count('entry'))
{'entry__count': 16}
@@ -2037,6 +2124,7 @@ Range test (inclusive).
Example::
+ import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))
diff --git a/docs/ref/models/relations.txt b/docs/ref/models/relations.txt
index c923961a19..ffebe37193 100644
--- a/docs/ref/models/relations.txt
+++ b/docs/ref/models/relations.txt
@@ -12,8 +12,11 @@ Related objects reference
* The "other side" of a :class:`~django.db.models.ForeignKey` relation.
That is::
+ from django.db import models
+
class Reporter(models.Model):
- ...
+ # ...
+ pass
class Article(models.Model):
reporter = models.ForeignKey(Reporter)
@@ -24,7 +27,8 @@ Related objects reference
* Both sides of a :class:`~django.db.models.ManyToManyField` relation::
class Topping(models.Model):
- ...
+ # ...
+ pass
class Pizza(models.Model):
toppings = models.ManyToManyField(Topping)
diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt
index 2fac7f2f9c..578418b4ee 100644
--- a/docs/ref/request-response.txt
+++ b/docs/ref/request-response.txt
@@ -578,20 +578,27 @@ streaming response if (and only if) no middleware accesses the
instantiated with an iterator. Django will consume and save the content of
the iterator on first access.
-Setting headers
-~~~~~~~~~~~~~~~
+Setting header fields
+~~~~~~~~~~~~~~~~~~~~~
-To set or remove a header in your response, treat it like a dictionary::
+To set or remove a header field in your response, treat it like a dictionary::
>>> response = HttpResponse()
- >>> response['Cache-Control'] = 'no-cache'
- >>> del response['Cache-Control']
+ >>> response['Age'] = 120
+ >>> del response['Age']
Note that unlike a dictionary, ``del`` doesn't raise ``KeyError`` if the header
-doesn't exist.
+field doesn't exist.
+
+For setting the ``Cache-Control`` and ``Vary`` header fields, it is recommended
+to use the :func:`~django.utils.cache.patch_cache_control` and
+:func:`~django.utils.cache.patch_vary_headers` methods from
+:mod:`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 headers cannot contain newlines. An attempt to set a header containing a
-newline character (CR or LF) will raise ``BadHeaderError``
+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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -616,7 +623,13 @@ Attributes
.. attribute:: HttpResponse.status_code
- The `HTTP Status code`_ for the response.
+ The `HTTP status code`_ for the response.
+
+.. attribute:: HttpResponse.reason_phrase
+
+ .. versionadded:: 1.6
+
+ The HTTP reason phrase for the response.
.. attribute:: HttpResponse.streaming
@@ -628,7 +641,7 @@ Attributes
Methods
-------
-.. method:: HttpResponse.__init__(content='', content_type=None, status=200)
+.. method:: HttpResponse.__init__(content='', content_type=None, status=200, reason=None)
Instantiates an ``HttpResponse`` object with the given page content and
content type.
@@ -646,8 +659,12 @@ Methods
Historically, this parameter was called ``mimetype`` (now deprecated).
- ``status`` is the `HTTP Status code`_ for the response.
+ ``status`` is the `HTTP status code`_ for the response.
+ .. versionadded:: 1.6
+
+ ``reason`` is the HTTP response phrase. If not provided, a default phrase
+ will be used.
.. method:: HttpResponse.__setitem__(header, value)
@@ -727,8 +744,7 @@ Methods
This method makes an :class:`HttpResponse` instance a file-like object.
-.. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
-
+.. _HTTP status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
.. _ref-httpresponse-subclasses:
@@ -851,7 +867,13 @@ Attributes
.. attribute:: HttpResponse.status_code
- The `HTTP Status code`_ for the response.
+ The `HTTP status code`_ for the response.
+
+.. attribute:: HttpResponse.reason_phrase
+
+ .. versionadded:: 1.6
+
+ The HTTP reason phrase for the response.
.. attribute:: HttpResponse.streaming
diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt
index eb470cdd14..ef52d3170c 100644
--- a/docs/ref/settings.txt
+++ b/docs/ref/settings.txt
@@ -280,6 +280,12 @@ CACHE_MIDDLEWARE_ANONYMOUS_ONLY
Default: ``False``
+.. deprecated:: 1.6
+
+ This setting was largely ineffective because of using cookies for sessions
+ and CSRF. See the :doc:`Django 1.6 release notes</releases/1.6>` for more
+ information.
+
If the value of this setting is ``True``, only anonymous requests (i.e., not
those made by a logged-in user) will be cached. Otherwise, the middleware
caches every page that doesn't have GET or POST parameters.
@@ -287,8 +293,6 @@ caches every page that doesn't have GET or POST parameters.
If you set the value of this setting to ``True``, you should make sure you've
activated ``AuthenticationMiddleware``.
-See :doc:`/topics/cache`.
-
.. setting:: CACHE_MIDDLEWARE_KEY_PREFIX
CACHE_MIDDLEWARE_KEY_PREFIX
@@ -340,9 +344,9 @@ CSRF_COOKIE_HTTPONLY
Default: ``False``
-Whether to use HttpOnly flag on the CSRF cookie. If this is set to ``True``,
-client-side JavaScript will not to be able to access the CSRF cookie. See
-:setting:`SESSION_COOKIE_HTTPONLY` for details on HttpOnly.
+Whether to use ``HttpOnly`` flag on the CSRF cookie. If this is set to
+``True``, client-side JavaScript will not to be able to access the CSRF cookie.
+See :setting:`SESSION_COOKIE_HTTPONLY` for details on ``HttpOnly``.
.. setting:: CSRF_COOKIE_NAME
@@ -1239,7 +1243,7 @@ Default: ``()`` (Empty tuple)
A tuple of IP addresses, as strings, that:
* See debug comments, when :setting:`DEBUG` is ``True``
-* Receive X headers if the ``XViewMiddleware`` is installed (see
+* Receive X headers in admindocs if the ``XViewMiddleware`` is installed (see
:doc:`/topics/http/middleware`)
.. setting:: LANGUAGE_CODE
@@ -2227,6 +2231,9 @@ Controls where Django stores message data. Valid values are:
See :ref:`message storage backends <message-storage-backends>` for more details.
+The backends that use cookies -- ``CookieStorage`` and ``FallbackStorage`` --
+use the value of :setting:`SESSION_COOKIE_DOMAIN` when setting their cookies.
+
.. setting:: MESSAGE_TAGS
MESSAGE_TAGS
@@ -2258,18 +2265,6 @@ to override. See :ref:`message-displaying` above for more details.
according to the values in the above :ref:`constants table
<message-level-constants>`.
-.. _messages-session_cookie_domain:
-
-SESSION_COOKIE_DOMAIN
----------------------
-
-Default: ``None``
-
-The storage backends that use cookies -- ``CookieStorage`` and
-``FallbackStorage`` -- use the value of :setting:`SESSION_COOKIE_DOMAIN` in
-setting their cookies.
-
-
.. _settings-sessions:
Sessions
@@ -2320,7 +2315,7 @@ SESSION_COOKIE_HTTPONLY
Default: ``True``
-Whether to use HTTPOnly flag on the session cookie. If this is set to
+Whether to use ``HTTPOnly`` flag on the session cookie. If this is set to
``True``, client-side JavaScript will not to be able to access the
session cookie.
diff --git a/docs/ref/signals.txt b/docs/ref/signals.txt
index ca472bd60e..e7270e1957 100644
--- a/docs/ref/signals.txt
+++ b/docs/ref/signals.txt
@@ -360,6 +360,53 @@ Management signals
Signals sent by :doc:`django-admin </ref/django-admin>`.
+pre_syncdb
+----------
+
+.. data:: django.db.models.signals.pre_syncdb
+ :module:
+
+Sent by the :djadmin:`syncdb` command before it starts to install an
+application.
+
+Any handlers that listen to this signal need to be written in a particular
+place: a ``management`` module in one of your :setting:`INSTALLED_APPS`. If
+handlers are registered anywhere else they may not be loaded by
+:djadmin:`syncdb`.
+
+Arguments sent with this signal:
+
+``sender``
+ The ``models`` module that was just installed. That is, if
+ :djadmin:`syncdb` just installed an app called ``"foo.bar.myapp"``,
+ ``sender`` will be the ``foo.bar.myapp.models`` module.
+
+``app``
+ Same as ``sender``.
+
+``create_models``
+ A list of the model classes from any app which :djadmin:`syncdb` plans to
+ create.
+
+
+``verbosity``
+ Indicates how much information manage.py is printing on screen. See
+ the :djadminopt:`--verbosity` flag for details.
+
+ Functions which listen for :data:`pre_syncdb` should adjust what they
+ output to the screen based on the value of this argument.
+
+``interactive``
+ If ``interactive`` is ``True``, it's safe to prompt the user to input
+ things on the command line. If ``interactive`` is ``False``, functions
+ which listen for this signal should not try to prompt for anything.
+
+ For example, the :mod:`django.contrib.auth` app only prompts to create a
+ superuser when ``interactive`` is ``True``.
+
+``db``
+ The alias of database on which a command will operate.
+
post_syncdb
-----------
diff --git a/docs/ref/template-response.txt b/docs/ref/template-response.txt
index cdefe2fae8..4f34d150ed 100644
--- a/docs/ref/template-response.txt
+++ b/docs/ref/template-response.txt
@@ -215,6 +215,7 @@ re-rendered, you can re-evaluate the rendered content, and assign
the content of the response manually::
# Set up a rendered TemplateResponse
+ >>> from django.template.response import TemplateResponse
>>> t = TemplateResponse(request, 'original.html', {})
>>> t.render()
>>> print(t.content)
@@ -256,6 +257,8 @@ To define a post-render callback, just define a function that takes
a single argument -- response -- and register that function with
the template response::
+ from django.template.response import TemplateResponse
+
def my_render_callback(response):
# Do content-sensitive processing
do_post_processing()
diff --git a/docs/ref/templates/api.txt b/docs/ref/templates/api.txt
index 677aa13cbb..160cdc7194 100644
--- a/docs/ref/templates/api.txt
+++ b/docs/ref/templates/api.txt
@@ -286,6 +286,7 @@ 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'
@@ -397,6 +398,9 @@ Also, you can give ``RequestContext`` a list of additional processors, using the
optional, third positional argument, ``processors``. In this example, the
``RequestContext`` instance gets a ``ip_address`` variable::
+ from django.http import HttpResponse
+ from django.template import RequestContext
+
def ip_address_processor(request):
return {'ip_address': request.META['REMOTE_ADDR']}
@@ -417,6 +421,9 @@ optional, third positional argument, ``processors``. In this example, the
:func:`~django.shortcuts.render_to_response()`: a ``RequestContext``
instance. Your code might look like this::
+ from django.shortcuts import render_to_response
+ from django.template import RequestContext
+
def some_view(request):
# ...
return render_to_response('my_template.html',
diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
index 287fd4f59e..24eda2ce2c 100644
--- a/docs/ref/templates/builtins.txt
+++ b/docs/ref/templates/builtins.txt
@@ -862,6 +862,8 @@ above would result in the following output:
* New York: 20,000,000
* India
* Calcutta: 15,000,000
+* USA
+ * Chicago: 7,000,000
* Japan
* Tokyo: 33,000,000
diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt
index 14ae9aa9b8..d2ef945a2e 100644
--- a/docs/ref/utils.txt
+++ b/docs/ref/utils.txt
@@ -490,7 +490,7 @@ Atom1Feed
Usually you should build up HTML using Django's templates to make use of its
autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
-where appropriate. This module provides some additional low level utilitiesfor
+where appropriate. This module provides some additional low level utilities for
escaping HTML.
.. function:: escape(text)
@@ -564,7 +564,13 @@ escaping HTML.
strip_tags(value)
If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
- return value will be ``"Joel is a slug"``.
+ return value will be ``"Joel is a slug"``. Note that ``strip_tags`` result
+ may still contain unsafe HTML content, so you might use
+ :func:`~django.utils.html.escape` to make it a safe string.
+
+ .. versionchanged:: 1.6
+
+ For improved safety, ``strip_tags`` is now parser-based.
.. function:: remove_tags(value, tags)
@@ -923,9 +929,21 @@ For a complete discussion on the usage of the following see the
.. function:: now()
- Returns an aware or naive :class:`~datetime.datetime` that represents the
- current point in time when :setting:`USE_TZ` is ``True`` or ``False``
- respectively.
+ Returns a :class:`~datetime.datetime` that represents the
+ current point in time. Exactly what's returned depends on the value of
+ :setting:`USE_TZ`:
+
+ * If :setting:`USE_TZ` is ``False``, this will be be a
+ :ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
+ without an associated timezone) that represents the current time
+ in the system's local timezone.
+
+ * If :setting:`USE_TZ` is ``True``, this will be an
+ :ref:`aware <naive_vs_aware_datetimes>` datetime representing the
+ current time in UTC. Note that :func:`now` will always return
+ times in UTC regardless of the value of :setting:`TIME_ZONE`;
+ you can use :func:`localtime` to convert to a time in the current
+ time zone.
.. function:: is_aware(value)