From d34639b09bf85dfb1b6f9a4b59f8ccbc3117230b Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Thu, 7 Jun 2007 21:49:06 +0000 Subject: newforms-admin: Merged to [5439] git-svn-id: http://code.djangoproject.com/svn/django/branches/newforms-admin@5440 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/add_ons.txt | 9 ++++++-- docs/db-api.txt | 16 +++++++++++--- docs/django-admin.txt | 9 ++++---- docs/fastcgi.txt | 2 +- docs/generic_views.txt | 3 +++ docs/install.txt | 4 +++- docs/model-api.txt | 36 +++++++++++++++++++++++--------- docs/modpython.txt | 49 +++++++++++++++++++++++++++++++++++++++++-- docs/newforms.txt | 8 +++---- docs/serialization.txt | 23 ++++++++++++++++++++ docs/settings.txt | 53 ++++++++++++++++++++++++++++++++++++++++------- docs/templates.txt | 26 ++++++++++++++++------- docs/templates_python.txt | 12 ++++++++++- docs/testing.txt | 12 +++++++++-- docs/tutorial03.txt | 5 +++-- docs/tutorial04.txt | 28 ++++++++++++++++++++++--- docs/url_dispatch.txt | 35 +++++++++++++++++++++++++++++++ 17 files changed, 279 insertions(+), 51 deletions(-) (limited to 'docs') diff --git a/docs/add_ons.txt b/docs/add_ons.txt index 4f45d99d9a..ffc4f7420f 100644 --- a/docs/add_ons.txt +++ b/docs/add_ons.txt @@ -6,8 +6,9 @@ Django aims to follow Python's `"batteries included" philosophy`_. It ships with a variety of extra, optional tools that solve common Web-development problems. -This code lives in ``django/contrib`` in the Django distribution. Here's a -rundown of the packages in ``contrib``: +This code lives in ``django/contrib`` in the Django distribution. This document +gives a rundown of the packages in ``contrib``, along with any dependencies +those packages have. .. admonition:: Note @@ -26,6 +27,8 @@ The automatic Django administrative interface. For more information, see .. _Tutorial 2: ../tutorial02/ +Requires the auth_ and contenttypes_ contrib packages to be installed. + auth ==== @@ -144,6 +147,8 @@ See the `flatpages documentation`_. .. _flatpages documentation: ../flatpages/ +Requires the sites_ contrib package to be installed as well. + localflavor =========== diff --git a/docs/db-api.txt b/docs/db-api.txt index de612e0e3d..775913d693 100644 --- a/docs/db-api.txt +++ b/docs/db-api.txt @@ -134,6 +134,15 @@ the database until you explicitly call ``save()``. The ``save()`` method has no return value. +Updating ``ForeignKey`` fields works exactly the same way; simply assign an +object of the right type to the field in question:: + + joe = Author.objects.create(name="Joe") + entry.author = joe + entry.save() + +Django will complain if you try to assign an object of the wrong type. + How Django knows to UPDATE vs. INSERT ------------------------------------- @@ -1229,8 +1238,8 @@ whose ``headline`` contains ``'Lennon'``:: Blog.objects.filter(entry__headline__contains='Lennon') -Escaping parenthesis and underscores in LIKE statements -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Escaping percent signs and underscores in LIKE statements +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The field lookups that equate to ``LIKE`` SQL statements (``iexact``, ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith`` @@ -1748,7 +1757,8 @@ Shortcuts As you develop views, you will discover a number of common idioms in the way you use the database API. Django encodes some of these idioms as -shortcuts that can be used to simplify the process of writing views. +shortcuts that can be used to simplify the process of writing views. These +functions are in the ``django.shortcuts`` module. get_object_or_404() ------------------- diff --git a/docs/django-admin.txt b/docs/django-admin.txt index cc2eadc365..d20db7edc9 100644 --- a/docs/django-admin.txt +++ b/docs/django-admin.txt @@ -295,7 +295,7 @@ Serving static files with the development server ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default, the development server doesn't serve any static files for your site -(such as CSS files, images, things under ``MEDIA_ROOT_URL`` and so forth). If +(such as CSS files, images, things under ``MEDIA_URL`` and so forth). If you want to configure Django to serve static media, read the `serving static files`_ documentation. @@ -403,9 +403,10 @@ this command to install the default apps. If you're installing the ``django.contrib.auth`` application, ``syncdb`` will give you the option of creating a superuser immediately. -``syncdb`` will also search for and install any fixture named ``initial_data``. -See the documentation for ``loaddata`` for details on the specification of -fixture data files. +``syncdb`` will also search for and install any fixture named ``initial_data`` +with an appropriate extension (e.g. ``json`` or ``xml``). See the +documentation for ``loaddata`` for details on the specification of fixture +data files. test ---- diff --git a/docs/fastcgi.txt b/docs/fastcgi.txt index 119688096f..81888bba76 100644 --- a/docs/fastcgi.txt +++ b/docs/fastcgi.txt @@ -203,7 +203,7 @@ This is probably the most common case, if you're using Django's admin site:: DocumentRoot /home/user/public_html Alias /media /home/user/python/django/contrib/admin/media RewriteEngine On - RewriteRule ^/(media.*)$ /$1 [QSA,L] + RewriteRule ^/(media.*)$ /$1 [QSA,L,PT] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L] diff --git a/docs/generic_views.txt b/docs/generic_views.txt index bb5f7320f6..359a82506a 100644 --- a/docs/generic_views.txt +++ b/docs/generic_views.txt @@ -99,6 +99,9 @@ which is a dictionary of the parameters captured in the URL. dictionary is callable, the generic view will call it just before rendering the template. + * ``mimetype``: The MIME type to use for the resulting document. Defaults + to the value of the ``DEFAULT_CONTENT_TYPE`` setting. + **Example:** Given the following URL patterns:: diff --git a/docs/install.txt b/docs/install.txt index c3ccd27f76..4f5a4bbe31 100644 --- a/docs/install.txt +++ b/docs/install.txt @@ -97,7 +97,9 @@ This file should also be located in your ``site-packages`` directory. * If you're using Windows: ``C:\Python2.X\lib\site-packages`` - * If you're using MacOSX: ``/Library/Python2.X/site-packages`` + * If you're using MacOSX: ``/Library/Python2.X/site-packages`` or + ``/Library/Frameworks/Python.framework/Versions/2.X/lib/python2.X/site-packages/`` + (in later releases). Install the Django code ======================= diff --git a/docs/model-api.txt b/docs/model-api.txt index ae1c37fc8f..a6bb8a5cfc 100644 --- a/docs/model-api.txt +++ b/docs/model-api.txt @@ -269,6 +269,13 @@ For example, say your ``MEDIA_ROOT`` is set to ``'/home/media'``, and upload a file on Jan. 15, 2007, it will be saved in the directory ``/home/media/photos/2007/01/15``. +If you want to retrieve the upload file's on-disk filename, or a URL that +refers to that file, or the file's size, you can use the +``get_FOO_filename()``, ``get_FOO_url()`` and ``get_FOO_size()`` methods. +They are all documented here__. + +__ ../db-api/#get-foo-filename + Note that whenever you deal with uploaded files, you should pay close attention to where you're uploading them and what type of files they are, to avoid security holes. *Validate all uploaded files* so that you're sure the files are @@ -338,9 +345,14 @@ image. Has two extra optional arguments, ``height_field`` and ``width_field``, which, if set, will be auto-populated with the height and width of the image each time a model instance is saved. +In addition to the special ``get_FOO_*`` methods that are available for +``FileField``, an ``ImageField`` also has ``get_FOO_height()`` and +``get_FOO_width()`` methods. These are documented elsewhere_. + Requires the `Python Imaging Library`_. .. _Python Imaging Library: http://www.pythonware.com/products/pil/ +.. _elsewhere: ../db-api/#get-foo-height-and-get-foo-width ``IntegerField`` ~~~~~~~~~~~~~~~~ @@ -463,8 +475,10 @@ If ``True``, Django will store empty values as ``NULL`` in the database. Default is ``False``. Note that empty string values will always get stored as empty strings, not -as ``NULL`` -- so use ``null=True`` for non-string fields such as integers, -booleans and dates. +as ``NULL``. Only use ``null=True`` for non-string fields such as integers, +booleans and dates. For both types of fields, you will also need to set +``blank=True`` if you wish to permit empty values in forms, as the ``null`` +parameter only affects database storage (see blank_, below). Avoid using ``null`` on string-based fields such as ``CharField`` and ``TextField`` unless you have an excellent reason. If a string-based field @@ -1846,14 +1860,15 @@ rows. Example:: row = cursor.fetchone() return row -``connection`` and ``cursor`` simply use the standard `Python DB-API`_. If -you're not familiar with the Python DB-API, note that the SQL statement in -``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters -directly within the SQL. If you use this technique, the underlying database -library will automatically add quotes and escaping to your parameter(s) as -necessary. (Also note that Django expects the ``"%s"`` placeholder, *not* the -``"?"`` placeholder, which is used by the SQLite Python bindings. This is for -the sake of consistency and sanity.) +``connection`` and ``cursor`` mostly implement the standard `Python DB-API`_ +(except when it comes to `transaction handling`_). If you're not familiar with +the Python DB-API, note that the SQL statement in ``cursor.execute()`` uses +placeholders, ``"%s"``, rather than adding parameters directly within the SQL. +If you use this technique, the underlying database library will automatically +add quotes and escaping to your parameter(s) as necessary. (Also note that +Django expects the ``"%s"`` placeholder, *not* the ``"?"`` placeholder, which is +used by the SQLite Python bindings. This is for the sake of consistency and +sanity.) A final note: If all you want to do is a custom ``WHERE`` clause, you can just just the ``where``, ``tables`` and ``params`` arguments to the standard lookup @@ -1861,6 +1876,7 @@ API. See `Other lookup options`_. .. _Python DB-API: http://www.python.org/peps/pep-0249.html .. _Other lookup options: ../db-api/#extra-params-select-where-tables +.. _transaction handling: ../transactions/ Overriding default model methods -------------------------------- diff --git a/docs/modpython.txt b/docs/modpython.txt index 37909a09fd..388a6168f3 100644 --- a/docs/modpython.txt +++ b/docs/modpython.txt @@ -51,9 +51,17 @@ whereas ```` points at places in the URL structure of a Web site. ```` would be meaningless here. Also, if you've manually altered your ``PYTHONPATH`` to put your Django project -on it, you'll need to tell mod_python:: +on it, you'll need to tell mod_python: - PythonPath "['/path/to/project'] + sys.path" +.. parsed-literal:: + + + SetHandler python-program + PythonHandler django.core.handlers.modpython + SetEnv DJANGO_SETTINGS_MODULE mysite.settings + PythonDebug On + **PythonPath "['/path/to/project'] + sys.path"** + .. caution:: @@ -211,6 +219,41 @@ Here are two recommended approaches: 2. Or, copy the admin media files so that they live within your Apache document root. +Using eggs with mod_python +========================== + +If you installed Django from a Python egg_ or are using eggs in your Django +project, some extra configuration is required. Create an extra file in your +project (or somewhere else) that contains something like the following:: + + import os + os.environ['PYTHON_EGG_CACHE'] = '/some/directory' + +Here, ``/some/directory`` is a directory that the Apache webserver process can +write to. It will be used as the location for any unpacking of code the eggs +need to do. + +Then you have to tell mod_python to import this file before doing anything +else. This is done using the PythonImport_ directive to mod_python. You need +to ensure that you have specified the ``PythonInterpreter`` directive to +mod_python as described above__ (you need to do this even if you aren't +serving multiple installations in this case). Then add the ``PythonImport`` +line inside the ``Location`` or ``VirtualHost`` section. For example:: + + PythonInterpreter my_django + PythonImport /path/to/my/project/file.py my_django + +Note that you can use an absolute path here (or a normal dotted import path), +as described in the `mod_python manual`_. We use an absolute path in the +above example because if any Python path modifications are required to access +your project, they will not have been done at the time the ``PythonImport`` +line is processed. + +.. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs +.. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html +.. _mod_python manual: PythonImport_ +__ `Multiple Django installations on the same Apache`_ + Error handling ============== @@ -256,3 +299,5 @@ as necessary. .. _Expat Causing Apache Crash: http://www.dscpl.com.au/articles/modpython-006.html .. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp .. _Getting mod_python Working: http://www.dscpl.com.au/articles/modpython-001.html + + diff --git a/docs/newforms.txt b/docs/newforms.txt index 7ec4e9560c..bb6c179648 100644 --- a/docs/newforms.txt +++ b/docs/newforms.txt @@ -686,13 +686,13 @@ For example::
    -
  • {{ form.sender.label }} {{ form.sender.label }}
  • +
  • {{ form.sender.label }} {{ form.sender }}
  • {{ form.sender.help_text }}
  • - {% if form.sender.errors %}
      {{ form.sender.errors }}{% endif %} + {% if form.sender.errors %}
        {{ form.sender.errors }}
      {% endif %} -
    • {{ form.subject.label }} {{ form.subject.label }}
    • +
    • {{ form.subject.label }} {{ form.subject }}
    • {{ form.subject.help_text }}
    • - {% if form.subject.errors %}
        {{ form.subject.errors }}{% endif %} + {% if form.subject.errors %}
          {{ form.subject.errors }}
        {% endif %} ...
      diff --git a/docs/serialization.txt b/docs/serialization.txt index 3216cb061e..01afa2708c 100644 --- a/docs/serialization.txt +++ b/docs/serialization.txt @@ -44,6 +44,25 @@ This is useful if you want to serialize data directly to a file-like object .. _HTTPResponse: ../request_response/#httpresponse-objects +Subset of fields +~~~~~~~~~~~~~~~~ + +If you only want a subset of fields to be serialized, you can +specify a `fields` argument to the serializer:: + + from django.core import serializers + data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size')) + +In this example, only the `name` and `size` attributes of each model will +be serialized. + +.. note:: + + Depending on your model, you may find that it is not possible to deserialize + a model that only serializes a subset of its fields. If a serialized object + doesn't specify all the fields that are required by a model, the deserializer + will not be able to save deserialized instances. + Deserializing data ------------------ @@ -92,10 +111,14 @@ Django "ships" with a few included serializers: ``python`` Translates to and from "simple" Python objects (lists, dicts, strings, etc.). Not really all that useful on its own, but used as a base for other serializers. + + ``yaml`` Serializes to YAML (Yet Another Markup Lanuage). This + serializer is only available if PyYAML_ is installed. ========== ============================================================== .. _json: http://json.org/ .. _simplejson: http://undefined.org/python/#simplejson +.. _PyYAML: http://www.pyyaml.org/ Notes for specific serialization formats ---------------------------------------- diff --git a/docs/settings.txt b/docs/settings.txt index bf0a9f85f6..12e6dab4bc 100644 --- a/docs/settings.txt +++ b/docs/settings.txt @@ -264,6 +264,11 @@ MySQL will connect via a Unix socket to the specified socket. For example:: If you're using MySQL and this value *doesn't* start with a forward slash, then this value is assumed to be the host. +If you're using PostgreSQL, an empty string means to use a Unix domain socket +for the connection, rather than a network connection to localhost. If you +explictly need to use a TCP/IP connection on the local machine with +PostgreSQL, specify ``localhost`` here. + DATABASE_NAME ------------- @@ -771,7 +776,8 @@ Default:: ("django.core.context_processors.auth", "django.core.context_processors.debug", - "django.core.context_processors.i18n") + "django.core.context_processors.i18n", + "django.core.context_processors.media") A tuple of callables that are used to populate the context in ``RequestContext``. These callables take a request object as their argument and return a dictionary @@ -820,26 +826,57 @@ misspelled) variables. See `How invalid variables are handled`_. .. _How invalid variables are handled: ../templates_python/#how-invalid-variables-are-handled -TEST_RUNNER ------------ +TEST_DATABASE_CHARSET +--------------------- -Default: ``'django.test.simple.run_tests'`` +**New in Django development version** -The name of the method to use for starting the test suite. See -`Testing Django Applications`_. +Default: ``None`` -.. _Testing Django Applications: ../testing/ +The character set encoding used to create the test database. The value of this +string is passed directly through to the database, so its format is +backend-specific. + +Supported for the PostgreSQL_ (``postgresql``, ``postgresql_psycopg2``) and MySQL_ (``mysql``, ``mysql_old``) backends. + +.. _PostgreSQL: http://www.postgresql.org/docs/8.2/static/multibyte.html +.. _MySQL: http://www.mysql.org/doc/refman/5.0/en/charset-database.html + +TEST_DATABASE_COLLATION +------------------------ + +**New in Django development version** + +Default: ``None`` + +The collation order to use when creating the test database. This value is +passed directly to the backend, so its format is backend-specific. + +Only supported for ``mysql`` and ``mysql_old`` backends (see `section 10.3.2`_ +of the MySQL manual for details). + +.. _section 10.3.2: http://www.mysql.org/doc/refman/5.0/en/charset-database.html TEST_DATABASE_NAME ------------------ Default: ``None`` -The name of database to use when running the test suite. If a value of +The name of database to use when running the test suite. If a value of ``None`` is specified, the test database will use the name ``'test_' + settings.DATABASE_NAME``. See `Testing Django Applications`_. .. _Testing Django Applications: ../testing/ +TEST_RUNNER +----------- + +Default: ``'django.test.simple.run_tests'`` + +The name of the method to use for starting the test suite. See +`Testing Django Applications`_. + +.. _Testing Django Applications: ../testing/ + TIME_FORMAT ----------- diff --git a/docs/templates.txt b/docs/templates.txt index 2f9f769b96..d8b511dedc 100644 --- a/docs/templates.txt +++ b/docs/templates.txt @@ -91,9 +91,12 @@ Filters can be "chained." The output of one filter is applied to the next. ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents, then converting line breaks to ``

      `` tags. -Some filters take arguments. A filter argument looks like this: -``{{ bio|truncatewords:"30" }}``. This will display the first 30 words of the -``bio`` variable. Filter arguments always are in double quotes. +Some filters take arguments. A filter argument looks like this: ``{{ +bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio`` +variable. + +Filter arguments that contain spaces must be quoted; for example, to join a list +with commas and spaced you'd use ``{{ list|join:", " }}``. The `Built-in filter reference`_ below describes all the built-in filters. @@ -112,7 +115,7 @@ know how to write Python code. Comments ======== -To comment-out part of a template, use the comment syntax: ``{# #}``. +To comment-out part of a line in a template, use the comment syntax: ``{# #}``. For example, this template would render as ``'hello'``:: @@ -122,6 +125,12 @@ A comment can contain any template code, invalid or not. For example:: {# {% if foo %}bar{% else %} #} +This syntax can only be used for single-line comments (no newlines are +permitted between the ``{#`` and ``#}`` delimiters). If you need to comment +out a multiline portion of the template, see the ``comment`` tag, below__. + +__ comment_ + Template inheritance ==================== @@ -843,10 +852,11 @@ The first argument is a path to a view function in the format should be comma-separated values that will be used as positional and keyword arguments in the URL. All arguments required by the URLconf should be present. -For example, suppose you have a view, ``app_name.client``, whose URLconf takes -a client ID. The URLconf line might look like this:: +For example, suppose you have a view, ``app_views.client``, whose URLconf +takes a client ID (here, ``client()`` is a method inside the views file +``app_views.py``). The URLconf line might look like this:: - ('^client/(\d+)/$', 'app_name.client') + ('^client/(\d+)/$', 'app_views.client') If this app's URLconf is included into the project's URLconf under a path such as this:: @@ -855,7 +865,7 @@ such as this:: ...then, in a template, you can create a link to this view like this:: - {% url app_name.client client.id %} + {% url app_views.client client.id %} The template tag will output the string ``/clients/client/123/``. diff --git a/docs/templates_python.txt b/docs/templates_python.txt index 08a287f572..f3e2f2c64b 100644 --- a/docs/templates_python.txt +++ b/docs/templates_python.txt @@ -294,7 +294,8 @@ return a dictionary of items to be merged into the context. By default, ("django.core.context_processors.auth", "django.core.context_processors.debug", - "django.core.context_processors.i18n") + "django.core.context_processors.i18n", + "django.core.context_processors.media") Each processor is applied in order. That means, if one processor adds a variable to the context and a second processor adds a variable with the same @@ -390,6 +391,15 @@ See the `internationalization docs`_ for more. .. _LANGUAGE_CODE setting: ../settings/#language-code .. _internationalization docs: ../i18n/ +django.core.context_processors.media +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every +``RequestContext`` will contain a variable ``MEDIA_URL``, providing the +value of the `MEDIA_URL setting`_. + +.. _MEDIA_URL setting: ../settings/#media-url + django.core.context_processors.request ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/testing.txt b/docs/testing.txt index 92edf46e09..50c4ec3046 100644 --- a/docs/testing.txt +++ b/docs/testing.txt @@ -4,7 +4,7 @@ Testing Django applications Automated testing is an extremely useful bug-killing tool for the modern Web developer. You can use a collection of tests -- a **test suite** -- to -to solve, or avoid, a number of problems: +solve, or avoid, a number of problems: * When you're writing new code, you can use tests to validate your code works as expected. @@ -147,7 +147,7 @@ doctests or unit tests are right for you. If you've been using Python for a while, ``doctest`` will probably feel more "pythonic". It's designed to make writing tests as easy as possible, so there's no overhead of writing classes or methods; you simply put tests in -docstrings. This gives the added advantage of given your modules automatic +docstrings. This gives the added advantage of giving your modules automatic documentation -- well-written doctests can kill both the documentation and the testing bird with a single stone. @@ -571,6 +571,14 @@ database settings will the same as they would be for the project normally. If you wish to use a name other than the default for the test database, you can use the ``TEST_DATABASE_NAME`` setting to provide a name. +**New in Django development version:** For fine-grained control over the +character encoding of your database, use the ``TEST_DATABASE_CHARSET`` setting. +If you're using MySQL, you can also use the ``TEST_DATABASE_COLLATION`` setting +to control the particular collation used by the test database. See the +settings_ documentation for details of these advanced settings. + +.. _settings: ../settings/ + The test database is created by the user in the ``DATABASE_USER`` setting. This user needs to have sufficient privileges to create a new database on the system. diff --git a/docs/tutorial03.txt b/docs/tutorial03.txt index 8bb63791aa..41febe021d 100644 --- a/docs/tutorial03.txt +++ b/docs/tutorial03.txt @@ -60,9 +60,10 @@ arguments from the dictionary (an optional third item in the tuple). For more on ``HTTPRequest`` objects, see the `request and response documentation`_. For more details on URLconfs, see the `URLconf documentation`_. -When you ran ``python manage.py startproject mysite`` at the beginning of +When you ran ``python django-admin.py startproject mysite`` at the beginning of Tutorial 1, it created a default URLconf in ``mysite/urls.py``. It also -automatically set your ``ROOT_URLCONF`` setting to point at that file:: +automatically set your ``ROOT_URLCONF`` setting (in ``settings.py``) to point +at that file:: ROOT_URLCONF = 'mysite.urls' diff --git a/docs/tutorial04.txt b/docs/tutorial04.txt index 6fee842f8b..5cc12c445d 100644 --- a/docs/tutorial04.txt +++ b/docs/tutorial04.txt @@ -48,6 +48,7 @@ So let's create a ``vote()`` function in ``mysite/polls/views.py``:: from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponseRedirect + from django.core.urlresolvers import reverse from mysite.polls.models import Choice, Poll # ... def vote(request, poll_id): @@ -66,7 +67,7 @@ So let's create a ``vote()`` function in ``mysite/polls/views.py``:: # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. - return HttpResponseRedirect('/polls/%s/results/' % p.id) + return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,))) This code includes a few things we haven't covered yet in this tutorial: @@ -86,13 +87,29 @@ This code includes a few things we haven't covered yet in this tutorial: * After incrementing the choice count, the code returns an ``HttpResponseRedirect`` rather than a normal ``HttpResponse``. ``HttpResponseRedirect`` takes a single argument: the URL to which the - user will be redirected. You should leave off the "http://" and domain - name if you can. That helps your app become portable across domains. + user will be redirected (see the following point for how we construct + the URL in this case). As the Python comment above points out, you should always return an ``HttpResponseRedirect`` after successfully dealing with POST data. This tip isn't specific to Django; it's just good Web development practice. + * We are using the ``reverse()`` function in the ``HttpResponseRedirect`` + constructor in this example. This function helps avoid having to + hardcode a URL in the view function. It is given the name of the view + that we want to pass control to and the variable portion of the URL + pattern that points to that view. In this case, using the URLConf we set + up in Tutorial 3, this ``reverse()`` call will return a string like :: + + '/polls/3/results/' + + ... where the ``3`` is the value of ``p.id``. This redirected URL will + then call the ``'results'`` view to display the final page. Note that + you need to use the full name of the view here (including the prefix). + + For more information about ``reverse()``, see the `URL dispatcher`_ + documentation. + As mentioned in Tutorial 3, ``request`` is a ``HTTPRequest`` object. For more on ``HTTPRequest`` objects, see the `request and response documentation`_. @@ -121,6 +138,7 @@ results page that gets updated each time you vote. If you submit the form without having chosen a choice, you should see the error message. .. _request and response documentation: ../request_response/ +.. _URL dispatcher: ../url_dispatch#reverse Use generic views: Less code is better ====================================== @@ -256,4 +274,8 @@ installments: * Advanced admin features: Permissions * Advanced admin features: Custom JavaScript +In the meantime, you can read through the rest of the `Django documentation`_ +and start writing your own applications. + .. _Tutorial 3: ../tutorial03/ +.. _Django documentation: http://www.djangoproject.com/documentation/ diff --git a/docs/url_dispatch.txt b/docs/url_dispatch.txt index 39eed0625b..402b1200b5 100644 --- a/docs/url_dispatch.txt +++ b/docs/url_dispatch.txt @@ -551,3 +551,38 @@ not restricted to valid Python names. Putting a prefix on your URL names, perhaps derived from the application name, will decrease the chances of collision. We recommend something like ``myapp-comment`` instead of ``comment``. + +Utility methods +=============== + +reverse() +--------- + +If you need to use something similar to the ``{% url %}`` template tag in your +code, Django provides the ``django.core.urlresolvers.reverse()``. The +``reverse()`` function has the following signature:: + + reverse(viewname, urlconf=None, args=None, kwargs=None) + +``viewname`` is either the function name (either a function reference, or the +string version of the name, if you used that form in ``urlpatterns``) or the +`URL pattern name`_. Normally, you won't need to worry about the +``urlconf`` parameter and will only pass in the positional and keyword +arguments to use in the URL matching. For example:: + + from django.core.urlresolvers import reverse + + def myview(request): + return HttpResponseRedirect(reverse('arch-summary', args=[1945])) + +.. _URL pattern name: `Naming URL patterns`_ + +permalink() +----------- + +The ``permalink()`` decorator is useful for writing short methods that return +a full URL path. For example, a model's ``get_absolute_url()`` method. Refer +to the `model API documentation`_ for more information about ``permalink()``. + +.. _model API documentation: ../model-api/#the-permalink-decorator + -- cgit v1.3