1
0
mirror of https://github.com/django/django.git synced 2025-06-05 11:39:13 +00:00

Refs #30947 -- Changed tuples to lists where appropriate.

This commit is contained in:
Alex Morega 2022-08-26 17:10:27 +03:00 committed by Mariusz Felisiak
parent b3db6c8dcb
commit de6c9c7054
16 changed files with 142 additions and 142 deletions

View File

@ -14,11 +14,11 @@ ADDITION = 1
CHANGE = 2 CHANGE = 2
DELETION = 3 DELETION = 3
ACTION_FLAG_CHOICES = ( ACTION_FLAG_CHOICES = [
(ADDITION, _("Addition")), (ADDITION, _("Addition")),
(CHANGE, _("Change")), (CHANGE, _("Change")),
(DELETION, _("Deletion")), (DELETION, _("Deletion")),
) ]
class LogEntryManager(models.Manager): class LogEntryManager(models.Manager):

View File

@ -204,7 +204,7 @@ object:
class QuestionAdmin(admin.ModelAdmin): class QuestionAdmin(admin.ModelAdmin):
# ... # ...
list_display = ('question_text', 'pub_date') list_display = ['question_text', 'pub_date']
For good measure, let's also include the ``was_published_recently()`` method For good measure, let's also include the ``was_published_recently()`` method
from :doc:`Tutorial 2 </intro/tutorial02>`: from :doc:`Tutorial 2 </intro/tutorial02>`:
@ -214,7 +214,7 @@ from :doc:`Tutorial 2 </intro/tutorial02>`:
class QuestionAdmin(admin.ModelAdmin): class QuestionAdmin(admin.ModelAdmin):
# ... # ...
list_display = ('question_text', 'pub_date', 'was_published_recently') list_display = ['question_text', 'pub_date', 'was_published_recently']
Now the question change list page looks like this: Now the question change list page looks like this:

View File

@ -33,13 +33,13 @@ Each specified field should be either a ``BooleanField``, ``CharField``,
``ManyToManyField``, for example:: ``ManyToManyField``, for example::
class PersonAdmin(admin.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(admin.UserAdmin): class PersonAdmin(admin.UserAdmin):
list_filter = ('company__name',) list_filter = ['company__name']
Using a ``SimpleListFilter`` Using a ``SimpleListFilter``
============================ ============================
@ -70,10 +70,10 @@ and ``parameter_name`` attributes, and override the ``lookups`` and
human-readable name for the option that will appear human-readable name for the option that will appear
in the right sidebar. in the right sidebar.
""" """
return ( return [
('80s', _('in the eighties')), ('80s', _('in the eighties')),
('90s', _('in the nineties')), ('90s', _('in the nineties')),
) ]
def queryset(self, request, queryset): def queryset(self, request, queryset):
""" """
@ -95,7 +95,7 @@ and ``parameter_name`` attributes, and override the ``lookups`` and
) )
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_filter = (DecadeBornListFilter,) list_filter = [DecadeBornListFilter]
.. note:: .. note::
@ -144,9 +144,9 @@ field name and the second element is a class inheriting from
``django.contrib.admin.FieldListFilter``, for example:: ``django.contrib.admin.FieldListFilter``, for example::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_filter = ( list_filter = [
('is_staff', admin.BooleanFieldListFilter), ('is_staff', admin.BooleanFieldListFilter),
) ]
Here the ``is_staff`` field will use the ``BooleanFieldListFilter``. Specifying Here the ``is_staff`` field will use the ``BooleanFieldListFilter``. Specifying
only the field name, fields will automatically use the appropriate filter for only the field name, fields will automatically use the appropriate filter for
@ -159,9 +159,9 @@ You can limit the choices of a related model to the objects involved in
that relation using ``RelatedOnlyFieldListFilter``:: that relation using ``RelatedOnlyFieldListFilter``::
class BookAdmin(admin.ModelAdmin): class BookAdmin(admin.ModelAdmin):
list_filter = ( list_filter = [
('author', admin.RelatedOnlyFieldListFilter), ('author', admin.RelatedOnlyFieldListFilter),
) ]
Assuming ``author`` is a ``ForeignKey`` to a ``User`` model, this will Assuming ``author`` is a ``ForeignKey`` to a ``User`` model, this will
limit the ``list_filter`` choices to the users who have written a book, limit the ``list_filter`` choices to the users who have written a book,
@ -172,9 +172,9 @@ filter on both empty strings and nulls, depending on what the field
allows to store:: allows to store::
class BookAdmin(admin.ModelAdmin): class BookAdmin(admin.ModelAdmin):
list_filter = ( list_filter = [
('title', admin.EmptyFieldListFilter), ('title', admin.EmptyFieldListFilter),
) ]
By defining a filter using the ``__in`` lookup, it is possible to filter for By defining a filter using the ``__in`` lookup, it is possible to filter for
any of a group of values. You need to override the ``expected_parameters`` any of a group of values. You need to override the ``expected_parameters``

View File

