Merge pull request #1162 from sspross/patch-docs
Add needed Imports to the Documentation, Part II
This commit is contained in:
commit
c6855e8a70
1
AUTHORS
1
AUTHORS
|
@ -343,6 +343,7 @@ answer newbie questions, and generally made Django that much better:
|
||||||
David Krauth
|
David Krauth
|
||||||
Kevin Kubasik <kevin@kubasik.net>
|
Kevin Kubasik <kevin@kubasik.net>
|
||||||
kurtiss@meetro.com
|
kurtiss@meetro.com
|
||||||
|
Vladimir Kuzma <vladimirkuzma.ch@gmail.com>
|
||||||
Denis Kuzmichyov <kuzmichyov@gmail.com>
|
Denis Kuzmichyov <kuzmichyov@gmail.com>
|
||||||
Panos Laganakos <panos.laganakos@gmail.com>
|
Panos Laganakos <panos.laganakos@gmail.com>
|
||||||
Nick Lane <nick.lane.au@gmail.com>
|
Nick Lane <nick.lane.au@gmail.com>
|
||||||
|
|
|
@ -300,18 +300,21 @@ Template filter code falls into one of two situations:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
from django.utils.html import conditional_escape
|
from django import template
|
||||||
from django.utils.safestring import mark_safe
|
from django.utils.html import conditional_escape
|
||||||
|
from django.utils.safestring import mark_safe
|
||||||
|
|
||||||
@register.filter(needs_autoescape=True)
|
register = template.Library()
|
||||||
def initial_letter_filter(text, autoescape=None):
|
|
||||||
first, other = text[0], text[1:]
|
@register.filter(needs_autoescape=True)
|
||||||
if autoescape:
|
def initial_letter_filter(text, autoescape=None):
|
||||||
esc = conditional_escape
|
first, other = text[0], text[1:]
|
||||||
else:
|
if autoescape:
|
||||||
esc = lambda x: x
|
esc = conditional_escape
|
||||||
result = '<strong>%s</strong>%s' % (esc(first), esc(other))
|
else:
|
||||||
return mark_safe(result)
|
esc = lambda x: x
|
||||||
|
result = '<strong>%s</strong>%s' % (esc(first), esc(other))
|
||||||
|
return mark_safe(result)
|
||||||
|
|
||||||
The ``needs_autoescape`` flag and the ``autoescape`` keyword argument mean
|
The ``needs_autoescape`` flag and the ``autoescape`` keyword argument mean
|
||||||
that our function will know whether automatic escaping is in effect when the
|
that our function will know whether automatic escaping is in effect when the
|
||||||
|
@ -454,8 +457,9 @@ Continuing the above example, we need to define ``CurrentTimeNode``:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
from django import template
|
|
||||||
import datetime
|
import datetime
|
||||||
|
from django import template
|
||||||
|
|
||||||
class CurrentTimeNode(template.Node):
|
class CurrentTimeNode(template.Node):
|
||||||
def __init__(self, format_string):
|
def __init__(self, format_string):
|
||||||
self.format_string = format_string
|
self.format_string = format_string
|
||||||
|
@ -498,6 +502,8 @@ The ``__init__`` method for the ``Context`` class takes a parameter called
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
from django.template import Context
|
||||||
|
|
||||||
def render(self, context):
|
def render(self, context):
|
||||||
# ...
|
# ...
|
||||||
new_context = Context({'var': obj}, autoescape=context.autoescape)
|
new_context = Context({'var': obj}, autoescape=context.autoescape)
|
||||||
|
@ -545,7 +551,10 @@ A naive implementation of ``CycleNode`` might look something like this:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
class CycleNode(Node):
|
import itertools
|
||||||
|
from django import template
|
||||||
|
|
||||||
|
class CycleNode(template.Node):
|
||||||
def __init__(self, cyclevars):
|
def __init__(self, cyclevars):
|
||||||
self.cycle_iter = itertools.cycle(cyclevars)
|
self.cycle_iter = itertools.cycle(cyclevars)
|
||||||
def render(self, context):
|
def render(self, context):
|
||||||
|
@ -576,7 +585,7 @@ Let's refactor our ``CycleNode`` implementation to use the ``render_context``:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
class CycleNode(Node):
|
class CycleNode(template.Node):
|
||||||
def __init__(self, cyclevars):
|
def __init__(self, cyclevars):
|
||||||
self.cyclevars = cyclevars
|
self.cyclevars = cyclevars
|
||||||
def render(self, context):
|
def render(self, context):
|
||||||
|
@ -664,6 +673,7 @@ Now your tag should begin to look like this:
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
from django import template
|
from django import template
|
||||||
|
|
||||||
def do_format_time(parser, token):
|
def do_format_time(parser, token):
|
||||||
try:
|
try:
|
||||||
# split_contents() knows not to split quoted strings.
|
# split_contents() knows not to split quoted strings.
|
||||||
|
@ -722,6 +732,11 @@ Our earlier ``current_time`` function could thus be written like this:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
from django import template
|
||||||
|
|
||||||
|
register = template.Library()
|
||||||
|
|
||||||
def current_time(format_string):
|
def current_time(format_string):
|
||||||
return datetime.datetime.now().strftime(format_string)
|
return datetime.datetime.now().strftime(format_string)
|
||||||
|
|
||||||
|
@ -965,6 +980,9 @@ outputting it:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
from django import template
|
||||||
|
|
||||||
class CurrentTimeNode2(template.Node):
|
class CurrentTimeNode2(template.Node):
|
||||||
def __init__(self, format_string):
|
def __init__(self, format_string):
|
||||||
self.format_string = format_string
|
self.format_string = format_string
|
||||||
|
|
|
@ -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``
|
customizing the interface. All options are defined on the ``ModelAdmin``
|
||||||
subclass::
|
subclass::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class AuthorAdmin(admin.ModelAdmin):
|
class AuthorAdmin(admin.ModelAdmin):
|
||||||
date_hierarchy = 'pub_date'
|
date_hierarchy = 'pub_date'
|
||||||
|
|
||||||
|
@ -157,6 +159,8 @@ subclass::
|
||||||
|
|
||||||
For example, let's consider the following model::
|
For example, let's consider the following model::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Author(models.Model):
|
class Author(models.Model):
|
||||||
name = models.CharField(max_length=100)
|
name = models.CharField(max_length=100)
|
||||||
title = models.CharField(max_length=3)
|
title = models.CharField(max_length=3)
|
||||||
|
@ -166,6 +170,8 @@ subclass::
|
||||||
and ``title`` fields, you would specify ``fields`` or ``exclude`` like
|
and ``title`` fields, you would specify ``fields`` or ``exclude`` like
|
||||||
this::
|
this::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class AuthorAdmin(admin.ModelAdmin):
|
class AuthorAdmin(admin.ModelAdmin):
|
||||||
fields = ('name', 'title')
|
fields = ('name', 'title')
|
||||||
|
|
||||||
|
@ -234,6 +240,8 @@ subclass::
|
||||||
A full example, taken from the
|
A full example, taken from the
|
||||||
:class:`django.contrib.flatpages.models.FlatPage` model::
|
:class:`django.contrib.flatpages.models.FlatPage` model::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class FlatPageAdmin(admin.ModelAdmin):
|
class FlatPageAdmin(admin.ModelAdmin):
|
||||||
fieldsets = (
|
fieldsets = (
|
||||||
(None, {
|
(None, {
|
||||||
|
@ -356,6 +364,10 @@ subclass::
|
||||||
If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
|
If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
|
||||||
option then ``ModelAdmin`` takes precedence::
|
option then ``ModelAdmin`` takes precedence::
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
from django.contrib import admin
|
||||||
|
from myapp.models import Person
|
||||||
|
|
||||||
class PersonForm(forms.ModelForm):
|
class PersonForm(forms.ModelForm):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
@ -459,6 +471,9 @@ subclass::
|
||||||
the same as the callable, but ``self`` in this context is the model
|
the same as the callable, but ``self`` in this context is the model
|
||||||
instance. Here's a full model example::
|
instance. Here's a full model example::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
name = models.CharField(max_length=50)
|
name = models.CharField(max_length=50)
|
||||||
birthday = models.DateField()
|
birthday = models.DateField()
|
||||||
|
@ -494,6 +509,8 @@ subclass::
|
||||||
|
|
||||||
Here's a full example model::
|
Here's a full example model::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from django.contrib import admin
|
||||||
from django.utils.html import format_html
|
from django.utils.html import format_html
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
|
@ -519,6 +536,9 @@ subclass::
|
||||||
|
|
||||||
Here's a full example model::
|
Here's a full example model::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
first_name = models.CharField(max_length=50)
|
first_name = models.CharField(max_length=50)
|
||||||
birthday = models.DateField()
|
birthday = models.DateField()
|
||||||
|
@ -547,6 +567,8 @@ subclass::
|
||||||
|
|
||||||
For example::
|
For example::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from django.contrib import admin
|
||||||
from django.utils.html import format_html
|
from django.utils.html import format_html
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
|
@ -634,13 +656,13 @@ subclass::
|
||||||
``BooleanField``, ``CharField``, ``DateField``, ``DateTimeField``,
|
``BooleanField``, ``CharField``, ``DateField``, ``DateTimeField``,
|
||||||
``IntegerField``, ``ForeignKey`` or ``ManyToManyField``, for example::
|
``IntegerField``, ``ForeignKey`` or ``ManyToManyField``, for example::
|
||||||
|
|
||||||
class PersonAdmin(ModelAdmin):
|
class PersonAdmin(admin.ModelAdmin):
|
||||||
list_filter = ('is_staff', 'company')
|
list_filter = ('is_staff', 'company')
|
||||||
|
|
||||||
Field names in ``list_filter`` can also span relations
|
Field names in ``list_filter`` can also span relations
|
||||||
using the ``__`` lookup, for example::
|
using the ``__`` lookup, for example::
|
||||||
|
|
||||||
class PersonAdmin(UserAdmin):
|
class PersonAdmin(admin.UserAdmin):
|
||||||
list_filter = ('company__name',)
|
list_filter = ('company__name',)
|
||||||
|
|
||||||
* a class inheriting from ``django.contrib.admin.SimpleListFilter``,
|
* a class inheriting from ``django.contrib.admin.SimpleListFilter``,
|
||||||
|
@ -650,10 +672,10 @@ subclass::
|
||||||
|
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
from django.utils.translation import ugettext_lazy as _
|
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
|
# Human-readable title which will be displayed in the
|
||||||
# right admin sidebar just above the filter options.
|
# right admin sidebar just above the filter options.
|
||||||
title = _('decade born')
|
title = _('decade born')
|
||||||
|
@ -689,7 +711,7 @@ subclass::
|
||||||
return queryset.filter(birthday__gte=date(1990, 1, 1),
|
return queryset.filter(birthday__gte=date(1990, 1, 1),
|
||||||
birthday__lte=date(1999, 12, 31))
|
birthday__lte=date(1999, 12, 31))
|
||||||
|
|
||||||
class PersonAdmin(ModelAdmin):
|
class PersonAdmin(admin.ModelAdmin):
|
||||||
list_filter = (DecadeBornListFilter,)
|
list_filter = (DecadeBornListFilter,)
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
@ -732,11 +754,9 @@ subclass::
|
||||||
element is a class inheriting from
|
element is a class inheriting from
|
||||||
``django.contrib.admin.FieldListFilter``, for example::
|
``django.contrib.admin.FieldListFilter``, for example::
|
||||||
|
|
||||||
from django.contrib.admin import BooleanFieldListFilter
|
class PersonAdmin(admin.ModelAdmin):
|
||||||
|
|
||||||
class PersonAdmin(ModelAdmin):
|
|
||||||
list_filter = (
|
list_filter = (
|
||||||
('is_staff', BooleanFieldListFilter),
|
('is_staff', admin.BooleanFieldListFilter),
|
||||||
)
|
)
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
@ -746,7 +766,7 @@ subclass::
|
||||||
|
|
||||||
It is possible to specify a custom template for rendering a list filter::
|
It is possible to specify a custom template for rendering a list filter::
|
||||||
|
|
||||||
class FilterWithCustomTemplate(SimpleListFilter):
|
class FilterWithCustomTemplate(admin.SimpleListFilter):
|
||||||
template = "custom_template.html"
|
template = "custom_template.html"
|
||||||
|
|
||||||
See the default template provided by django (``admin/filter.html``) for
|
See the default template provided by django (``admin/filter.html``) for
|
||||||
|
@ -876,10 +896,11 @@ subclass::
|
||||||
the admin interface to provide feedback on the status of the objects being
|
the admin interface to provide feedback on the status of the objects being
|
||||||
edited, for example::
|
edited, for example::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
from django.utils.html import format_html_join
|
from django.utils.html import format_html_join
|
||||||
from django.utils.safestring import mark_safe
|
from django.utils.safestring import mark_safe
|
||||||
|
|
||||||
class PersonAdmin(ModelAdmin):
|
class PersonAdmin(admin.ModelAdmin):
|
||||||
readonly_fields = ('address_report',)
|
readonly_fields = ('address_report',)
|
||||||
|
|
||||||
def address_report(self, instance):
|
def address_report(self, instance):
|
||||||
|
@ -1038,6 +1059,8 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
|
|
||||||
For example to attach ``request.user`` to the object prior to saving::
|
For example to attach ``request.user`` to the object prior to saving::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class ArticleAdmin(admin.ModelAdmin):
|
class ArticleAdmin(admin.ModelAdmin):
|
||||||
def save_model(self, request, obj, form, change):
|
def save_model(self, request, obj, form, change):
|
||||||
obj.user = request.user
|
obj.user = request.user
|
||||||
|
@ -1071,7 +1094,7 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
is expected to return a ``list`` or ``tuple`` for ordering similar
|
is expected to return a ``list`` or ``tuple`` for ordering similar
|
||||||
to the :attr:`ordering` attribute. For example::
|
to the :attr:`ordering` attribute. For example::
|
||||||
|
|
||||||
class PersonAdmin(ModelAdmin):
|
class PersonAdmin(admin.ModelAdmin):
|
||||||
|
|
||||||
def get_ordering(self, request):
|
def get_ordering(self, request):
|
||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
|
@ -1298,6 +1321,8 @@ templates used by the :class:`ModelAdmin` views:
|
||||||
Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
|
Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
|
||||||
on the changelist page. To use a custom form, for example::
|
on the changelist page. To use a custom form, for example::
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
|
||||||
class MyForm(forms.ModelForm):
|
class MyForm(forms.ModelForm):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -1539,6 +1564,8 @@ information.
|
||||||
The admin interface has the ability to edit models on the same page as a
|
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::
|
parent model. These are called inlines. Suppose you have these two models::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Author(models.Model):
|
class Author(models.Model):
|
||||||
name = models.CharField(max_length=100)
|
name = models.CharField(max_length=100)
|
||||||
|
|
||||||
|
@ -1549,6 +1576,8 @@ information.
|
||||||
You can edit the books authored by an author on the author page. You add
|
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``::
|
inlines to a model by specifying them in a ``ModelAdmin.inlines``::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class BookInline(admin.TabularInline):
|
class BookInline(admin.TabularInline):
|
||||||
model = Book
|
model = Book
|
||||||
|
|
||||||
|
@ -1682,6 +1711,8 @@ 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.
|
It is sometimes possible to have more than one foreign key to the same model.
|
||||||
Take this model for instance::
|
Take this model for instance::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Friendship(models.Model):
|
class Friendship(models.Model):
|
||||||
to_person = models.ForeignKey(Person, related_name="friends")
|
to_person = models.ForeignKey(Person, related_name="friends")
|
||||||
from_person = models.ForeignKey(Person, related_name="from_friends")
|
from_person = models.ForeignKey(Person, related_name="from_friends")
|
||||||
|
@ -1690,6 +1721,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
|
you need to explicitly define the foreign key since it is unable to do so
|
||||||
automatically::
|
automatically::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
from myapp.models import Friendship
|
||||||
|
|
||||||
class FriendshipInline(admin.TabularInline):
|
class FriendshipInline(admin.TabularInline):
|
||||||
model = Friendship
|
model = Friendship
|
||||||
fk_name = "to_person"
|
fk_name = "to_person"
|
||||||
|
@ -1712,6 +1746,8 @@ widgets with inlines.
|
||||||
|
|
||||||
Suppose we have the following models::
|
Suppose we have the following models::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
name = models.CharField(max_length=128)
|
name = models.CharField(max_length=128)
|
||||||
|
|
||||||
|
@ -1722,6 +1758,8 @@ Suppose we have the following models::
|
||||||
If you want to display many-to-many relations using an inline, you can do
|
If you want to display many-to-many relations using an inline, you can do
|
||||||
so by defining an ``InlineModelAdmin`` object for the relationship::
|
so by defining an ``InlineModelAdmin`` object for the relationship::
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
class MembershipInline(admin.TabularInline):
|
class MembershipInline(admin.TabularInline):
|
||||||
model = Group.members.through
|
model = Group.members.through
|
||||||
|
|
||||||
|
@ -1768,6 +1806,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
|
this is easy to do with inline admin models. Suppose we have the following
|
||||||
models::
|
models::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Person(models.Model):
|
class Person(models.Model):
|
||||||
name = models.CharField(max_length=128)
|
name = models.CharField(max_length=128)
|
||||||
|
|
||||||
|
@ -1816,6 +1856,8 @@ Using generic relations as an inline
|
||||||
It is possible to use an inline with generically related objects. Let's say
|
It is possible to use an inline with generically related objects. Let's say
|
||||||
you have the following models::
|
you have the following models::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Image(models.Model):
|
class Image(models.Model):
|
||||||
image = models.ImageField(upload_to="images")
|
image = models.ImageField(upload_to="images")
|
||||||
content_type = models.ForeignKey(ContentType)
|
content_type = models.ForeignKey(ContentType)
|
||||||
|
|
|
@ -384,6 +384,7 @@ Utilities
|
||||||
the middleware. Example::
|
the middleware. Example::
|
||||||
|
|
||||||
from django.views.decorators.csrf import csrf_exempt
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
@csrf_exempt
|
@csrf_exempt
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
|
|
|
@ -53,6 +53,7 @@ How to use ``FormPreview``
|
||||||
overrides the ``done()`` method::
|
overrides the ``done()`` method::
|
||||||
|
|
||||||
from django.contrib.formtools.preview import FormPreview
|
from django.contrib.formtools.preview import FormPreview
|
||||||
|
from django.http import HttpResponseRedirect
|
||||||
from myapp.models import SomeModel
|
from myapp.models import SomeModel
|
||||||
|
|
||||||
class SomeModelFormPreview(FormPreview):
|
class SomeModelFormPreview(FormPreview):
|
||||||
|
|
|
@ -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
|
at the field level and at the form instance level, and the latter gets
|
||||||
precedence::
|
precedence::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> class CommentForm(forms.Form):
|
>>> class CommentForm(forms.Form):
|
||||||
... name = forms.CharField(initial='class')
|
... name = forms.CharField(initial='class')
|
||||||
... url = forms.URLField()
|
... 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
|
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::
|
``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
|
||||||
|
|
||||||
|
>>> from django.forms import Form
|
||||||
>>> class OptionalPersonForm(Form):
|
>>> class OptionalPersonForm(Form):
|
||||||
... first_name = CharField()
|
... first_name = CharField()
|
||||||
... last_name = CharField()
|
... last_name = CharField()
|
||||||
|
@ -327,54 +329,54 @@ a form object, and each rendering method returns a Unicode object.
|
||||||
|
|
||||||
.. method:: Form.as_p
|
.. method:: Form.as_p
|
||||||
|
|
||||||
``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
|
``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
|
||||||
containing one field::
|
containing one field::
|
||||||
|
|
||||||
>>> f = ContactForm()
|
>>> f = ContactForm()
|
||||||
>>> f.as_p()
|
>>> 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>'
|
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())
|
>>> 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_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_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_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>
|
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
|
||||||
|
|
||||||
``as_ul()``
|
``as_ul()``
|
||||||
~~~~~~~~~~~
|
~~~~~~~~~~~
|
||||||
|
|
||||||
.. method:: Form.as_ul
|
.. method:: Form.as_ul
|
||||||
|
|
||||||
``as_ul()`` renders the form as a series of ``<li>`` tags, with each
|
``as_ul()`` renders the form as a series of ``<li>`` tags, with each
|
||||||
``<li>`` containing one field. It does *not* include the ``<ul>`` or
|
``<li>`` containing one field. It does *not* include the ``<ul>`` or
|
||||||
``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for
|
``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for
|
||||||
flexibility::
|
flexibility::
|
||||||
|
|
||||||
>>> f = ContactForm()
|
>>> f = ContactForm()
|
||||||
>>> f.as_ul()
|
>>> 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>'
|
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())
|
>>> 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_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_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_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>
|
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
|
||||||
|
|
||||||
``as_table()``
|
``as_table()``
|
||||||
~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. method:: Form.as_table
|
.. method:: Form.as_table
|
||||||
|
|
||||||
Finally, ``as_table()`` outputs the form as an HTML ``<table>``. This is
|
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,
|
exactly the same as ``print``. In fact, when you ``print`` a form object,
|
||||||
it calls its ``as_table()`` method behind the scenes::
|
it calls its ``as_table()`` method behind the scenes::
|
||||||
|
|
||||||
>>> f = ContactForm()
|
>>> f = ContactForm()
|
||||||
>>> f.as_table()
|
>>> 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>'
|
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())
|
>>> 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_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_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_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>
|
<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
|
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`
|
:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
|
||||||
attributes::
|
attributes::
|
||||||
|
|
||||||
|
from django.forms import Form
|
||||||
|
|
||||||
class ContactForm(Form):
|
class ContactForm(Form):
|
||||||
error_css_class = 'error'
|
error_css_class = 'error'
|
||||||
required_css_class = 'required'
|
required_css_class = 'required'
|
||||||
|
@ -621,23 +625,23 @@ For a field's list of errors, access the field's ``errors`` attribute.
|
||||||
|
|
||||||
.. attribute:: BoundField.errors
|
.. attribute:: BoundField.errors
|
||||||
|
|
||||||
A list-like object that is displayed as an HTML ``<ul class="errorlist">``
|
A list-like object that is displayed as an HTML ``<ul class="errorlist">``
|
||||||
when printed::
|
when printed::
|
||||||
|
|
||||||
>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
|
>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
|
||||||
>>> f = ContactForm(data, auto_id=False)
|
>>> f = ContactForm(data, auto_id=False)
|
||||||
>>> print(f['message'])
|
>>> print(f['message'])
|
||||||
<input type="text" name="message" />
|
<input type="text" name="message" />
|
||||||
>>> f['message'].errors
|
>>> f['message'].errors
|
||||||
[u'This field is required.']
|
[u'This field is required.']
|
||||||
>>> print(f['message'].errors)
|
>>> print(f['message'].errors)
|
||||||
<ul class="errorlist"><li>This field is required.</li></ul>
|
<ul class="errorlist"><li>This field is required.</li></ul>
|
||||||
>>> f['subject'].errors
|
>>> f['subject'].errors
|
||||||
[]
|
[]
|
||||||
>>> print(f['subject'].errors)
|
>>> print(f['subject'].errors)
|
||||||
|
|
||||||
>>> str(f['subject'].errors)
|
>>> str(f['subject'].errors)
|
||||||
''
|
''
|
||||||
|
|
||||||
.. method:: BoundField.label_tag(contents=None, attrs=None)
|
.. 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
|
(in that order), and its field list includes the fields from the parent
|
||||||
classes::
|
classes::
|
||||||
|
|
||||||
|
>>> from django.forms import Form
|
||||||
>>> class PersonForm(Form):
|
>>> class PersonForm(Form):
|
||||||
... first_name = CharField()
|
... first_name = CharField()
|
||||||
... last_name = CharField()
|
... last_name = CharField()
|
||||||
|
|
|
@ -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
|
an empty value -- either ``None`` or the empty string (``""``) -- then
|
||||||
``clean()`` will raise a ``ValidationError`` exception::
|
``clean()`` will raise a ``ValidationError`` exception::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> f = forms.CharField()
|
>>> f = forms.CharField()
|
||||||
>>> f.clean('foo')
|
>>> f.clean('foo')
|
||||||
u'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.
|
Here's a full example ``Form`` that implements ``label`` for two of its fields.
|
||||||
We've specified ``auto_id=False`` to simplify the output::
|
We've specified ``auto_id=False`` to simplify the output::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> class CommentForm(forms.Form):
|
>>> class CommentForm(forms.Form):
|
||||||
... name = forms.CharField(label='Your name')
|
... name = forms.CharField(label='Your name')
|
||||||
... url = forms.URLField(label='Your Web site', required=False)
|
... 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
|
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::
|
field is initialized to a particular value. For example::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> class CommentForm(forms.Form):
|
>>> class CommentForm(forms.Form):
|
||||||
... name = forms.CharField(initial='Your name')
|
... name = forms.CharField(initial='Your name')
|
||||||
... url = forms.URLField(initial='http://')
|
... 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
|
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::
|
fields. We've specified ``auto_id=False`` to simplify the output::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> class HelpTextContactForm(forms.Form):
|
>>> class HelpTextContactForm(forms.Form):
|
||||||
... subject = forms.CharField(max_length=100, help_text='100 characters max.')
|
... subject = forms.CharField(max_length=100, help_text='100 characters max.')
|
||||||
... message = forms.CharField()
|
... 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
|
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::
|
want to override. For example, here is the default error message::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> generic = forms.CharField()
|
>>> generic = forms.CharField()
|
||||||
>>> generic.clean('')
|
>>> generic.clean('')
|
||||||
Traceback (most recent call last):
|
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 list of fields that should be used to validate the field's value (in
|
||||||
the order in which they are provided).
|
the order in which they are provided).
|
||||||
|
|
||||||
|
>>> from django.forms import ComboField
|
||||||
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
|
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
|
||||||
>>> f.clean('test@example.com')
|
>>> f.clean('test@example.com')
|
||||||
u'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
|
object, and should return a string suitable for representing it. For
|
||||||
example::
|
example::
|
||||||
|
|
||||||
|
from django.forms import ModelChoiceField
|
||||||
|
|
||||||
class MyModelChoiceField(ModelChoiceField):
|
class MyModelChoiceField(ModelChoiceField):
|
||||||
def label_from_instance(self, obj):
|
def label_from_instance(self, obj):
|
||||||
return "My Object #%i" % obj.id
|
return "My Object #%i" % obj.id
|
||||||
|
|
|
@ -183,6 +183,9 @@ the ``default_validators`` attribute.
|
||||||
Simple validators can be used to validate values inside the field, let's have
|
Simple validators can be used to validate values inside the field, let's have
|
||||||
a look at Django's ``SlugField``::
|
a look at Django's ``SlugField``::
|
||||||
|
|
||||||
|
from django.forms import CharField
|
||||||
|
from django.core import validators
|
||||||
|
|
||||||
class SlugField(CharField):
|
class SlugField(CharField):
|
||||||
default_validators = [validators.validate_slug]
|
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
|
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::
|
write a cleaning method that operates on the ``recipients`` field, like so::
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
|
||||||
class ContactForm(forms.Form):
|
class ContactForm(forms.Form):
|
||||||
# Everything as before.
|
# 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
|
an error, you can raise a ``ValidationError`` from the ``clean()`` method. For
|
||||||
example::
|
example::
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
|
||||||
class ContactForm(forms.Form):
|
class ContactForm(forms.Form):
|
||||||
# Everything as before.
|
# 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
|
effectively in your particular situation. Our new code (replacing the previous
|
||||||
sample) looks like this::
|
sample) looks like this::
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
|
||||||
class ContactForm(forms.Form):
|
class ContactForm(forms.Form):
|
||||||
# Everything as before.
|
# Everything as before.
|
||||||
...
|
...
|
||||||
|
|
|
@ -201,6 +201,7 @@ foundation for custom widgets.
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',})
|
>>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',})
|
||||||
>>> name.render('name', 'A name')
|
>>> name.render('name', 'A name')
|
||||||
u'<input title="Your name" type="text" name="name" value="A name" size="10" />'
|
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
|
:class:`~datetime.datetime` value into a list with date and time split
|
||||||
into two separate values::
|
into two separate values::
|
||||||
|
|
||||||
|
from django.forms import MultiWidget
|
||||||
|
|
||||||
class SplitDateTimeWidget(MultiWidget):
|
class SplitDateTimeWidget(MultiWidget):
|
||||||
|
|
||||||
# ...
|
# ...
|
||||||
|
|
|
@ -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
|
from a ``Context`` object once it's been instantiated, too, using standard
|
||||||
dictionary syntax::
|
dictionary syntax::
|
||||||
|
|
||||||
|
>>> from django.template import Context
|
||||||
>>> c = Context({"foo": "bar"})
|
>>> c = Context({"foo": "bar"})
|
||||||
>>> c['foo']
|
>>> c['foo']
|
||||||
'bar'
|
'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
|
optional, third positional argument, ``processors``. In this example, the
|
||||||
``RequestContext`` instance gets a ``ip_address`` variable::
|
``RequestContext`` instance gets a ``ip_address`` variable::
|
||||||
|
|
||||||
|
from django.http import HttpResponse
|
||||||
|
from django.template import RequestContext
|
||||||
|
|
||||||
def ip_address_processor(request):
|
def ip_address_processor(request):
|
||||||
return {'ip_address': request.META['REMOTE_ADDR']}
|
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``
|
:func:`~django.shortcuts.render_to_response()`: a ``RequestContext``
|
||||||
instance. Your code might look like this::
|
instance. Your code might look like this::
|
||||||
|
|
||||||
|
from django.shortcuts import render_to_response
|
||||||
|
from django.template import RequestContext
|
||||||
|
|
||||||
def some_view(request):
|
def some_view(request):
|
||||||
# ...
|
# ...
|
||||||
return render_to_response('my_template.html',
|
return render_to_response('my_template.html',
|
||||||
|
|
|
@ -56,6 +56,9 @@ telling the formset how many additional forms to show in addition to the
|
||||||
number of forms it generates from the initial data. Lets take a look at an
|
number of forms it generates from the initial data. Lets take a look at an
|
||||||
example::
|
example::
|
||||||
|
|
||||||
|
>>> import datetime
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms imporrt ArticleForm
|
||||||
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
|
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
|
||||||
>>> formset = ArticleFormSet(initial=[
|
>>> formset = ArticleFormSet(initial=[
|
||||||
... {'title': u'Django is now open source',
|
... {'title': u'Django is now open source',
|
||||||
|
@ -88,6 +91,8 @@ The ``max_num`` parameter to :func:`~django.forms.formsets.formset_factory`
|
||||||
gives you the ability to limit the maximum number of empty forms the formset
|
gives you the ability to limit the maximum number of empty forms the formset
|
||||||
will display::
|
will display::
|
||||||
|
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms imporrt ArticleForm
|
||||||
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
|
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
|
||||||
>>> formset = ArticleFormSet()
|
>>> formset = ArticleFormSet()
|
||||||
>>> for form in formset:
|
>>> for form in formset:
|
||||||
|
@ -124,6 +129,8 @@ Validation with a formset is almost identical to a regular ``Form``. There is
|
||||||
an ``is_valid`` method on the formset to provide a convenient way to validate
|
an ``is_valid`` method on the formset to provide a convenient way to validate
|
||||||
all forms in the formset::
|
all forms in the formset::
|
||||||
|
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms imporrt ArticleForm
|
||||||
>>> ArticleFormSet = formset_factory(ArticleForm)
|
>>> ArticleFormSet = formset_factory(ArticleForm)
|
||||||
>>> data = {
|
>>> data = {
|
||||||
... 'form-TOTAL_FORMS': u'1',
|
... 'form-TOTAL_FORMS': u'1',
|
||||||
|
@ -230,6 +237,8 @@ A formset has a ``clean`` method similar to the one on a ``Form`` class. This
|
||||||
is where you define your own validation that works at the formset level::
|
is where you define your own validation that works at the formset level::
|
||||||
|
|
||||||
>>> from django.forms.formsets import BaseFormSet
|
>>> from django.forms.formsets import BaseFormSet
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms import ArticleForm
|
||||||
|
|
||||||
>>> class BaseArticleFormSet(BaseFormSet):
|
>>> class BaseArticleFormSet(BaseFormSet):
|
||||||
... def clean(self):
|
... def clean(self):
|
||||||
|
@ -276,6 +285,8 @@ If ``validate_max=True`` is passed to
|
||||||
:func:`~django.forms.formsets.formset_factory`, validation will also check
|
:func:`~django.forms.formsets.formset_factory`, validation will also check
|
||||||
that the number of forms in the data set is less than or equal to ``max_num``.
|
that the number of forms in the data set is less than or equal to ``max_num``.
|
||||||
|
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms import ArticleForm
|
||||||
>>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
|
>>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)
|
||||||
>>> data = {
|
>>> data = {
|
||||||
... 'form-TOTAL_FORMS': u'2',
|
... 'form-TOTAL_FORMS': u'2',
|
||||||
|
@ -329,6 +340,8 @@ Default: ``False``
|
||||||
|
|
||||||
Lets you create a formset with the ability to order::
|
Lets you create a formset with the ability to order::
|
||||||
|
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms import ArticleForm
|
||||||
>>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
|
>>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
|
||||||
>>> formset = ArticleFormSet(initial=[
|
>>> formset = ArticleFormSet(initial=[
|
||||||
... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
|
... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
|
||||||
|
@ -385,6 +398,8 @@ Default: ``False``
|
||||||
|
|
||||||
Lets you create a formset with the ability to delete::
|
Lets you create a formset with the ability to delete::
|
||||||
|
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms import ArticleForm
|
||||||
>>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
|
>>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
|
||||||
>>> formset = ArticleFormSet(initial=[
|
>>> formset = ArticleFormSet(initial=[
|
||||||
... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
|
... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
|
||||||
|
@ -437,6 +452,9 @@ accomplished. The formset base class provides an ``add_fields`` method. You
|
||||||
can simply override this method to add your own fields or even redefine the
|
can simply override this method to add your own fields or even redefine the
|
||||||
default fields/attributes of the order and deletion fields::
|
default fields/attributes of the order and deletion fields::
|
||||||
|
|
||||||
|
>>> from django.forms.formsets import BaseFormSet
|
||||||
|
>>> from django.forms.formsets import formset_factory
|
||||||
|
>>> from myapp.forms import ArticleForm
|
||||||
>>> class BaseArticleFormSet(BaseFormSet):
|
>>> class BaseArticleFormSet(BaseFormSet):
|
||||||
... def add_fields(self, form, index):
|
... def add_fields(self, form, index):
|
||||||
... super(BaseArticleFormSet, self).add_fields(form, index)
|
... super(BaseArticleFormSet, self).add_fields(form, index)
|
||||||
|
@ -459,6 +477,10 @@ management form inside the template. Let's look at a sample view:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
from django.forms.formsets import formset_factory
|
||||||
|
from django.shortcuts import render_to_response
|
||||||
|
from myapp.forms import ArticleForm
|
||||||
|
|
||||||
def manage_articles(request):
|
def manage_articles(request):
|
||||||
ArticleFormSet = formset_factory(ArticleForm)
|
ArticleFormSet = formset_factory(ArticleForm)
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
|
@ -534,6 +556,10 @@ a look at how this might be accomplished:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
from django.forms.formsets import formset_factory
|
||||||
|
from django.shortcuts import render_to_response
|
||||||
|
from myapp.forms import ArticleForm, BookForm
|
||||||
|
|
||||||
def manage_articles(request):
|
def manage_articles(request):
|
||||||
ArticleFormSet = formset_factory(ArticleForm)
|
ArticleFormSet = formset_factory(ArticleForm)
|
||||||
BookFormSet = formset_factory(BookForm)
|
BookFormSet = formset_factory(BookForm)
|
||||||
|
|
|
@ -49,6 +49,8 @@ define the media requirements.
|
||||||
|
|
||||||
Here's a simple example::
|
Here's a simple example::
|
||||||
|
|
||||||
|
from django import froms
|
||||||
|
|
||||||
class CalendarWidget(forms.TextInput):
|
class CalendarWidget(forms.TextInput):
|
||||||
class Media:
|
class Media:
|
||||||
css = {
|
css = {
|
||||||
|
@ -211,6 +213,7 @@ to using :setting:`MEDIA_URL`. For example, if the :setting:`MEDIA_URL` for
|
||||||
your site was ``'http://uploads.example.com/'`` and :setting:`STATIC_URL`
|
your site was ``'http://uploads.example.com/'`` and :setting:`STATIC_URL`
|
||||||
was ``None``::
|
was ``None``::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> class CalendarWidget(forms.TextInput):
|
>>> class CalendarWidget(forms.TextInput):
|
||||||
... class Media:
|
... class Media:
|
||||||
... css = {
|
... css = {
|
||||||
|
@ -267,6 +270,7 @@ Combining media objects
|
||||||
Media objects can also be added together. When two media objects are added,
|
Media objects can also be added together. When two media objects are added,
|
||||||
the resulting Media object contains the union of the media from both files::
|
the resulting Media object contains the union of the media from both files::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> class CalendarWidget(forms.TextInput):
|
>>> class CalendarWidget(forms.TextInput):
|
||||||
... class Media:
|
... class Media:
|
||||||
... css = {
|
... css = {
|
||||||
|
@ -298,6 +302,7 @@ Regardless of whether you define a media declaration, *all* Form objects
|
||||||
have a media property. The default value for this property is the result
|
have a media property. The default value for this property is the result
|
||||||
of adding the media definitions for all widgets that are part of the form::
|
of adding the media definitions for all widgets that are part of the form::
|
||||||
|
|
||||||
|
>>> from django import forms
|
||||||
>>> class ContactForm(forms.Form):
|
>>> class ContactForm(forms.Form):
|
||||||
... date = DateField(widget=CalendarWidget)
|
... date = DateField(widget=CalendarWidget)
|
||||||
... name = CharField(max_length=40, widget=OtherWidget)
|
... name = CharField(max_length=40, widget=OtherWidget)
|
||||||
|
|
|
@ -23,6 +23,7 @@ class from a Django model.
|
||||||
For example::
|
For example::
|
||||||
|
|
||||||
>>> from django.forms import ModelForm
|
>>> from django.forms import ModelForm
|
||||||
|
>>> from myapp.models import Article
|
||||||
|
|
||||||
# Create the form class.
|
# Create the form class.
|
||||||
>>> class ArticleForm(ModelForm):
|
>>> class ArticleForm(ModelForm):
|
||||||
|
@ -222,6 +223,9 @@ supplied, ``save()`` will update that instance. If it's not supplied,
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
>>> from myapp.models import Article
|
||||||
|
>>> from myapp.forms import ArticleForm
|
||||||
|
|
||||||
# Create a form instance from POST data.
|
# Create a form instance from POST data.
|
||||||
>>> f = ArticleForm(request.POST)
|
>>> f = ArticleForm(request.POST)
|
||||||
|
|
||||||
|
@ -316,6 +320,8 @@ these security concerns do not apply to you:
|
||||||
1. Set the ``fields`` attribute to the special value ``'__all__'`` to indicate
|
1. Set the ``fields`` attribute to the special value ``'__all__'`` to indicate
|
||||||
that all fields in the model should be used. For example::
|
that all fields in the model should be used. For example::
|
||||||
|
|
||||||
|
from django.forms import ModelForm
|
||||||
|
|
||||||
class AuthorForm(ModelForm):
|
class AuthorForm(ModelForm):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Author
|
model = Author
|
||||||
|
@ -401,6 +407,7 @@ of its default ``<input type="text">``, you can override the field's
|
||||||
widget::
|
widget::
|
||||||
|
|
||||||
from django.forms import ModelForm, Textarea
|
from django.forms import ModelForm, Textarea
|
||||||
|
from myapp.models import Author
|
||||||
|
|
||||||
class AuthorForm(ModelForm):
|
class AuthorForm(ModelForm):
|
||||||
class Meta:
|
class Meta:
|
||||||
|
@ -421,6 +428,9 @@ you can do this by declaratively specifying fields like you would in a regular
|
||||||
For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
|
For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
|
||||||
field, you could do the following::
|
field, you could do the following::
|
||||||
|
|
||||||
|
from django.forms import ModelForm
|
||||||
|
from myapp.models import Article
|
||||||
|
|
||||||
class ArticleForm(ModelForm):
|
class ArticleForm(ModelForm):
|
||||||
pub_date = MyDateFormField()
|
pub_date = MyDateFormField()
|
||||||
|
|
||||||
|
@ -432,6 +442,9 @@ field, you could do the following::
|
||||||
If you want to override a field's default label, then specify the ``label``
|
If you want to override a field's default label, then specify the ``label``
|
||||||
parameter when declaring the form field::
|
parameter when declaring the form field::
|
||||||
|
|
||||||
|
from django.forms import ModelForm, DateField
|
||||||
|
from myapp.models import Article
|
||||||
|
|
||||||
class ArticleForm(ModelForm):
|
class ArticleForm(ModelForm):
|
||||||
pub_date = DateField(label='Publication date')
|
pub_date = DateField(label='Publication date')
|
||||||
|
|
||||||
|
@ -484,6 +497,8 @@ By default, the fields in a ``ModelForm`` will not localize their data. To
|
||||||
enable localization for fields, you can use the ``localized_fields``
|
enable localization for fields, you can use the ``localized_fields``
|
||||||
attribute on the ``Meta`` class.
|
attribute on the ``Meta`` class.
|
||||||
|
|
||||||
|
>>> from django.forms import ModelForm
|
||||||
|
>>> from myapp.models import Author
|
||||||
>>> class AuthorForm(ModelForm):
|
>>> class AuthorForm(ModelForm):
|
||||||
... class Meta:
|
... class Meta:
|
||||||
... model = Author
|
... model = Author
|
||||||
|
@ -574,6 +589,7 @@ definition. This may be more convenient if you do not have many customizations
|
||||||
to make::
|
to make::
|
||||||
|
|
||||||
>>> from django.forms.models import modelform_factory
|
>>> from django.forms.models import modelform_factory
|
||||||
|
>>> from myapp.models import Book
|
||||||
>>> BookForm = modelform_factory(Book, fields=("author", "title"))
|
>>> BookForm = modelform_factory(Book, fields=("author", "title"))
|
||||||
|
|
||||||
This can also be used to make simple modifications to existing forms, for
|
This can also be used to make simple modifications to existing forms, for
|
||||||
|
@ -604,6 +620,7 @@ of enhanced formset classes that make it easy to work with Django models. Let's
|
||||||
reuse the ``Author`` model from above::
|
reuse the ``Author`` model from above::
|
||||||
|
|
||||||
>>> from django.forms.models import modelformset_factory
|
>>> from django.forms.models import modelformset_factory
|
||||||
|
>>> from myapp.models import Author
|
||||||
>>> AuthorFormSet = modelformset_factory(Author)
|
>>> AuthorFormSet = modelformset_factory(Author)
|
||||||
|
|
||||||
This will create a formset that is capable of working with the data associated
|
This will create a formset that is capable of working with the data associated
|
||||||
|
@ -642,6 +659,7 @@ Alternatively, you can create a subclass that sets ``self.queryset`` in
|
||||||
``__init__``::
|
``__init__``::
|
||||||
|
|
||||||
from django.forms.models import BaseModelFormSet
|
from django.forms.models import BaseModelFormSet
|
||||||
|
from myapp.models import Author
|
||||||
|
|
||||||
class BaseAuthorFormSet(BaseModelFormSet):
|
class BaseAuthorFormSet(BaseModelFormSet):
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
|
@ -787,6 +805,10 @@ Using a model formset in a view
|
||||||
Model formsets are very similar to formsets. Let's say we want to present a
|
Model formsets are very similar to formsets. Let's say we want to present a
|
||||||
formset to edit ``Author`` model instances::
|
formset to edit ``Author`` model instances::
|
||||||
|
|
||||||
|
from django.forms.models import modelformset_factory
|
||||||
|
from django.shortcuts import render_to_response
|
||||||
|
from myapp.models import Author
|
||||||
|
|
||||||
def manage_authors(request):
|
def manage_authors(request):
|
||||||
AuthorFormSet = modelformset_factory(Author)
|
AuthorFormSet = modelformset_factory(Author)
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
|
@ -815,12 +837,15 @@ the unique constraints on your model (either ``unique``, ``unique_together`` or
|
||||||
on a ``model_formset`` and maintain this validation, you must call the parent
|
on a ``model_formset`` and maintain this validation, you must call the parent
|
||||||
class's ``clean`` method::
|
class's ``clean`` method::
|
||||||
|
|
||||||
|
from django.forms.models import BaseModelFormSet
|
||||||
|
|
||||||
class MyModelFormSet(BaseModelFormSet):
|
class MyModelFormSet(BaseModelFormSet):
|
||||||
def clean(self):
|
def clean(self):
|
||||||
super(MyModelFormSet, self).clean()
|
super(MyModelFormSet, self).clean()
|
||||||
# example custom validation across forms in the formset:
|
# example custom validation across forms in the formset:
|
||||||
for form in self.forms:
|
for form in self.forms:
|
||||||
# your custom formset validation
|
# your custom formset validation
|
||||||
|
pass
|
||||||
|
|
||||||
Using a custom queryset
|
Using a custom queryset
|
||||||
-----------------------
|
-----------------------
|
||||||
|
@ -828,6 +853,10 @@ Using a custom queryset
|
||||||
As stated earlier, you can override the default queryset used by the model
|
As stated earlier, you can override the default queryset used by the model
|
||||||
formset::
|
formset::
|
||||||
|
|
||||||
|
from django.forms.models import modelformset_factory
|
||||||
|
from django.shortcuts import render_to_response
|
||||||
|
from myapp.models import Author
|
||||||
|
|
||||||
def manage_authors(request):
|
def manage_authors(request):
|
||||||
AuthorFormSet = modelformset_factory(Author)
|
AuthorFormSet = modelformset_factory(Author)
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
|
@ -914,6 +943,8 @@ Inline formsets is a small abstraction layer on top of model formsets. These
|
||||||
simplify the case of working with related objects via a foreign key. Suppose
|
simplify the case of working with related objects via a foreign key. Suppose
|
||||||
you have these two models::
|
you have these two models::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
class Author(models.Model):
|
class Author(models.Model):
|
||||||
name = models.CharField(max_length=100)
|
name = models.CharField(max_length=100)
|
||||||
|
|
||||||
|
|
|
@ -80,6 +80,7 @@ In this example, the text ``"Welcome to my site."`` is marked as a translation
|
||||||
string::
|
string::
|
||||||
|
|
||||||
from django.utils.translation import ugettext as _
|
from django.utils.translation import ugettext as _
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
output = _("Welcome to my site.")
|
output = _("Welcome to my site.")
|
||||||
|
@ -89,6 +90,7 @@ Obviously, you could code this without using the alias. This example is
|
||||||
identical to the previous one::
|
identical to the previous one::
|
||||||
|
|
||||||
from django.utils.translation import ugettext
|
from django.utils.translation import ugettext
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
def my_view(request):
|
def my_view(request):
|
||||||
output = ugettext("Welcome to my site.")
|
output = ugettext("Welcome to my site.")
|
||||||
|
@ -192,6 +194,7 @@ of its value.)
|
||||||
For example::
|
For example::
|
||||||
|
|
||||||
from django.utils.translation import ungettext
|
from django.utils.translation import ungettext
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
def hello_world(request, count):
|
def hello_world(request, count):
|
||||||
page = ungettext(
|
page = ungettext(
|
||||||
|
@ -208,6 +211,7 @@ languages as the ``count`` variable.
|
||||||
Lets see a slightly more complex usage example::
|
Lets see a slightly more complex usage example::
|
||||||
|
|
||||||
from django.utils.translation import ungettext
|
from django.utils.translation import ungettext
|
||||||
|
from myapp.models import Report
|
||||||
|
|
||||||
count = Report.objects.count()
|
count = Report.objects.count()
|
||||||
if count == 1:
|
if count == 1:
|
||||||
|
@ -283,6 +287,7 @@ For example::
|
||||||
|
|
||||||
or::
|
or::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
from django.utils.translation import pgettext_lazy
|
from django.utils.translation import pgettext_lazy
|
||||||
|
|
||||||
class MyThing(models.Model):
|
class MyThing(models.Model):
|
||||||
|
@ -328,6 +333,7 @@ Model fields and relationships ``verbose_name`` and ``help_text`` option values
|
||||||
For example, to translate the help text of the *name* field in the following
|
For example, to translate the help text of the *name* field in the following
|
||||||
model, do the following::
|
model, do the following::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
class MyThing(models.Model):
|
class MyThing(models.Model):
|
||||||
|
@ -336,8 +342,6 @@ model, do the following::
|
||||||
You can mark names of ``ForeignKey``, ``ManyTomanyField`` or ``OneToOneField``
|
You can mark names of ``ForeignKey``, ``ManyTomanyField`` or ``OneToOneField``
|
||||||
relationship as translatable by using their ``verbose_name`` options::
|
relationship as translatable by using their ``verbose_name`` options::
|
||||||
|
|
||||||
from django.utils.translation import ugettext_lazy as _
|
|
||||||
|
|
||||||
class MyThing(models.Model):
|
class MyThing(models.Model):
|
||||||
kind = models.ForeignKey(ThingKind, related_name='kinds',
|
kind = models.ForeignKey(ThingKind, related_name='kinds',
|
||||||
verbose_name=_('kind'))
|
verbose_name=_('kind'))
|
||||||
|
@ -355,6 +359,7 @@ It is recommended to always provide explicit
|
||||||
relying on the fallback English-centric and somewhat naïve determination of
|
relying on the fallback English-centric and somewhat naïve determination of
|
||||||
verbose names Django performs by looking at the model's class name::
|
verbose names Django performs by looking at the model's class name::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
class MyThing(models.Model):
|
class MyThing(models.Model):
|
||||||
|
@ -370,6 +375,7 @@ Model methods ``short_description`` attribute values
|
||||||
For model methods, you can provide translations to Django and the admin site
|
For model methods, you can provide translations to Django and the admin site
|
||||||
with the ``short_description`` attribute::
|
with the ``short_description`` attribute::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
class MyThing(models.Model):
|
class MyThing(models.Model):
|
||||||
|
@ -404,6 +410,7 @@ If you ever see output that looks like ``"hello
|
||||||
If you don't like the long ``ugettext_lazy`` name, you can just alias it as
|
If you don't like the long ``ugettext_lazy`` name, you can just alias it as
|
||||||
``_`` (underscore), like so::
|
``_`` (underscore), like so::
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
class MyThing(models.Model):
|
class MyThing(models.Model):
|
||||||
|
@ -429,6 +436,9 @@ definition. Therefore, you are authorized to pass a key name instead of an
|
||||||
integer as the ``number`` argument. Then ``number`` will be looked up in the
|
integer as the ``number`` argument. Then ``number`` will be looked up in the
|
||||||
dictionary under that key during string interpolation. Here's example::
|
dictionary under that key during string interpolation. Here's example::
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
from django.utils.translation import ugettext_lazy
|
||||||
|
|
||||||
class MyForm(forms.Form):
|
class MyForm(forms.Form):
|
||||||
error_message = ungettext_lazy("You only provided %(num)d argument",
|
error_message = ungettext_lazy("You only provided %(num)d argument",
|
||||||
"You only provided %(num)d arguments", 'num')
|
"You only provided %(num)d arguments", 'num')
|
||||||
|
@ -461,6 +471,7 @@ that concatenates its contents *and* converts them to strings only when the
|
||||||
result is included in a string. For example::
|
result is included in a string. For example::
|
||||||
|
|
||||||
from django.utils.translation import string_concat
|
from django.utils.translation import string_concat
|
||||||
|
from django.utils.translation import ugettext_lazy
|
||||||
...
|
...
|
||||||
name = ugettext_lazy('John Lennon')
|
name = ugettext_lazy('John Lennon')
|
||||||
instrument = ugettext_lazy('guitar')
|
instrument = ugettext_lazy('guitar')
|
||||||
|
@ -1663,6 +1674,8 @@ preference available as ``request.LANGUAGE_CODE`` for each
|
||||||
:class:`~django.http.HttpRequest`. Feel free to read this value in your view
|
:class:`~django.http.HttpRequest`. Feel free to read this value in your view
|
||||||
code. Here's a simple example::
|
code. Here's a simple example::
|
||||||
|
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
def hello_world(request, count):
|
def hello_world(request, count):
|
||||||
if request.LANGUAGE_CODE == 'de-at':
|
if request.LANGUAGE_CODE == 'de-at':
|
||||||
return HttpResponse("You prefer to read Austrian German.")
|
return HttpResponse("You prefer to read Austrian German.")
|
||||||
|
|
Loading…
Reference in New Issue