Merge pull request #1162 from sspross/patch-docs

Add needed Imports to the Documentation, Part II
This commit is contained in:
Marc Tamlyn 2013-05-19 05:26:13 -07:00
commit c6855e8a70
14 changed files with 246 additions and 76 deletions

View file

@ -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:
@ -459,6 +471,9 @@ subclass::
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):
@ -634,13 +656,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 +672,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 +711,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 +754,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 +766,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
@ -876,10 +896,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):
@ -1038,6 +1059,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 +1094,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:
@ -1298,6 +1321,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 +1564,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 +1576,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
@ -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.
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 +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
automatically::
from django.contrib import admin
from myapp.models import Friendship
class FriendshipInline(admin.TabularInline):
model = Friendship
fk_name = "to_person"
@ -1712,6 +1746,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 +1758,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 +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
models::
from django.db import models
class Person(models.Model):
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
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)

View file

@ -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):

View file

@ -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):

View file

@ -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()

View file

@ -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

View file

@ -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.
...

View file

@ -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):
# ...

View file

@ -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',