@ -249,7 +249,7 @@ subclass::
from django.contrib import admin from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin): class AuthorAdmin(admin.ModelAdmin):
list_display = ('name', 'title', 'view_birth_date') list_display = ['name', 'title', 'view_birth_date']
@admin.display(empty_value='???') @admin.display(empty_value='???')
def view_birth_date(self, obj): def view_birth_date(self, obj):
@ -276,10 +276,10 @@ subclass::
from django.contrib import admin from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin): class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title') fields = ['name', 'title']
class AuthorAdmin(admin.ModelAdmin): class AuthorAdmin(admin.ModelAdmin):
exclude = ('birth_date',) exclude = ['birth_date']
Since the Author model only has three fields, ``name``, ``title``, and Since the Author model only has three fields, ``name``, ``title``, and
``birth_date``, the forms resulting from the above declarations will ``birth_date``, the forms resulting from the above declarations will
@ -294,7 +294,7 @@ subclass::
:class:`django.contrib.flatpages.models.FlatPage` model as follows:: :class:`django.contrib.flatpages.models.FlatPage` model as follows::
class FlatPageAdmin(admin.ModelAdmin): class FlatPageAdmin(admin.ModelAdmin):
fields = ('url', 'title', 'content') fields = ['url', 'title', 'content']
In the above example, only the fields ``url``, ``title`` and ``content`` In the above example, only the fields ``url``, ``title`` and ``content``
will be displayed, sequentially, in the form. ``fields`` can contain will be displayed, sequentially, in the form. ``fields`` can contain
@ -314,7 +314,7 @@ subclass::
own line:: own line::
class FlatPageAdmin(admin.ModelAdmin): class FlatPageAdmin(admin.ModelAdmin):
fields = (('url', 'title'), 'content') fields = [('url', 'title'), 'content']
.. admonition:: Note .. admonition:: Note
@ -346,15 +346,15 @@ subclass::
from django.contrib import admin from django.contrib import admin
class FlatPageAdmin(admin.ModelAdmin): class FlatPageAdmin(admin.ModelAdmin):
fieldsets = ( fieldsets = [
(None, { (None, {
'fields': ('url', 'title', 'content', 'sites') 'fields': ['url', 'title', 'content', 'sites'],
}), }),
('Advanced options', { ('Advanced options', {
'classes': ('collapse',), 'classes': ['collapse'],
'fields': ('registration_required', 'template_name'), 'fields': ['registration_required', 'template_name'],
}), }),
) ]
This results in an admin page that looks like: This results in an admin page that looks like:
@ -368,13 +368,13 @@ subclass::
The ``field_options`` dictionary can have the following keys: The ``field_options`` dictionary can have the following keys:
* ``fields`` * ``fields``
A tuple of field names to display in this fieldset. This key is A list or tuple of field names to display in this fieldset. This key is
required. required.
Example:: Example::
{ {
'fields': ('first_name', 'last_name', 'address', 'city', 'state'), 'fields': ['first_name', 'last_name', 'address', 'city', 'state'],
} }
As with the :attr:`~ModelAdmin.fields` option, to display multiple As with the :attr:`~ModelAdmin.fields` option, to display multiple
@ -383,7 +383,7 @@ subclass::
the same line:: the same line::
{ {
'fields': (('first_name', 'last_name'), 'address', 'city', 'state'), 'fields': [('first_name', 'last_name'), 'address', 'city', 'state'],
} }
``fields`` can contain values defined in ``fields`` can contain values defined in
@ -399,7 +399,7 @@ subclass::
Example:: Example::
{ {
'classes': ('wide', 'extrapretty'), 'classes': ['wide', 'extrapretty'],
} }
Two useful classes defined by the default admin site stylesheet are Two useful classes defined by the default admin site stylesheet are
@ -540,7 +540,7 @@ subclass::
Example:: Example::
list_display = ('first_name', 'last_name') list_display = ['first_name', 'last_name']
If you don't set ``list_display``, the admin site will display a single If you don't set ``list_display``, the admin site will display a single
column that displays the ``__str__()`` representation of each object. column that displays the ``__str__()`` representation of each object.
@ -552,7 +552,7 @@ subclass::
* The name of a model field. For example:: * The name of a model field. For example::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name') list_display = ['first_name', 'last_name']
* A callable that accepts one argument, the model instance. For example:: * A callable that accepts one argument, the model instance. For example::
@ -561,13 +561,13 @@ subclass::
return ("%s %s" % (obj.first_name, obj.last_name)).upper() return ("%s %s" % (obj.first_name, obj.last_name)).upper()
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = (upper_case_name,) list_display = [upper_case_name]
* A string representing a ``ModelAdmin`` method that accepts one argument, * A string representing a ``ModelAdmin`` method that accepts one argument,
the model instance. For example:: the model instance. For example::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('upper_case_name',) list_display = ['upper_case_name']
@admin.display(description='Name') @admin.display(description='Name')
def upper_case_name(self, obj): def upper_case_name(self, obj):
@ -588,7 +588,7 @@ subclass::
return '%ds' % (self.birthday.year // 10 * 10) return '%ds' % (self.birthday.year // 10 * 10)
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'decade_born_in') list_display = ['name', 'decade_born_in']
A few special cases to note about ``list_display``: A few special cases to note about ``list_display``:
@ -630,7 +630,7 @@ subclass::
) )
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'colored_name') list_display = ['first_name', 'last_name', 'colored_name']
* As some examples have already demonstrated, when using a callable, a * As some examples have already demonstrated, when using a callable, a
model method, or a ``ModelAdmin`` method, you can customize the column's model method, or a ``ModelAdmin`` method, you can customize the column's
@ -654,7 +654,7 @@ subclass::
Or on a field level:: Or on a field level::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'birth_date_view') list_display = ['name', 'birth_date_view']
@admin.display(empty_value='unknown') @admin.display(empty_value='unknown')
def birth_date_view(self, obj): def birth_date_view(self, obj):
@ -678,12 +678,12 @@ subclass::
return 1950 <= self.birthday.year < 1960 return 1950 <= self.birthday.year < 1960
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'born_in_fifties') list_display = ['name', 'born_in_fifties']
* The ``__str__()`` method is just as valid in ``list_display`` as any * The ``__str__()`` method is just as valid in ``list_display`` as any
other model method, so it's perfectly OK to do this:: other model method, so it's perfectly OK to do this::
list_display = ('__str__', 'some_other_field') list_display = ['__str__', 'some_other_field']
* Usually, elements of ``list_display`` that aren't actual database * Usually, elements of ``list_display`` that aren't actual database
fields can't be used in sorting (because Django does all the sorting fields can't be used in sorting (because Django does all the sorting
@ -711,7 +711,7 @@ subclass::
) )
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'colored_first_name') list_display = ['first_name', 'colored_first_name']
The above will tell Django to order by the ``first_name`` field when The above will tell Django to order by the ``first_name`` field when
trying to sort by ``colored_first_name`` in the admin. trying to sort by ``colored_first_name`` in the admin.
@ -731,7 +731,7 @@ subclass::
author = models.ForeignKey(Person, on_delete=models.CASCADE) author = models.ForeignKey(Person, on_delete=models.CASCADE)
class BlogAdmin(admin.ModelAdmin): class BlogAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'author_first_name') list_display = ['title', 'author', 'author_first_name']
@admin.display(ordering='author__first_name') @admin.display(ordering='author__first_name')
def author_first_name(self, obj): def author_first_name(self, obj):
@ -766,7 +766,7 @@ subclass::
return self.first_name + ' ' + self.last_name return self.first_name + ' ' + self.last_name
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('full_name',) list_display = ['full_name']
Note that ``@property`` must be above ``@display``. If you're using the Note that ``@property`` must be above ``@display``. If you're using the
old way -- setting the display-related attributes directly rather than old way -- setting the display-related attributes directly rather than
@ -819,13 +819,13 @@ subclass::
linked on the change list page:: linked on the change list page::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'birthday') list_display = ['first_name', 'last_name', 'birthday']
list_display_links = ('first_name', 'last_name') list_display_links = ['first_name', 'last_name']
In this example, the change list page grid will have no links:: In this example, the change list page grid will have no links::
class AuditEntryAdmin(admin.ModelAdmin): class AuditEntryAdmin(admin.ModelAdmin):
list_display = ('timestamp', 'message') list_display = ['timestamp', 'message']
list_display_links = None list_display_links = None
.. _admin-list-editable: .. _admin-list-editable:
@ -892,7 +892,7 @@ subclass::
``select_related`` as parameters. For example:: ``select_related`` as parameters. For example::
class ArticleAdmin(admin.ModelAdmin): class ArticleAdmin(admin.ModelAdmin):
list_select_related = ('author', 'category') list_select_related = ['author', 'category']
will call ``select_related('author', 'category')``. will call ``select_related('author', 'category')``.
@ -942,7 +942,7 @@ subclass::
fields it should prepopulate from:: fields it should prepopulate from::
class ArticleAdmin(admin.ModelAdmin): class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)} prepopulated_fields = {"slug": ["title"]}
When set, the given fields will use a bit of JavaScript to populate from When set, the given fields will use a bit of JavaScript to populate from
the fields assigned. The main use for this functionality is to the fields assigned. The main use for this functionality is to
@ -1045,7 +1045,7 @@ subclass::
``ManyToManyField``:: ``ManyToManyField``::
class ArticleAdmin(admin.ModelAdmin): class ArticleAdmin(admin.ModelAdmin):
raw_id_fields = ("newspaper",) raw_id_fields = ["newspaper"]
The ``raw_id_fields`` ``Input`` widget should contain a primary key if the The ``raw_id_fields`` ``Input`` widget should contain a primary key if the
field is a ``ForeignKey`` or a comma separated list of values if the field field is a ``ForeignKey`` or a comma separated list of values if the field
@ -1081,7 +1081,7 @@ subclass::
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
readonly_fields = ('address_report',) readonly_fields = ['address_report']
# description functions like a model field's verbose_name # description functions like a model field's verbose_name
@admin.display(description='Address') @admin.display(description='Address')
@ -1397,8 +1397,8 @@ templates used by the :class:`ModelAdmin` views:
For example, to search by ``name`` and ``age``, you could use:: For example, to search by ``name`` and ``age``, you could use::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'age') list_display = ['name', 'age']
search_fields = ('name',) search_fields = ['name']
def get_search_results(self, request, queryset, search_term): def get_search_results(self, request, queryset, search_term):
queryset, may_have_duplicates = super().get_search_results( queryset, may_have_duplicates = super().get_search_results(
@ -1543,7 +1543,7 @@ templates used by the :class:`ModelAdmin` views:
filtering based on add, change, delete, and view permissions:: filtering based on add, change, delete, and view permissions::
class MyModelAdmin(admin.ModelAdmin): class MyModelAdmin(admin.ModelAdmin):
inlines = (MyInline,) inlines = [MyInline]
def get_inline_instances(self, request, obj=None): def get_inline_instances(self, request, obj=None):
return [inline(self.model, self.admin_site) for inline in self.inlines] return [inline(self.model, self.admin_site) for inline in self.inlines]
@ -1736,12 +1736,12 @@ templates used by the :class:`ModelAdmin` views:
class MyModelAdmin(admin.ModelAdmin): class MyModelAdmin(admin.ModelAdmin):
def formfield_for_choice_field(self, db_field, request, **kwargs): def formfield_for_choice_field(self, db_field, request, **kwargs):
if db_field.name == "status": if db_field.name == "status":
kwargs['choices'] = ( kwargs['choices'] = [
('accepted', 'Accepted'), ('accepted', 'Accepted'),
('denied', 'Denied'), ('denied', 'Denied'),
) ]
if request.user.is_superuser: if request.user.is_superuser:
kwargs['choices'] += (('ready', 'Ready for deployment'),) kwargs['choices'].append(('ready', 'Ready for deployment'))
return super().formfield_for_choice_field(db_field, request, **kwargs) return super().formfield_for_choice_field(db_field, request, **kwargs)
.. admonition:: Note .. admonition:: Note
@ -2063,9 +2063,9 @@ on your ``ModelAdmin``::
class ArticleAdmin(admin.ModelAdmin): class ArticleAdmin(admin.ModelAdmin):
class Media: class Media:
css = { css = {
"all": ("my_styles.css",) "all": ["my_styles.css"],
} }
js = ("my_code.js",) js = ["my_code.js"]
The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
:setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
@ -2283,7 +2283,7 @@ The ``InlineModelAdmin`` class adds or customizes:
class BookInline(admin.TabularInline): class BookInline(admin.TabularInline):
model = Book model = Book
raw_id_fields = ("pages",) raw_id_fields = ["pages"]
.. attribute:: InlineModelAdmin.template .. attribute:: InlineModelAdmin.template
@ -2451,7 +2451,7 @@ so by defining an ``InlineModelAdmin`` object for the relationship::
inlines = [ inlines = [
MembershipInline, MembershipInline,
] ]
exclude = ('members',) exclude = ['members']
There are two features worth noting in this example. There are two features worth noting in this example.
@ -2518,10 +2518,10 @@ customized using any of the options available to ``InlineModelAdmin`` classes.
Now create admin views for the ``Person`` and ``Group`` models:: Now create admin views for the ``Person`` and ``Group`` models::
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
inlines = (MembershipInline,) inlines = [MembershipInline]
class GroupAdmin(admin.ModelAdmin): class GroupAdmin(admin.ModelAdmin):
inlines = (MembershipInline,) inlines = [MembershipInline]
Finally, register your ``Person`` and ``Group`` models with the admin site:: Finally, register your ``Person`` and ``Group`` models with the admin site::

View File

@ -185,17 +185,17 @@ registering a custom ``ModelAdmin`` for ``FlatPage``::
# Define a new FlatPageAdmin # Define a new FlatPageAdmin
class FlatPageAdmin(FlatPageAdmin): class FlatPageAdmin(FlatPageAdmin):
fieldsets = ( fieldsets = [
(None, {'fields': ('url', 'title', 'content', 'sites')}), (None, {'fields': ['url', 'title', 'content', 'sites']}),
(_('Advanced options'), { (_('Advanced options'), {
'classes': ('collapse',), 'classes': ['collapse'],
'fields': ( 'fields': [
'enable_comments', 'enable_comments',
'registration_required', 'registration_required',
'template_name', 'template_name',
), ],
}), }),
) ]
# Re-register FlatPageAdmin # Re-register FlatPageAdmin
admin.site.unregister(FlatPage) admin.site.unregister(FlatPage)

View File

@ -42,7 +42,7 @@ Example::
serialize('geojson', City.objects.all(), serialize('geojson', City.objects.all(),
geometry_field='point', geometry_field='point',
fields=('name',)) fields=['name'])
Would output:: Would output::

View File

@ -248,10 +248,10 @@ current/rangetypes.html#RANGETYPES-INCLUSIVITY>`_. For example::
constraints = [ constraints = [
ExclusionConstraint( ExclusionConstraint(
name='exclude_overlapping_reservations', name='exclude_overlapping_reservations',
expressions=( expressions=[
(TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS), (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS),
('room', RangeOperators.EQUAL), ('room', RangeOperators.EQUAL),
), ],
condition=Q(cancelled=False), condition=Q(cancelled=False),
), ),
] ]

View File

@ -556,7 +556,7 @@ This example illustrates all possible attributes and methods for a
Returns the feed's categories as iterable over strings. Returns the feed's categories as iterable over strings.
""" """
categories = ("python", "django") # Hard-coded list of categories. categories = ["python", "django"] # Hard-coded list of categories.
# COPYRIGHT NOTICE -- One of the following three is optional. The # COPYRIGHT NOTICE -- One of the following three is optional. The
# framework looks for them in this order. # framework looks for them in this order.
@ -604,7 +604,7 @@ This example illustrates all possible attributes and methods for a
Returns a list of items to publish in this feed. Returns a list of items to publish in this feed.
""" """
items = ('Item 1', 'Item 2') # Hard-coded items. items = ['Item 1', 'Item 2'] # Hard-coded items.
# GET_OBJECT -- This is required for feeds that publish different data # GET_OBJECT -- This is required for feeds that publish different data
# for different URL parameters. (See "A complex example" above.) # for different URL parameters. (See "A complex example" above.)
@ -870,7 +870,7 @@ This example illustrates all possible attributes and methods for a
Returns the categories for every item in the feed. Returns the categories for every item in the feed.
""" """
item_categories = ("python", "django") # Hard-coded categories. item_categories = ["python", "django"] # Hard-coded categories.
# ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the
# following three is optional. The framework looks for them in this # following three is optional. The framework looks for them in this

View File

@ -833,11 +833,11 @@ For example::
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
SHIRT_SIZES = ( SHIRT_SIZES = [
('S', 'Small'), ('S', 'Small'),
('M', 'Medium'), ('M', 'Medium'),
('L', 'Large'), ('L', 'Large'),
) ]
name = models.CharField(max_length=60) name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES) shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)

