Django

Code

Show
Ignore:
Timestamp:
07/19/08 08:30:47 (6 months ago)
Author:
jbronn
Message:

gis: Merged revisions 7921,7926-7928,7938-7941,7945-7947,7949-7950,7952,7955-7956,7961,7964-7968,7970-7978 via svnmerge from trunk.

This includes the newforms-admin branch, and thus is backwards-incompatible. The geographic admin is _not_ in this changeset, and is forthcoming.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/gis

    • Property svnmerge-integrated changed from /django/trunk:1-7917 to /django/trunk:1-7978
  • django/branches/gis/docs/authentication.txt

    r7642 r7979  
    517517template context variables: 
    518518 
    519     * ``form``: A ``FormWrapper`` object representing the login form. See the 
    520       `forms documentation`_ for more on ``FormWrapper`` objects. 
     519    * ``form``: A ``Form`` object representing the login form. See the 
     520      `newforms documentation`_ for more on ``Form`` objects. 
    521521    * ``next``: The URL to redirect to after successful login. This may contain 
    522522      a query string, too. 
     
    542542    {% block content %} 
    543543 
    544     {% if form.has_errors %} 
     544    {% if form.errors %} 
    545545    <p>Your username and password didn't match. Please try again.</p> 
    546546    {% endif %} 
     
    548548    <form method="post" action="."> 
    549549    <table> 
    550     <tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr> 
    551     <tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr> 
     550    <tr><td>{{ form.username.label_tag }}</td><td>{{ form.username }}</td></tr> 
     551    <tr><td>{{ form.password.label_tag }}</td><td>{{ form.password }}</td></tr> 
    552552    </table> 
    553553 
     
    558558    {% endblock %} 
    559559 
    560 .. _forms documentation: ../forms/ 
     560.. _newforms documentation: ../newforms/ 
    561561.. _site framework docs: ../sites/ 
    562562 
     
    678678      will default to ``settings.LOGIN_URL`` if not supplied. 
    679679 
    680 Built-in manipulators 
    681 --------------------- 
     680Built-in forms 
     681-------------- 
     682 
     683**New in Django development version.** 
    682684 
    683685If you don't want to use the built-in views, but want the convenience 
    684 of not having to write manipulators for this functionality, the 
    685 authentication system provides several built-in manipulators: 
    686  
    687     * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A 
    688       manipulator used in the admin interface to change a user's 
    689       password. 
    690  
    691     * ``django.contrib.auth.forms.AuthenticationForm``: A manipulator 
    692       for logging a user in. 
    693  
    694     * ``django.contrib.auth.forms.PasswordChangeForm``: A manipulator 
    695       for allowing a user to change their password. 
    696  
    697     * ``django.contrib.auth.forms.PasswordResetForm``: A manipulator 
    698       for resetting a user's password and emailing the new password to 
    699       them. 
    700  
    701     * ``django.contrib.auth.forms.UserCreationForm``: A manipulator 
    702       for creating a new user. 
     686of not having to write forms for this functionality, the authentication 
     687system provides several built-in forms: 
     688 
     689    * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A form used in 
     690      the admin interface to change a user's password. 
     691 
     692    * ``django.contrib.auth.forms.AuthenticationForm``: A form for logging a 
     693      user in. 
     694 
     695    * ``django.contrib.auth.forms.PasswordChangeForm``: A form for allowing a 
     696      user to change their password. 
     697 
     698    * ``django.contrib.auth.forms.PasswordResetForm``: A form for resetting a 
     699      user's password and emailing the new password to them. 
     700 
     701    * ``django.contrib.auth.forms.UserCreationForm``: A form for creating a 
     702      new user. 
    703703 
    704704Limiting access to logged-in users that pass a test 
  • django/branches/gis/docs/contenttypes.txt

    r7354 r7979  
    205205       models you'll be relating to. (For most models, this means an 
    206206       ``IntegerField`` or ``PositiveIntegerField``.) 
     207 
     208           This field must be of the same type as the primary key of the models 
     209           that will be involved in the generic relation. For example, if you use 
     210           ``IntegerField``, you won't be able to form a generic relation with a 
     211           model that uses a ``CharField`` as a primary key. 
    207212 
    208213    3. Give your model a ``GenericForeignKey``, and pass it the names of 
  • django/branches/gis/docs/custom_model_fields.txt

    r7354 r7979  
    205205    * ``validator_list`` 
    206206    * ``choices`` 
    207     * ``radio_admin`` 
    208207    * ``help_text`` 
    209208    * ``db_column`` 
  • django/branches/gis/docs/generic_views.txt

    r7918 r7979  
    702702      the URLconf. See `Notes on pagination`_ below. 
    703703 
    704     * ``page``: The current page number, as an integer. This is 1-based.  
     704    * ``page``: The current page number, as an integer. This is 1-based. 
    705705      See `Notes on pagination`_ below. 
    706706 
     
    810810        /objects/?page=3 
    811811 
    812     * To loop over all the available page numbers, use the ``page_range``  
    813       variable. You can iterate over the list provided by ``page_range``  
     812    * To loop over all the available page numbers, use the ``page_range`` 
     813      variable. You can iterate over the list provided by ``page_range`` 
    814814      to create a link to every page of results. 
    815815 
    816816These values and lists are 1-based, not 0-based, so the first page would be 
    817 represented as page ``1``.  
     817represented as page ``1``. 
    818818 
    819819For more on pagination, read the `pagination documentation`_. 
     
    821821.. _`pagination documentation`: ../pagination/ 
    822822 
    823 **New in Django development version:**  
     823**New in Django development version:** 
    824824 
    825825As a special case, you are also permitted to use ``last`` as a value for 
     
    828828    /objects/?page=last 
    829829 
    830 This allows you to access the final page of results without first having to  
     830This allows you to access the final page of results without first having to 
    831831determine how many pages there are. 
    832832 
     
    907907for creating, editing and deleting objects. 
    908908 
     909**Changed in Django development version:** 
     910 
     911``django.views.generic.create_update.create_object`` and 
     912``django.views.generic.create_update.update_object`` now use `newforms`_ to 
     913build and display the form. 
     914 
     915.. _newforms: ../newforms/ 
     916 
    909917``django.views.generic.create_update.create_object`` 
    910918---------------------------------------------------- 
     
    913921 
    914922A page that displays a form for creating an object, redisplaying the form with 
    915 validation errors (if there are any) and saving the object. This uses the 
    916 automatic manipulators that come with Django models. 
    917  
    918 **Required arguments:** 
    919  
    920     * ``model``: The Django model class of the object that the form will 
    921       create. 
     923validation errors (if there are any) and saving the object. 
     924 
     925**Required arguments:** 
     926 
     927    * Either ``form_class`` or ``model`` is required. 
     928 
     929      If you provide ``form_class``, it should be a 
     930      ``django.newforms.ModelForm`` subclass.  Use this argument when you need 
     931      to customize the model's form.  See the `ModelForm docs`_ for more 
     932      information. 
     933 
     934      Otherwise, ``model`` should be a Django model class and the form used 
     935      will be a standard ``ModelForm`` for ``model``. 
    922936 
    923937**Optional arguments:** 
     
    960974In addition to ``extra_context``, the template's context will be: 
    961975 
    962     * ``form``: A ``django.oldforms.FormWrapper`` instance representing the form 
    963       for editing the object. This lets you refer to form fields easily in the 
     976    * ``form``: A ``django.newforms.ModelForm`` instance representing the form 
     977      for creating the object. This lets you refer to form fields easily in the 
    964978      template system. 
    965979 
    966       For example, if ``model`` has two fields, ``name`` and ``address``:: 
     980      For example, if the model has two fields, ``name`` and ``address``:: 
    967981 
    968982          <form action="" method="post"> 
    969           <p><label for="id_name">Name:</label> {{ form.name }}</p> 
    970           <p><label for="id_address">Address:</label> {{ form.address }}</p> 
     983          <p>{{ form.name.label_tag }} {{ form.name }}</p> 
     984          <p>{{ form.address.label_tag }} {{ form.address }}</p> 
    971985          </form> 
    972986 
    973       See the `manipulator and formfield documentation`_ for more information 
    974       about using ``FormWrapper`` objects in templates. 
     987      See the `newforms documentation`_ for more information about using 
     988      ``Form`` objects in templates. 
    975989 
    976990.. _authentication system: ../authentication/ 
    977 .. _manipulator and formfield documentation: ../forms/ 
     991.. _ModelForm docs: ../newforms/modelforms 
     992.. _newforms documentation: ../newforms/ 
    978993 
    979994``django.views.generic.create_update.update_object`` 
     
    9881003**Required arguments:** 
    9891004 
    990     * ``model``: The Django model class of the object that the form will 
    991       create. 
     1005    * Either ``form_class`` or ``model`` is required. 
     1006 
     1007      If you provide ``form_class``, it should be a 
     1008      ``django.newforms.ModelForm`` subclass.  Use this argument when you need 
     1009      to customize the model's form.  See the `ModelForm docs`_ for more 
     1010      information. 
     1011 
     1012      Otherwise, ``model`` should be a Django model class and the form used 
     1013      will be a standard ``ModelForm`` for ``model``. 
    9921014 
    9931015    * Either ``object_id`` or (``slug`` *and* ``slug_field``) is required. 
     
    10421064In addition to ``extra_context``, the template's context will be: 
    10431065 
    1044     * ``form``: A ``django.oldforms.FormWrapper`` instance representing the form 
     1066    * ``form``: A ``django.newforms.ModelForm`` instance representing the form 
    10451067      for editing the object. This lets you refer to form fields easily in the 
    10461068      template system. 
    10471069 
    1048       For example, if ``model`` has two fields, ``name`` and ``address``:: 
     1070      For example, if the model has two fields, ``name`` and ``address``:: 
    10491071 
    10501072          <form action="" method="post"> 
    1051           <p><label for="id_name">Name:</label> {{ form.name }}</p> 
    1052           <p><label for="id_address">Address:</label> {{ form.address }}</p> 
     1073          <p>{{ form.name.label_tag }} {{ form.name }}</p> 
     1074          <p>{{ form.address.label_tag }} {{ form.address }}</p> 
    10531075          </form> 
    10541076 
    1055       See the `manipulator and formfield documentation`_ for more information 
    1056       about using ``FormWrapper`` objects in templates. 
     1077      See the `newforms documentation`_ for more information about using 
     1078      ``Form`` objects in templates. 
    10571079 
    10581080    * ``object``: The original object being edited. This variable's name 
  • django/branches/gis/docs/model-api.txt

    r7836 r7979  
    1313    * Model metadata (non-field information) goes in an inner class named 
    1414      ``Meta``. 
    15     * Metadata used for Django's admin site goes into an inner class named 
    16       ``Admin``. 
    1715    * With all of this, Django gives you an automatically-generated 
    1816      database-access API, which is explained in the `Database API reference`_. 
     
    426424Implies ``db_index=True``. 
    427425 
    428 Accepts an extra option, ``prepopulate_from``, which is a list of fields 
    429 from which to auto-populate the slug, via JavaScript, in the object's admin 
    430 form:: 
    431  
    432     models.SlugField(prepopulate_from=("pre_name", "name")) 
    433  
    434 ``prepopulate_from`` doesn't accept DateTimeFields, ForeignKeys nor 
    435 ManyToManyFields. 
    436  
    437 The admin represents ``SlugField`` as an ``<input type="text">`` (a 
    438 single-line input). 
    439  
    440426``SmallIntegerField`` 
    441427~~~~~~~~~~~~~~~~~~~~~ 
     
    569555        gender = models.CharField(max_length=1, choices=GENDER_CHOICES) 
    570556 
     557You can also collect your available choices into named groups that can 
     558be used for organizational purposes:: 
     559 
     560    MEDIA_CHOICES = ( 
     561        ('Audio', ( 
     562                ('vinyl', 'Vinyl'), 
     563                ('cd', 'CD'), 
     564            ) 
     565        ), 
     566        ('Video', ( 
     567                ('vhs', 'VHS Tape'), 
     568                ('dvd', 'DVD'), 
     569            ) 
     570        ), 
     571        ('unknown', 'Unknown'), 
     572    ) 
     573 
     574The first element in each tuple is the name to apply to the group. The  
     575second element is an iterable of 2-tuples, with each 2-tuple containing 
     576a value and a human-readable name for an option. Grouped options may be  
     577combined with ungrouped options within a single list (such as the  
     578`unknown` option in this example). 
     579 
    571580For each model field that has ``choices`` set, Django will add a method to 
    572581retrieve the human-readable name for the field's current value. See 
     
    665674``primary_key=True`` implies ``null=False`` and ``unique=True``. Only 
    666675one primary key is allowed on an object. 
    667  
    668 ``radio_admin`` 
    669 ~~~~~~~~~~~~~~~ 
    670  
    671 By default, Django's admin uses a select-box interface (<select>) for 
    672 fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin`` 
    673 is set to ``True``, Django will use a radio-button interface instead. 
    674  
    675 Don't use this for a field unless it's a ``ForeignKey`` or has ``choices`` 
    676 set. 
    677676 
    678677``unique`` 
     
    823822    Argument                 Description 
    824823    =======================  ============================================================ 
    825     ``edit_inline``          If ``True``, this related object is edited 
    826                              "inline" on the related object's page. This means 
    827                              that the object will not have its own admin 
    828                              interface. Use either ``models.TABULAR`` or ``models.STACKED``, 
    829                              which, respectively, designate whether the inline-editable 
    830                              objects are displayed as a table or as a "stack" of 
    831                              fieldsets. 
    832  
    833824    ``limit_choices_to``     A dictionary of lookup arguments and values (see 
    834825                             the `Database API reference`_) that limit the 
     
    848839 
    849840                             Not compatible with ``edit_inline``. 
    850  
    851     ``max_num_in_admin``     For inline-edited objects, this is the maximum 
    852                              number of related objects to display in the admin. 
    853                              Thus, if a pizza could only have up to 10 
    854                              toppings, ``max_num_in_admin=10`` would ensure 
    855                              that a user never enters more than 10 toppings. 
    856  
    857                              Note that this doesn't ensure more than 10 related 
    858                              toppings ever get created. It simply controls the 
    859                              admin interface; it doesn't enforce things at the 
    860                              Python API level or database level. 
    861  
    862     ``min_num_in_admin``     The minimum number of related objects displayed in 
    863                              the admin. Normally, at the creation stage, 
    864                              ``num_in_admin`` inline objects are shown, and at 
    865                              the edit stage ``num_extra_on_change`` blank 
    866                              objects are shown in addition to all pre-existing 
    867                              related objects.  However, no fewer than 
    868                              ``min_num_in_admin`` related objects will ever be 
    869                              displayed. 
    870  
    871     ``num_extra_on_change``  The number of extra blank related-object fields to 
    872                              show at the change stage. 
    873  
    874     ``num_in_admin``         The default number of inline objects to display 
    875                              on the object page at the add stage. 
    876  
    877     ``raw_id_admin``         Only display a field for the integer to be entered 
    878                              instead of a drop-down menu. This is useful when 
    879                              related to an object type that will have too many 
    880                              rows to make a select box practical. 
    881  
    882                              Not used with ``edit_inline``. 
    883841 
    884842    ``related_name``         The name to use for the relation from the related 
     
    957915    =======================  ============================================================ 
    958916    ``related_name``         See the description under ``ForeignKey`` above. 
    959  
    960     ``filter_interface``     Use a nifty unobtrusive Javascript "filter" interface 
    961                              instead of the usability-challenged ``<select multiple>`` 
    962                              in the admin form for this object. The value should be 
    963                              ``models.HORIZONTAL`` or ``models.VERTICAL`` (i.e. 
    964                              should the interface be stacked horizontally or 
    965                              vertically). 
    966917 
    967918    ``limit_choices_to``     See the description under ``ForeignKey`` above. 
     
    12551206value, just as you would for any other attribute, and it will update the 
    12561207correct field in the model. 
    1257  
    1258 Admin options 
    1259 ============= 
    1260  
    1261 If you want your model to be visible to Django's admin site, give your model an 
    1262 inner ``"class Admin"``, like so:: 
    1263  
    1264     class Person(models.Model): 
    1265         first_name = models.CharField(max_length=30) 
    1266         last_name = models.CharField(max_length=30) 
    1267  
    1268         class Admin: 
    1269             # Admin options go here 
    1270             pass 
    1271  
    1272 The ``Admin`` class tells Django how to display the model in the admin site. 
    1273  
    1274 Here's a list of all possible ``Admin`` options. None of these options are 
    1275 required. To use an admin interface without specifying any options, use 
    1276 ``pass``, like so:: 
    1277  
    1278     class Admin: 
    1279         pass 
    1280  
    1281 Adding ``class Admin`` to a model is completely optional. 
    1282  
    1283 ``date_hierarchy`` 
    1284 ------------------ 
    1285  
    1286 Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in 
    1287 your model, and the change list page will include a date-based drilldown 
    1288 navigation by that field. 
    1289  
    1290 Example:: 
    1291  
    1292     date_hierarchy = 'pub_date' 
    1293  
    1294 ``fields`` 
    1295 ---------- 
    1296  
    1297 Set ``fields`` to control the layout of admin "add" and "change" pages. 
    1298  
    1299 ``fields`` is a list of two-tuples, in which each two-tuple represents a 
    1300 ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of the 
    1301 form.) 
    1302  
    1303 The two-tuples are in the format ``(name, field_options)``, where ``name`` is a 
    1304 string representing the title of the fieldset and ``field_options`` is a 
    1305 dictionary of information about the fieldset, including a list of fields to be 
    1306 displayed in it. 
    1307  
    1308 A full example, taken from the ``django.contrib.flatpages.FlatPage`` model:: 
    1309  
    1310     class Admin: 
    1311         fields = ( 
    1312             (None, { 
    1313                 'fields': ('url', 'title', 'content', 'sites') 
    1314             }), 
    1315             ('Advanced options', { 
    1316                 'classes': 'collapse', 
    1317                 'fields' : ('enable_comments', 'registration_required', 'template_name') 
    1318             }), 
    1319         ) 
    1320  
    1321 This results in an admin page that looks like: 
    1322  
    1323     .. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png 
    1324  
    1325 If ``fields`` isn't given, Django will default to displaying each field that 
    1326 isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in 
    1327 the same order as the fields are defined in the model. 
    1328  
    1329 The ``field_options`` dictionary can have the following keys: 
    1330  
    1331 ``fields`` 
    1332 ~~~~~~~~~~ 
    1333  
    1334 A tuple of field names to display in this fieldset. This key is required. 
    1335  
    1336 Example:: 
    1337  
    1338     { 
    1339     'fields': ('first_name', 'last_name', 'address', 'city', 'state'), 
    1340     } 
    1341  
    1342 To display multiple fields on the same line, wrap those fields in their own 
    1343 tuple. In this example, the ``first_name`` and ``last_name`` fields will 
    1344 display on the same line:: 
    1345  
    1346     { 
    1347     'fields': (('first_name', 'last_name'), 'address', 'city', 'state'), 
    1348     } 
    1349  
    1350 ``classes`` 
    1351 ~~~~~~~~~~~ 
    1352  
    1353 A string containing extra CSS classes to apply to the fieldset. 
    1354  
    1355 Example:: 
    1356  
    1357     { 
    1358     'classes': 'wide', 
    1359     } 
    1360  
    1361 Apply multiple classes by separating them with spaces. Example:: 
    1362  
    1363     { 
    1364     'classes': 'wide extrapretty', 
    1365     } 
    1366  
    1367 Two useful classes defined by the default admin-site stylesheet are 
    1368 ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will be 
    1369 initially collapsed in the admin and replaced with a small "click to expand" 
    1370 link. Fieldsets with the ``wide`` style will be given extra horizontal space. 
    1371  
    1372 ``description`` 
    1373 ~~~~~~~~~~~~~~~ 
    1374  
    1375 A string of optional extra text to be displayed at the top of each fieldset, 
    1376 under the heading of the fieldset. It's used verbatim, so you can use any HTML 
    1377 and you must escape any special HTML characters (such as ampersands) yourself. 
    1378  
    1379 ``js`` 
    1380 ------ 
    1381  
    1382 A list of strings representing URLs of JavaScript files to link into the admin 
    1383 screen via ``<script src="">`` tags. This can be used to tweak a given type of 
    1384 admin page in JavaScript or to provide "quick links" to fill in default values 
    1385 for certain fields. 
    1386  
    1387 If you use relative URLs -- URLs that don't start with ``http://`` or ``/`` -- 
    1388 then the admin site will automatically prefix these links with 
    1389 ``settings.ADMIN_MEDIA_PREFIX``. 
    1390  
    1391 ``list_display`` 
    1392 ---------------- 
    1393  
    1394 Set ``list_display`` to control which fields are displayed on the change list 
    1395 page of the admin. 
    1396  
    1397 Example:: 
    1398  
    1399     list_display = ('first_name', 'last_name') 
    1400  
    1401 If you don't set ``list_display``, the admin site will display a single column 
    1402 that displays the ``__str__()`` representation of each object. 
    1403  
    1404 A few special cases to note about ``list_display``: 
    1405  
    1406     * If the field is a ``ForeignKey``, Django will display the 
    1407       ``__unicode__()`` of the related object. 
    1408  
    1409     * ``ManyToManyField`` fields aren't supported, because that would entail 
    1410       executing a separate SQL statement for each row in the table. If you 
    1411       want to do this nonetheless, give your model a custom method, and add 
    1412       that method's name to ``list_display``. (See below for more on custom 
    1413       methods in ``list_display``.) 
    1414  
    1415     * If the field is a ``BooleanField`` or ``NullBooleanField``, Django will 
    1416       display a pretty "on" or "off" icon instead of ``True`` or ``False``. 
    1417  
    1418     * If the string given is a method of the model, Django will call it and 
    1419       display the output. This method should have a ``short_description`` 
    1420       function attribute, for use as the header for the field. 
    1421  
    1422       Here's a full example model:: 
    1423  
    1424           class Person(models.Model): 
    1425               name = models.CharField(max_length=50) 
    1426               birthday = models.DateField() 
    1427  
    1428               class Admin: 
    1429                   list_display = ('name', 'decade_born_in') 
    1430  
    1431               def decade_born_in(self): 
    1432                   return self.birthday.strftime('%Y')[:3] + "0's" 
    1433               decade_born_in.short_description = 'Birth decade' 
    1434  
    1435     * If the string given is a method of the model, Django will HTML-escape the 
    1436       output by default. If you'd rather not escape the output of the method, 
    1437       give the method an ``allow_tags`` attribute whose value is ``True``. 
    1438  
    1439       Here's a full example model:: 
    1440  
    1441           class Person(models.Model): 
    1442               first_name = models.CharField(max_length=50) 
    1443               last_name = models.CharField(max_length=50) 
    1444               color_code = models.CharField(max_length=6) 
    1445  
    1446               class Admin: 
    1447                   list_display = ('first_name', 'last_name', 'colored_name') 
    1448  
    1449               def colored_name(self): 
    1450                   return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name) 
    1451               colored_name.allow_tags = True 
    1452  
    1453     * If the string given is a method of the model that returns True or False 
    1454       Django will display a pretty "on" or "off" icon if you give the method a 
    1455       ``boolean`` attribute whose value is ``True``. 
    1456  
    1457       Here's a full example model:: 
    1458  
    1459           class Person(models.Model): 
    1460               first_name = models.CharField(max_length=50) 
    1461               birthday = models.DateField() 
    1462  
    1463               class Admin: 
    1464                   list_display = ('name', 'born_in_fifties') 
    1465  
    1466               def born_in_fifties(self): 
    1467                   return self.birthday.strftime('%Y')[:3] == 5 
    1468               born_in_fifties.boolean = True 
    1469  
    1470  
    1471     * The ``__str__()`` and ``__unicode__()`` methods are just as valid in 
    1472       ``list_display`` as any other model method, so it's perfectly OK to do 
    1473       this:: 
    1474  
    1475           list_display = ('__unicode__', 'some_other_field') 
    1476  
    1477     * Usually, elements of ``list_display`` that aren't actual database fields 
    1478       can't be used in sorting (because Django does all the sorting at the 
    1479       database level). 
    1480  
    1481       However, if an element of ``list_display`` represents a certain database 
    1482       field, you can indicate this fact by setting the ``admin_order_field`` 
    1483       attribute of the item. 
    1484  
    1485       For example:: 
    1486  
    1487         class Person(models.Model): 
    1488             first_name = models.CharField(max_length=50) 
    1489             color_code = models.CharField(max_length=6) 
    1490  
    1491             class Admin: 
    1492                 list_display = ('first_name', 'colored_first_name') 
    1493  
    1494             def colored_first_name(self): 
    1495                 return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name) 
    1496             colored_first_name.allow_tags = True 
    1497             colored_first_name.admin_order_field = 'first_name' 
    1498  
    1499       The above will tell Django to order by the ``first_name`` field when 
    1500       trying to sort by ``colored_first_name`` in the admin. 
    1501  
    1502 ``list_display_links`` 
    1503 ---------------------- 
    1504  
    1505 Set ``list_display_links`` to control which fields in ``list_display`` should 
    1506 be linked to the "change" page for an object. 
    1507  
    1508 By default, the change list page will link the first column -- the first field 
    1509 specified in ``list_display`` -- to the change page for each item. But 
    1510 ``list_display_links`` lets you change which columns are linked. Set 
    1511 ``list_display_links`` to a list or tuple of field names (in the same format as 
    1512 ``list_display``) to link. 
    1513  
    1514 ``list_display_links`` can specify one or many field names. As long as the 
    1515 field names appear in ``list_display``, Django doesn't care how many (or how 
    1516 few) fields are linked. The only requirement is: If you want to use 
    1517 ``list_display_links``, you must define ``list_display``. 
    1518  
    1519 In this example, the ``first_name`` and ``last_name`` fields will be linked on 
    1520 the change list page:: 
    1521  
    1522     class Admin: 
    1523         list_display = ('first_name', 'last_name', 'birthday') 
    1524         list_display_links = ('first_name', 'last_name') 
    1525  
    1526 Finally, note that in order to use ``list_display_links``, you must define 
    1527 ``list_display``, too. 
    1528  
    1529 ``list_filter`` 
    1530 --------------- 
    1531  
    1532 Set ``list_filter`` to activate filters in the right sidebar of the change list 
    1533 page of the admin. This should be a list of field names, and each specified 
    1534 field should be either a ``BooleanField``, ``CharField``, ``DateField``, 
    1535 ``DateTimeField``, ``IntegerField`` or ``ForeignKey``. 
    1536  
    1537 This example, taken from the ``django.contrib.auth.models.User`` model, shows 
    1538 how both ``list_display`` and ``list_filter`` work:: 
    1539  
    1540     class Admin: 
    1541         list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') 
    1542         list_filter = ('is_staff', 'is_superuser') 
    1543  
    1544 The above code results in an admin change list page that looks like this: 
    1545  
    1546     .. image:: http://media.djangoproject.com/img/doc/users_changelist.png 
    1547  
    1548 (This example also has ``search_fields`` defined. See below.) 
    1549  
    1550 ``list_per_page`` 
    1551 ----------------- 
    1552  
    1553 Set ``list_per_page`` to control how many items appear on each paginated admin 
    1554 change list page. By default, this is set to ``100``. 
    1555  
    1556 ``list_select_related`` 
    1557 ----------------------- 
    1558  
    1559 Set ``list_select_related`` to tell Django to use ``select_related()`` in 
    1560 retrieving the list of objects on the admin change list page. This can save you 
    1561 a bunch of database queries. 
    1562  
    1563 The value should be either ``True`` or ``False``. Default is ``False``. 
    1564  
    1565 Note that Django will use ``select_related()``, regardless of this setting, 
    1566 if one of the ``list_display`` fields is a ``ForeignKey``. 
    1567  
    1568 For more on ``select_related()``, see `the select_related() docs`_. 
    1569  
    1570 .. _the select_related() docs: ../db-api/#select-related 
    1571  
    1572 ``ordering`` 
    1573 ------------ 
    1574  
    1575 Set ``ordering`` to specify how objects on the admin change list page should be 
    1576 ordered. This should be a list or tuple in the same format as a model's 
    1577 ``ordering`` parameter. 
    1578  
    1579 If this isn't provided, the Django admin will use the model's default ordering. 
    1580  
    1581 ``save_as`` 
    1582 ----------- 
    1583  
    1584 Set ``save_as`` to enable a "save as" feature on admin change forms. 
    1585  
    1586 Normally, objects have three save options: "Save", "Save and continue editing" 
    1587 and "Save and add another". If ``save_as`` is ``True``, "Save and add another" 
    1588 will be replaced by a "Save as" button. 
    1589  
    1590 "Save as" means the object will be saved as a new object (with a new ID), 
    1591 rather than the old object. 
    1592  
    1593 By default, ``save_as`` is set to ``False``. 
    1594  
    1595 ``save_on_top`` 
    1596 --------------- 
    1597  
    1598 Set ``save_on_top`` to add save buttons across the top of your admin change 
    1599 forms. 
    1600  
    1601 Normally, the save buttons appear only at the bottom of the forms. If you set 
    1602 ``save_on_top``, the buttons will appear both on the top and the bottom. 
    1603  
    1604 By default, ``save_on_top`` is set to ``False``. 
    1605  
    1606 ``search_fields`` 
    1607 ----------------- 
    1608  
    1609 Set ``search_fields`` to enable a search box on the admin change list page. 
    1610 This should be set to a list of field names that will be searched whenever 
    1611 somebody submits a search query in that text box. 
    1612  
    1613 These fields should be some kind of text field, such as ``CharField`` or 
    1614 ``TextField``. You can also perform a related lookup on a ``ForeignKey`` with 
    1615 the lookup API "follow" notation:: 
    1616  
    1617     search_fields = ['foreign_key__related_fieldname'] 
    1618  
    1619 When somebody does a search in the admin search box, Django splits the search 
    1620 query into words and returns all objects that contain each of the words, case 
    1621 insensitive, where each word must be in at least one of ``search_fields``. For 
    1622 example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a 
    1623 user searches for ``john lennon``, Django will do the equivalent of this SQL 
    1624 ``WHERE`` clause:: 
    1625  
    1626     WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%') 
    1627     AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%') 
    1628  
    1629 For faster and/or more restrictive searches, prefix the field name 
    1630 with an operator: 
    1631  
    1632 ``^`` 
    1633     Matches the beginning of the field. For example, if ``search_fields`` is 
    1634     set to ``['^first_name', '^last_name']`` and a user searches for 
    1635     ``john lennon``, Django will do the equivalent of this SQL ``WHERE`` 
    1636     clause:: 
    1637  
    1638         WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%') 
    1639         AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%') 
    1640  
    1641     This query is more efficient than the normal ``'%john%'`` query, because 
    1642     the database only needs to check the beginning of a column's data, rather 
    1643     than seeking through the entire column's data. Plus, if the column has an 
    1644     index on it, some databases may be able to use the index for this query, 
    1645     even though it's a ``LIKE`` query. 
    1646  
    1647 ``=`` 
    1648     Matches exactly, case-insensitive. For example, if 
    1649     ``search_fields`` is set to ``['=first_name', '=last_name']`` and 
    1650     a user searches for ``john lennon``, Django will do the equivalent 
    1651     of this SQL ``WHERE`` clause:: 
    1652  
    1653         WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john') 
    1654         AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon') 
    1655  
    1656     Note that the query input is split by spaces, so, following this example, 
    1657     it's currently not possible to search for all records in which 
    1658     ``first_name`` is exactly ``'john winston'`` (containing a space). 
    1659  
    1660 ``@`` 
    1661     Performs a full-text match. This is like the default search method but uses 
    1662     an index. Currently this is only available for MySQL. 
    16631208 
    16641209Managers 
  • django/branches/gis/docs/modelforms.txt

    r7768 r7979  
    377377Chances are these notes won't affect you unless you're trying to do something 
    378378tricky with subclassing. 
     379 
     380Model Formsets 
     381============== 
     382 
     383Similar to regular formsets there are a couple enhanced formset classes that 
     384provide all the right things to work with your models. Lets reuse the 
     385``Author`` model from above:: 
     386 
     387    >>> from django.newforms.models import modelformset_factory 
     388    >>> AuthorFormSet = modelformset_factory(Author) 
     389 
     390This will create a formset that is capable of working with the data associated 
     391to the ``Author`` model. It works just like a regular formset:: 
     392 
     393    >>> formset = AuthorFormSet() 
     394    >>> print formset 
     395    <input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /> 
     396    <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></td></tr> 
     397    <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title"> 
     398    <option value="" selected="selected">---------</option> 
     399    <option value="MR">Mr.</option> 
     400    <option value="MRS">Mrs.</option> 
     401    <option value="MS">Ms.</option> 
     402    </select></td></tr> 
     403    <tr><th><label for="id_form-0-birth_date">Birth date:</label></th><td><input type="text" name="form-0-birth_date" id="id_form-0-birth_date" /><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr> 
     404 
     405.. note:: 
     406    One thing to note is that ``modelformset_factory`` uses ``formset_factory`` 
     407    and by default uses ``can_delete=True``. 
     408 
     409Changing the queryset 
     410--------------------- 
     411 
     412By default when you create a formset from a model the queryset will be all 
     413objects in the model. This is best shown as ``Author.objects.all()``. This is 
     414configurable:: 
     415 
     416    >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O')) 
     417 
     418Alternatively, you can use a subclassing based approach:: 
     419 
     420    from django.newforms.models import BaseModelFormSet 
     421     
     422    class BaseAuthorFormSet(BaseModelFormSet): 
     423        def get_queryset(self): 
     424            return super(BaseAuthorFormSet, self).get_queryset().filter(name__startswith='O') 
     425 
     426Then your ``BaseAuthorFormSet`` would be passed into the factory function to 
     427be used as a base:: 
     428 
     429    >>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet) 
     430 
     431Saving objects in the formset 
     432----------------------------- 
     433 
     434Similar to a ``ModelForm`` you can save the data into the model. This is done 
     435with the ``save()`` method on the formset:: 
     436 
     437    # create a formset instance with POST data. 
     438    >>> formset = AuthorFormSet(request.POST) 
     439     
     440    # assuming all is valid, save the data 
     441    >>> instances = formset.save() 
     442 
     443The ``save()`` method will return the instances that have been saved to the 
     444database. If an instance did not change in the bound data it will not be 
     445saved to the database and not found in ``instances`` in the above example. 
     446 
     447You can optionally pass in ``commit=False`` to ``save()`` to only return the 
     448model instances without any database interaction:: 
     449 
     450    # don't save to the database 
     451    >>> instances = formset.save(commit=False) 
     452    >>> for instance in instances: 
     453    ...     # do something with instance 
     454    ...     instance.save() 
     455 
     456This gives you the ability to attach data to the instances before saving them 
     457to the database. If your formset contains a ``ManyToManyField`` you will also 
     458need to make a call to ``formset.save_m2m()`` to ensure the many-to-many 
     459relationships are saved properly. 
     460 
     461Limiting the number of objects editable 
     462--------------------------------------- 
     463 
     464Similar to regular formsets you can use the ``max_num`` parameter to 
     465``modelformset_factory`` to limit the number of forms displayed. With 
     466model formsets this will properly limit the query to only select the maximum 
     467number of objects needed:: 
     468 
     469    >>> Author.objects.order_by('name') 
     470    [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>] 
     471     
     472    >>> AuthorFormSet = modelformset_factory(Author, max_num=2, extra=1) 
     473    >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name')) 
     474    >>> formset.initial 
     475    [{'id': 1, 'name': u'Charles Baudelaire'}, {'id': 3, 'name': u'Paul Verlaine'}] 
     476 
     477If the value of ``max_num`` is less than the total objects returned it will 
     478fill the rest with extra forms:: 
     479 
     480    >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=1) 
     481    >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name')) 
     482    >>> for form in formset.forms: 
     483    ...     print form.as_table() 
     484    <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></td></tr> 
     485    <tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" type="text" name="form-1-name" value="Paul Verlaine" maxlength="100" /><input type="hidden" name="form-1-id" value="3" id="id_form-1-id" /></td></tr> 
     486    <tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" type="text" name="form-2-name" value="Walt Whitman" maxlength="100" /><input type="hidden" name="form-2-id" value="2" id="id_form-2-id" /></td></tr> 
     487    <tr><th><label for="id_form-3-name">Name:</label></th><td><input id="id_form-3-name" type="text" name="form-3-name" maxlength="100" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></td></tr> 
     488 
     489Using ``inlineformset_factory`` 
     490------------------------------- 
     491 
     492The ``inlineformset_factory`` is a helper to a common usage pattern of working 
     <