View File

@ -349,7 +349,7 @@ add it to a ``UserAdmin`` class which is registered with the
# Define a new User admin # Define a new User admin
class UserAdmin(BaseUserAdmin): class UserAdmin(BaseUserAdmin):
inlines = (EmployeeInline,) inlines = [EmployeeInline]
# Re-register UserAdmin # Re-register UserAdmin
admin.site.unregister(User) admin.site.unregister(User)
@ -894,10 +894,10 @@ custom user class.
class CustomUserAdmin(UserAdmin): class CustomUserAdmin(UserAdmin):
... ...
fieldsets = UserAdmin.fieldsets + ( fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('custom_field',)}), (None, {'fields': ['custom_field']}),
) )
add_fieldsets = UserAdmin.add_fieldsets + ( add_fieldsets = UserAdmin.add_fieldsets + (
(None, {'fields': ('custom_field',)}), (None, {'fields': ['custom_field']}),
) )
See :ref:`a full example <custom-users-admin-full-example>` for more See :ref:`a full example <custom-users-admin-full-example>` for more
@ -1105,7 +1105,7 @@ code would be required in the app's ``admin.py`` file::
class Meta: class Meta:
model = MyUser model = MyUser
fields = ('email', 'date_of_birth') fields = ['email', 'date_of_birth']
def clean_password2(self): def clean_password2(self):
# Check that the two password entries match # Check that the two password entries match
@ -1133,7 +1133,7 @@ code would be required in the app's ``admin.py`` file::
class Meta: class Meta:
model = MyUser model = MyUser
fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin') fields = ['email', 'password', 'date_of_birth', 'is_active', 'is_admin']
class UserAdmin(BaseUserAdmin): class UserAdmin(BaseUserAdmin):
@ -1144,24 +1144,24 @@ code would be required in the app's ``admin.py`` file::
# The fields to be used in displaying the User model. # The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin # These override the definitions on the base UserAdmin
# that reference specific fields on auth.User. # that reference specific fields on auth.User.
list_display = ('email', 'date_of_birth', 'is_admin') list_display = ['email', 'date_of_birth', 'is_admin']
list_filter = ('is_admin',) list_filter = ['is_admin']
fieldsets = ( fieldsets = [
(None, {'fields': ('email', 'password')}), (None, {'fields': ['email', 'password']}),
('Personal info', {'fields': ('date_of_birth',)}), ('Personal info', {'fields': ['date_of_birth']}),
('Permissions', {'fields': ('is_admin',)}), ('Permissions', {'fields': ['is_admin']}),
) ]
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user. # overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = ( add_fieldsets = [
(None, { (None, {
'classes': ('wide',), 'classes': ['wide'],
'fields': ('email', 'date_of_birth', 'password1', 'password2'), 'fields': ['email', 'date_of_birth', 'password1', 'password2'],
}), }),
) ]
search_fields = ('email',) search_fields = ['email']
ordering = ('email',) ordering = ['email']
filter_horizontal = () filter_horizontal = []
# Now register the new UserAdmin... # Now register the new UserAdmin...

View File

@ -781,7 +781,7 @@ To apply permission checks to :doc:`class-based views
class MyView(PermissionRequiredMixin, View): class MyView(PermissionRequiredMixin, View):
permission_required = 'polls.add_choice' permission_required = 'polls.add_choice'
# Or multiple of permissions: # Or multiple of permissions:
permission_required = ('polls.view_choice', 'polls.change_choice') permission_required = ['polls.view_choice', 'polls.change_choice']
You can set any of the parameters of You can set any of the parameters of
:class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling

View File

@ -181,11 +181,11 @@ ones:
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
SHIRT_SIZES = ( SHIRT_SIZES = [
('S', 'Small'), ('S', 'Small'),
('M', 'Medium'), ('M', 'Medium'),
('L', 'Large'), ('L', 'Large'),
) ]
name = models.CharField(max_length=60) name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES) shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)

View File

@ -56,9 +56,9 @@ Here's an example::
class CalendarWidget(forms.TextInput): class CalendarWidget(forms.TextInput):
class Media: class Media:
css = { css = {
'all': ('pretty.css',) 'all': ['pretty.css'],
} }
js = ('animations.js', 'actions.js') js = ['animations.js', 'actions.js']
This code defines a ``CalendarWidget``, which will be based on ``TextInput``. This code defines a ``CalendarWidget``, which will be based on ``TextInput``.
Every time the CalendarWidget is used on a form, that form will be directed Every time the CalendarWidget is used on a form, that form will be directed
@ -96,8 +96,8 @@ provide two CSS options -- one for the screen, and one for print::
class Media: class Media:
css = { css = {
'screen': ('pretty.css',), 'screen': ['pretty.css'],
'print': ('newspaper.css',) 'print': ['newspaper.css'],
} }
If a group of CSS files are appropriate for multiple output media types, If a group of CSS files are appropriate for multiple output media types,
@ -107,9 +107,9 @@ requirements::
class Media: class Media:
css = { css = {
'screen': ('pretty.css',), 'screen': ['pretty.css'],
'tv,projector': ('lo_res.css',), 'tv,projector': ['lo_res.css'],
'print': ('newspaper.css',) 'print': ['newspaper.css],
} }
If this last CSS definition were to be rendered, it would become the following HTML:: If this last CSS definition were to be rendered, it would become the following HTML::
@ -144,9 +144,9 @@ example above::
>>> class FancyCalendarWidget(CalendarWidget): >>> class FancyCalendarWidget(CalendarWidget):
... class Media: ... class Media:
... css = { ... css = {
... 'all': ('fancy.css',) ... 'all': ['fancy.css'],
... } ... }
... js = ('whizbang.js',) ... js = ['whizbang.js']
>>> w = FancyCalendarWidget() >>> w = FancyCalendarWidget()
>>> print(w.media) >>> print(w.media)
@ -164,9 +164,9 @@ an ``extend=False`` declaration to the ``Media`` declaration::
... class Media: ... class Media:
... extend = False ... extend = False
... css = { ... css = {
... 'all': ('fancy.css',) ... 'all': ['fancy.css'],
... } ... }
... js = ('whizbang.js',) ... js = ['whizbang.js']
>>> w = FancyCalendarWidget() >>> w = FancyCalendarWidget()
>>> print(w.media) >>> print(w.media)
@ -195,8 +195,8 @@ be defined in a dynamic fashion::
class CalendarWidget(forms.TextInput): class CalendarWidget(forms.TextInput):
@property @property
def media(self): def media(self):
return forms.Media(css={'all': ('pretty.css',)}, return forms.Media(css={'all': ['pretty.css']},
js=('animations.js', 'actions.js')) js=['animations.js', 'actions.js'])
See the section on `Media objects`_ for more details on how to construct See the section on `Media objects`_ for more details on how to construct
return values for dynamic ``media`` properties. return values for dynamic ``media`` properties.
@ -230,9 +230,9 @@ was ``None``::
>>> class CalendarWidget(forms.TextInput): >>> class CalendarWidget(forms.TextInput):
... class Media: ... class Media:
... css = { ... css = {
... 'all': ('/css/pretty.css',), ... 'all': ['/css/pretty.css'],
... } ... }
... js = ('animations.js', 'http://othersite.com/actions.js') ... js = ['animations.js', 'http://othersite.com/actions.js']
>>> w = CalendarWidget() >>> w = CalendarWidget()
>>> print(w.media) >>> print(w.media)
@ -277,7 +277,7 @@ outputting the complete HTML ``<script>`` or ``<link>`` tag content::
>>> class SomeWidget(forms.TextInput): >>> class SomeWidget(forms.TextInput):
... class Media: ... class Media:
... js = (JSPath(),) ... js = [JSPath()]
``Media`` objects ``Media`` objects
================= =================
@ -319,13 +319,13 @@ specified by both::
>>> class CalendarWidget(forms.TextInput): >>> class CalendarWidget(forms.TextInput):
... class Media: ... class Media:
... css = { ... css = {
... 'all': ('pretty.css',) ... 'all': ['pretty.css'],
... } ... }
... js = ('animations.js', 'actions.js') ... js = ['animations.js', 'actions.js']
>>> class OtherWidget(forms.TextInput): >>> class OtherWidget(forms.TextInput):
... class Media: ... class Media:
... js = ('whizbang.js',) ... js = ['whizbang.js']
>>> w1 = CalendarWidget() >>> w1 = CalendarWidget()
>>> w2 = OtherWidget() >>> w2 = OtherWidget()
@ -350,10 +350,10 @@ For example::
>>> from django import forms >>> from django import forms
>>> class CalendarWidget(forms.TextInput): >>> class CalendarWidget(forms.TextInput):
... class Media: ... class Media:
... js = ('jQuery.js', 'calendar.js', 'noConflict.js') ... js = ['jQuery.js', 'calendar.js', 'noConflict.js']
>>> class TimeWidget(forms.TextInput): >>> class TimeWidget(forms.TextInput):
... class Media: ... class Media:
... js = ('jQuery.js', 'time.js', 'noConflict.js') ... js = ['jQuery.js', 'time.js', 'noConflict.js']
>>> w1 = CalendarWidget() >>> w1 = CalendarWidget()
>>> w2 = TimeWidget() >>> w2 = TimeWidget()
>>> print(w1.media + w2.media) >>> print(w1.media + w2.media)
@ -400,7 +400,7 @@ CSS for form layout -- add a ``Media`` declaration to the form::
... ...
... class Media: ... class Media:
... css = { ... css = {
... 'all': ('layout.css',) ... 'all': ['layout.css'],
... } ... }
>>> f = ContactForm() >>> f = ContactForm()

View File

@ -514,7 +514,7 @@ For example, if you want the ``CharField`` for the ``name`` attribute of
class AuthorForm(ModelForm): class AuthorForm(ModelForm):
class Meta: class Meta:
model = Author model = Author
fields = ('name', 'title', 'birth_date') fields = ['name', 'title', 'birth_date']
widgets = { widgets = {
'name': Textarea(attrs={'cols': 80, 'rows': 20}), 'name': Textarea(attrs={'cols': 80, 'rows': 20}),
} }
@ -535,7 +535,7 @@ the ``name`` field::
class AuthorForm(ModelForm): class AuthorForm(ModelForm):
class Meta: class Meta:
model = Author model = Author
fields = ('name', 'title', 'birth_date') fields = ['name', 'title', 'birth_date']
labels = { labels = {
'name': _('Writer'), 'name': _('Writer'),
} }
@ -669,7 +669,7 @@ attribute on the ``Meta`` class.
>>> class AuthorForm(ModelForm): >>> class AuthorForm(ModelForm):
... class Meta: ... class Meta:
... model = Author ... model = Author
... localized_fields = ('birth_date',) ... localized_fields = ['birth_date']
If ``localized_fields`` is set to the special value ``'__all__'``, all fields If ``localized_fields`` is set to the special value ``'__all__'``, all fields
will be localized. will be localized.
@ -694,7 +694,7 @@ the ``Meta.fields`` or ``Meta.exclude`` lists::
>>> class RestrictedArticleForm(EnhancedArticleForm): >>> class RestrictedArticleForm(EnhancedArticleForm):
... class Meta(ArticleForm.Meta): ... class Meta(ArticleForm.Meta):
... exclude = ('body',) ... exclude = ['body']
This adds the extra method from the ``EnhancedArticleForm`` and modifies This adds the extra method from the ``EnhancedArticleForm`` and modifies
the original ``ArticleForm.Meta`` to remove one field. the original ``ArticleForm.Meta`` to remove one field.
@ -746,7 +746,7 @@ to make::
>>> from django.forms import modelform_factory >>> from django.forms import modelform_factory
>>> from myapp.models import Book >>> 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 modifications to existing forms, for example by This can also be used to make modifications to existing forms, for example by
specifying the widgets to be used for a given field:: specifying the widgets to be used for a given field::
@ -762,7 +762,7 @@ documentation.
... or enable localization for specific fields:: ... or enable localization for specific fields::
>>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=("birth_date",)) >>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=["birth_date"])
.. _model-formsets: .. _model-formsets:
@ -777,13 +777,13 @@ convenient. Let's reuse the ``Author`` model from above::
>>> from django.forms import modelformset_factory >>> from django.forms import modelformset_factory
>>> from myapp.models import Author >>> from myapp.models import Author
>>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title')) >>> AuthorFormSet = modelformset_factory(Author, fields=['name', 'title'])
Using ``fields`` restricts the formset to use only the given fields. Using ``fields`` restricts the formset to use only the given fields.
Alternatively, you can take an "opt-out" approach, specifying which fields to Alternatively, you can take an "opt-out" approach, specifying which fields to
exclude:: exclude::
>>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',)) >>> AuthorFormSet = modelformset_factory(Author, exclude=['birth_date'])
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
with the ``Author`` model. It works just like a regular formset:: with the ``Author`` model. It works just like a regular formset::
@ -836,7 +836,7 @@ Alternatively, you can create a subclass that sets ``self.queryset`` in
Then, pass your ``BaseAuthorFormSet`` class to the factory function:: Then, pass your ``BaseAuthorFormSet`` class to the factory function::
>>> AuthorFormSet = modelformset_factory( >>> AuthorFormSet = modelformset_factory(
... Author, fields=('name', 'title'), formset=BaseAuthorFormSet) ... Author, fields=['name', 'title'], formset=BaseAuthorFormSet)
If you want to return a formset that doesn't include *any* preexisting If you want to return a formset that doesn't include *any* preexisting
instances of the model, you can specify an empty QuerySet:: instances of the model, you can specify an empty QuerySet::
@ -854,7 +854,7 @@ you can create a custom model form that has custom validation::
class AuthorForm(forms.ModelForm): class AuthorForm(forms.ModelForm):
class Meta: class Meta:
model = Author model = Author
fields = ('name', 'title') fields = ['name', 'title']
def clean_name(self): def clean_name(self):
# custom validation for the name field # custom validation for the name field
@ -877,7 +877,7 @@ works the same way as the ``widgets`` dictionary on the inner ``Meta``
class of a ``ModelForm`` works:: class of a ``ModelForm`` works::
>>> AuthorFormSet = modelformset_factory( >>> AuthorFormSet = modelformset_factory(
... Author, fields=('name', 'title'), ... Author, fields=['name', 'title'],
... widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})}) ... widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})})
Enabling localization for fields with ``localized_fields`` Enabling localization for fields with ``localized_fields``
@ -887,8 +887,8 @@ Using the ``localized_fields`` parameter, you can enable localization for
fields in the form. fields in the form.
>>> AuthorFormSet = modelformset_factory( >>> AuthorFormSet = modelformset_factory(
... Author, fields=('name', 'title', 'birth_date'), ... Author, fields=['name', 'title', 'birth_date'],
... localized_fields=('birth_date',)) ... localized_fields=['birth_date'])
If ``localized_fields`` is set to the special value ``'__all__'``, all fields If ``localized_fields`` is set to the special value ``'__all__'``, all fields
will be localized. will be localized.
@ -964,7 +964,7 @@ extra forms displayed.
>>> Author.objects.order_by('name') >>> Author.objects.order_by('name')
<QuerySet [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]> <QuerySet [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]>
>>> AuthorFormSet = modelformset_factory(Author, fields=('name',), max_num=1) >>> AuthorFormSet = modelformset_factory(Author, fields=['name'], max_num=1)
>>> formset = AuthorFormSet(queryset=Author.objects.order_by('name')) >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
>>> [x.name for x in formset.get_queryset()] >>> [x.name for x in formset.get_queryset()]
['Charles Baudelaire', 'Paul Verlaine', 'Walt Whitman'] ['Charles Baudelaire', 'Paul Verlaine', 'Walt Whitman']
@ -978,7 +978,7 @@ If the value of ``max_num`` is greater than the number of existing related
objects, up to ``extra`` additional blank forms will be added to the formset, objects, up to ``extra`` additional blank forms will be added to the formset,
so long as the total number of forms does not exceed ``max_num``:: so long as the total number of forms does not exceed ``max_num``::
>>> AuthorFormSet = modelformset_factory(Author, fields=('name',), max_num=4, extra=2) >>> AuthorFormSet = modelformset_factory(Author, fields=['name'], max_num=4, extra=2)
>>> formset = AuthorFormSet(queryset=Author.objects.order_by('name')) >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
>>> for form in formset: >>> for form in formset:
... print(form.as_table()) ... print(form.as_table())
@ -1002,7 +1002,7 @@ objects::
>>> AuthorFormSet = modelformset_factory( >>> AuthorFormSet = modelformset_factory(
... Author, ... Author,
... fields=('name', 'title'), ... fields=['name', 'title'],
... edit_only=True, ... edit_only=True,
... ) ... )
@ -1020,7 +1020,7 @@ formset to edit ``Author`` model instances::
from myapp.models import Author from myapp.models import Author
def manage_authors(request): def manage_authors(request):
AuthorFormSet = modelformset_factory(Author, fields=('name', 'title')) AuthorFormSet = modelformset_factory(Author, fields=['name', 'title'])
if request.method == 'POST': if request.method == 'POST':
formset = AuthorFormSet(request.POST, request.FILES) formset = AuthorFormSet(request.POST, request.FILES)
if formset.is_valid(): if formset.is_valid():
@ -1086,7 +1086,7 @@ formset::
from myapp.models import Author from myapp.models import Author
def manage_authors(request): def manage_authors(request):
AuthorFormSet = modelformset_factory(Author, fields=('name', 'title')) AuthorFormSet = modelformset_factory(Author, fields=['name', 'title'])
queryset = Author.objects.filter(name__startswith='O') queryset = Author.objects.filter(name__startswith='O')
if request.method == "POST": if request.method == "POST":
formset = AuthorFormSet( formset = AuthorFormSet(
@ -1187,7 +1187,7 @@ If you want to create a formset that allows you to edit books belonging to
a particular author, you could do this:: a particular author, you could do this::
>>> from django.forms import inlineformset_factory >>> from django.forms import inlineformset_factory
>>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',)) >>> BookFormSet = inlineformset_factory(Author, Book, fields=['title'])
>>> author = Author.objects.get(name='Mike Royko') >>> author = Author.objects.get(name='Mike Royko')
>>> formset = BookFormSet(instance=author) >>> formset = BookFormSet(instance=author)
@ -1230,7 +1230,7 @@ Then when you create your inline formset, pass in the optional argument
``formset``:: ``formset``::
>>> from django.forms import inlineformset_factory >>> from django.forms import inlineformset_factory
>>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',), >>> BookFormSet = inlineformset_factory(Author, Book, fields=['title'],
... formset=CustomInlineFormSet) ... formset=CustomInlineFormSet)
>>> author = Author.objects.get(name='Mike Royko') >>> author = Author.objects.get(name='Mike Royko')
>>> formset = BookFormSet(instance=author) >>> formset = BookFormSet(instance=author)
@ -1259,7 +1259,7 @@ To resolve this, you can use ``fk_name`` to
:func:`~django.forms.models.inlineformset_factory`:: :func:`~django.forms.models.inlineformset_factory`::
>>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name='from_friend', >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name='from_friend',
... fields=('to_friend', 'length_in_months')) ... fields=['to_friend', 'length_in_months'])
Using an inline formset in a view Using an inline formset in a view
--------------------------------- ---------------------------------
@ -1269,7 +1269,7 @@ of a model. Here's how you can do that::
def manage_books(request, author_id): def manage_books(request, author_id):
author = Author.objects.get(pk=author_id) author = Author.objects.get(pk=author_id)
BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',)) BookInlineFormSet = inlineformset_factory(Author, Book, fields=['title'])
if request.method == "POST": if request.method == "POST":
formset = BookInlineFormSet(request.POST, request.FILES, instance=author) formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid(): if formset.is_valid():

View File

@ -56,7 +56,7 @@ If you only want a subset of fields to be serialized, you can
specify a ``fields`` argument to the serializer:: specify a ``fields`` argument to the serializer::
from django.core import serializers from django.core import serializers
data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size')) data = serializers.serialize('xml', SomeModel.objects.all(), fields=['name','size'])
In this example, only the ``name`` and ``size`` attributes of each model will In this example, only the ``name`` and ``size`` attributes of each model will
be serialized. The primary key is always serialized as the ``pk`` element in the be serialized. The primary key is always serialized as the ``pk`` element in the

View File

@ -237,7 +237,7 @@ Use the ``django.test.Client`` class to make requests.
list or tuple for the required key. For example, this value of ``data`` list or tuple for the required key. For example, this value of ``data``
would submit three selected values for the field named ``choices``:: would submit three selected values for the field named ``choices``::
{'choices': ('a', 'b', 'd')} {'choices': ['a', 'b', 'd']}
Submitting files is a special case. To POST a file, you need only Submitting files is a special case. To POST a file, you need only
provide the file field name as a key, and a file handle to the file you provide the file field name as a key, and a file handle to the file you