diff options
| author | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2008-03-18 05:45:37 +0000 |
|---|---|---|
| committer | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2008-03-18 05:45:37 +0000 |
| commit | 6df9e25b618b603fb903f9e6c74e675aa2490305 (patch) | |
| tree | c12117aa403438246fa629286ae565ace7e8805e /docs | |
| parent | 133111e40b3afe20e80e5f12e3b064ba080c318d (diff) | |
queryset-refactor: Merged from trunk up to [7280]
git-svn-id: http://code.djangoproject.com/svn/django/branches/queryset-refactor@7281 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'docs')
| -rw-r--r-- | docs/authentication.txt | 26 | ||||
| -rw-r--r-- | docs/contributing.txt | 6 | ||||
| -rw-r--r-- | docs/form_wizard.txt | 304 | ||||
| -rw-r--r-- | docs/i18n.txt | 7 | ||||
| -rw-r--r-- | docs/model-api.txt | 10 | ||||
| -rw-r--r-- | docs/modelforms.txt | 48 | ||||
| -rw-r--r-- | docs/newforms.txt | 2 | ||||
| -rw-r--r-- | docs/settings.txt | 5 | ||||
| -rw-r--r-- | docs/templates.txt | 269 |
9 files changed, 602 insertions, 75 deletions
diff --git a/docs/authentication.txt b/docs/authentication.txt index 5134e90267..9167458db2 100644 --- a/docs/authentication.txt +++ b/docs/authentication.txt @@ -83,12 +83,12 @@ Methods objects in the same way as any other `Django model`_:: myuser.groups = [group_list] - myuser.groups.add(group, group,...) - myuser.groups.remove(group, group,...) + myuser.groups.add(group, group, ...) + myuser.groups.remove(group, group, ...) myuser.groups.clear() myuser.user_permissions = [permission_list] myuser.user_permissions.add(permission, permission, ...) - myuser.user_permissions.remove(permission, permission, ...] + myuser.user_permissions.remove(permission, permission, ...) myuser.user_permissions.clear() In addition to those automatic API methods, ``User`` objects have the following @@ -309,7 +309,7 @@ with that ``User``. For more information, see `Chapter 12 of the Django book`_. -.. _Chapter 12 of the Django book: http://www.djangobook.com/en/beta/chapter12/#cn226 +.. _Chapter 12 of the Django book: http://www.djangobook.com/en/1.0/chapter12/#cn222 Authentication in Web requests ============================== @@ -380,14 +380,14 @@ This example shows how you might use both ``authenticate()`` and ``login()``:: # Return an 'invalid login' error message. .. admonition:: Calling ``authenticate()`` first - + When you're manually logging a user in, you *must* call ``authenticate()`` before you call ``login()``. ``authenticate()`` sets an attribute on the ``User`` noting which authentication backend successfully authenticated that user (see the `backends documentation`_ for details), and this information is needed later during the login process. - + .. _backends documentation: #other-authentication-sources Manually checking a user's password @@ -460,7 +460,7 @@ introduced in Python 2.4:: In the Django development version, ``login_required`` also takes an optional ``redirect_field_name`` parameter. Example:: - + from django.contrib.auth.decorators import login_required def my_view(request): @@ -468,7 +468,7 @@ In the Django development version, ``login_required`` also takes an optional my_view = login_required(redirect_field_name='redirect_to')(my_view) Again, an equivalent example of the more compact decorator syntax introduced in Python 2.4:: - + from django.contrib.auth.decorators import login_required @login_required(redirect_field_name='redirect_to') @@ -479,7 +479,7 @@ Again, an equivalent example of the more compact decorator syntax introduced in * If the user isn't logged in, redirect to ``settings.LOGIN_URL`` (``/accounts/login/`` by default), passing the current absolute URL - in the query string as ``next`` or the value of ``redirect_field_name``. + in the query string as ``next`` or the value of ``redirect_field_name``. For example: ``/accounts/login/?next=/polls/3/``. * If the user is logged in, execute the view normally. The view code is @@ -1119,7 +1119,7 @@ object the first time a user authenticates:: Handling authorization in custom backends ----------------------------------------- -Custom auth backends can provide their own permissions. +Custom auth backends can provide their own permissions. The user model will delegate permission lookup functions (``get_group_permissions()``, ``get_all_permissions()``, ``has_perm()``, and @@ -1132,9 +1132,9 @@ one backend grants. The simple backend above could implement permissions for the magic admin fairly simply:: - + class SettingsBackend: - + # ... def has_perm(self, user_obj, perm): @@ -1142,7 +1142,7 @@ simply:: return True else: return False - + This gives full permissions to the user granted access in the above example. Notice that the backend auth functions all take the user object as an argument, and they also accept the same arguments given to the associated ``User`` functions. diff --git a/docs/contributing.txt b/docs/contributing.txt index 37c9196467..885f5159b9 100644 --- a/docs/contributing.txt +++ b/docs/contributing.txt @@ -328,8 +328,12 @@ incorrect translation, or if you'd like to add a language that isn't yet translated, here's what to do: * Join the `Django i18n mailing list`_ and introduce yourself. - * Create and submit translations using the methods described in the + * Create translations using the methods described in the `i18n documentation`_. + * Create a diff of the ``.po`` file against the current Subversion trunk. + * Make sure that `` bin/compile-messages.py -l <lang>`` runs without + producing any warnings. + * Attach the patch to a ticket in Django's ticket system. .. _Django i18n mailing list: http://groups.google.com/group/django-i18n/ .. _i18n documentation: ../i18n/ diff --git a/docs/form_wizard.txt b/docs/form_wizard.txt new file mode 100644 index 0000000000..cd9e58ded1 --- /dev/null +++ b/docs/form_wizard.txt @@ -0,0 +1,304 @@ +=========== +Form wizard +=========== + +**New in Django development version.** + +Django comes with an optional "form wizard" application that splits forms_ +across multiple Web pages. It maintains state in hashed HTML +``<input type="hidden">`` fields, and the data isn't processed server-side +until the final form is submitted. + +You might want to use this if you have a lengthy form that would be too +unwieldy for display on a single page. The first page might ask the user for +core information, the second page might ask for less important information, +etc. + +The term "wizard," in this context, is `explained on Wikipedia`_. + +.. _explained on Wikipedia: http://en.wikipedia.org/wiki/Wizard_%28software%29 +.. _forms: ../newforms/ + +How it works +============ + +Here's the basic workflow for how a user would use a wizard: + + 1. The user visits the first page of the wizard, fills in the form and + submits it. + 2. The server validates the data. If it's invalid, the form is displayed + again, with error messages. If it's valid, the server calculates a + secure hash of the data and presents the user with the next form, + saving the validated data and hash in ``<input type="hidden">`` fields. + 3. Step 1 and 2 repeat, for every subsequent form in the wizard. + 4. Once the user has submitted all the forms and all the data has been + validated, the wizard processes the data -- saving it to the database, + sending an e-mail, or whatever the application needs to do. + +Usage +===== + +This application handles as much machinery for you as possible. Generally, you +just have to do these things: + + 1. Define a number of ``django.newforms`` ``Form`` classes -- one per wizard + page. + 2. Create a ``FormWizard`` class that specifies what to do once all of your + forms have been submitted and validated. This also lets you override some + of the wizard's behavior. + 3. Create some templates that render the forms. You can define a single, + generic template to handle every one of the forms, or you can define a + specific template for each form. + 4. Point your URLconf at your ``FormWizard`` class. + +Defining ``Form`` classes +========================= + +The first step in creating a form wizard is to create the ``Form`` classes. +These should be standard ``django.newforms`` ``Form`` classes, covered in the +`newforms documentation`_. + +These classes can live anywhere in your codebase, but convention is to put them +in a file called ``forms.py`` in your application. + +For example, let's write a "contact form" wizard, where the first page's form +collects the sender's e-mail address and subject, and the second page collects +the message itself. Here's what the ``forms.py`` might look like:: + + from django import newforms as forms + + class ContactForm1(forms.Form): + subject = forms.CharField(max_length=100) + sender = forms.EmailField() + + class ContactForm2(forms.Form): + message = forms.CharField(widget=forms.Textarea) + +**Important limitation:** Because the wizard uses HTML hidden fields to store +data between pages, you may not include a ``FileField`` in any form except the +last one. + +.. _newforms documentation: ../newforms/ + +Creating a ``FormWizard`` class +=============================== + +The next step is to create a ``FormWizard`` class, which should be a subclass +of ``django.contrib.formtools.wizard.FormWizard``. + +As your ``Form`` classes, this ``FormWizard`` class can live anywhere in your +codebase, but convention is to put it in ``forms.py``. + +The only requirement on this subclass is that it implement a ``done()`` method, +which specifies what should happen when the data for *every* form is submitted +and validated. This method is passed two arguments: + + * ``request`` -- an HttpRequest_ object + * ``form_list`` -- a list of ``django.newforms`` ``Form`` classes + +In this simplistic example, rather than perform any database operation, the +method simply renders a template of the validated data:: + + from django.shortcuts import render_to_response + from django.contrib.formtools.wizard import FormWizard + + class ContactWizard(FormWizard): + def done(self, request, form_list): + return render_to_response('done.html', { + 'form_data': [form.cleaned_data for form in form_list], + }) + +Note that this method will be called via ``POST``, so it really ought to be a +good Web citizen and redirect after processing the data. Here's another +example:: + + from django.http import HttpResponseRedirect + from django.contrib.formtools.wizard import FormWizard + + class ContactWizard(FormWizard): + def done(self, request, form_list): + do_something_with_the_form_data(form_list) + return HttpResponseRedirect('/page-to-redirect-to-when-done/') + +See the section "Advanced ``FormWizard`` methods" below to learn about more +``FormWizard`` hooks. + +.. _HttpRequest: request_response/#httprequest-objects + +Creating templates for the forms +================================ + +Next, you'll need to create a template that renders the wizard's forms. By +default, every form uses a template called ``forms/wizard.html``. (You can +change this template name by overriding ``FormWizard.get_template()``, which is +documented below. This hook also allows you to use a different template for +each form.) + +This template expects the following context: + + * ``step_field`` -- The name of the hidden field containing the step. + * ``step0`` -- The current step (zero-based). + * ``step`` -- The current step (one-based). + * ``step_count`` -- The total number of steps. + * ``form`` -- The ``Form`` instance for the current step (either empty or + with errors). + * ``previous_fields`` -- A string representing every previous data field, + plus hashes for completed forms, all in the form of hidden fields. Note + that you'll need to run this through the ``safe`` template filter, to + prevent auto-escaping, because it's raw HTML. + +It will also be passed any objects in ``extra_context``, which is a dictionary +you can specify that contains extra values to add to the context. You can +specify it in two ways: + + * Set the ``extra_context`` attribute on your ``FormWizard`` subclass to a + dictionary. + + * Pass ``extra_context`` as extra parameters in the URLconf. + +Here's a full example template:: + + {% extends "base.html" %} + + {% block content %} + <p>Step {{ step }} of {{ step_count }}</p> + <form action="." method="post"> + <table> + {{ form }} + </table> + <input type="hidden" name="{{ step_field }}" value="{{ step0 }}" /> + {{ previous_fields|safe }} + <input type="submit"> + </form> + {% endblock %} + +Note that ``previous_fields``, ``step_field`` and ``step0`` are all required +for the wizard to work properly. + +Hooking the wizard into a URLconf +================================= + +Finally, give your new ``FormWizard`` object a URL in ``urls.py``. The wizard +takes a list of your form objects as arguments:: + + from django.conf.urls.defaults import * + from mysite.testapp.forms import ContactForm1, ContactForm2, ContactWizard + + urlpatterns = patterns('', + (r'^contact/$', ContactWizard([ContactForm1, ContactForm2])), + ) + +Advanced ``FormWizard`` methods +=============================== + +Aside from the ``done()`` method, ``FormWizard`` offers a few advanced method +hooks that let you customize how your wizard works. + +Some of these methods take an argument ``step``, which is a zero-based counter +representing the current step of the wizard. (E.g., the first form is ``0`` and +the second form is ``1``.) + +``prefix_for_step`` +~~~~~~~~~~~~~~~~~~~ + +Given the step, returns a ``Form`` prefix to use. By default, this simply uses +the step itself. For more, see the `form prefix documentation`_. + +Default implementation:: + + def prefix_for_step(self, step): + return str(step) + +.. _form prefix documentation: ../newforms/#prefixes-for-forms + +``render_hash_failure`` +~~~~~~~~~~~~~~~~~~~~~~~ + +Renders a template if the hash check fails. It's rare that you'd need to +override this. + +Default implementation:: + + def render_hash_failure(self, request, step): + return self.render(self.get_form(step), request, step, + context={'wizard_error': 'We apologize, but your form has expired. Please continue filling out the form from this page.'}) + +``security_hash`` +~~~~~~~~~~~~~~~~~ + +Calculates the security hash for the given request object and ``Form`` instance. + +By default, this uses an MD5 hash of the form data and your +`SECRET_KEY setting`_. It's rare that somebody would need to override this. + +Example:: + + def security_hash(self, request, form): + return my_hash_function(request, form) + +.. _SECRET_KEY setting: ../settings/#secret-key + +``parse_params`` +~~~~~~~~~~~~~~~~ + +A hook for saving state from the request object and ``args`` / ``kwargs`` that +were captured from the URL by your URLconf. + +By default, this does nothing. + +Example:: + + def parse_params(self, request, *args, **kwargs): + self.my_state = args[0] + +``get_template`` +~~~~~~~~~~~~~~~~ + +Returns the name of the template that should be used for the given step. + +By default, this returns ``'forms/wizard.html'``, regardless of step. + +Example:: + + def get_template(self, step): + return 'myapp/wizard_%s.html' % step + +If ``get_template`` returns a list of strings, then the wizard will use the +template system's ``select_template()`` function, `explained in the template docs`_. +This means the system will use the first template that exists on the filesystem. +For example:: + + def get_template(self, step): + return ['myapp/wizard_%s.html' % step, 'myapp/wizard.html'] + +.. _explained in the template docs: ../templates_python/#the-python-api + +``render_template`` +~~~~~~~~~~~~~~~~~~~ + +Renders the template for the given step, returning an ``HttpResponse`` object. + +Override this method if you want to add a custom context, return a different +MIME type, etc. If you only need to override the template name, use +``get_template()`` instead. + +The template will be rendered with the context documented in the +"Creating templates for the forms" section above. + +``process_step`` +~~~~~~~~~~~~~~~~ + +Hook for modifying the wizard's internal state, given a fully validated ``Form`` +object. The Form is guaranteed to have clean, valid data. + +This method should *not* modify any of that data. Rather, it might want to set +``self.extra_context`` or dynamically alter ``self.form_list``, based on +previously submitted forms. + +Note that this method is called every time a page is rendered for *all* +submitted steps. + +The function signature:: + + def process_step(self, request, form, step): + # ... diff --git a/docs/i18n.txt b/docs/i18n.txt index bb6cf74ded..8da19cd242 100644 --- a/docs/i18n.txt +++ b/docs/i18n.txt @@ -547,7 +547,7 @@ following this algorithm: * First, it looks for a ``django_language`` key in the the current user's `session`_. - * Failing that, it looks for a cookie that is named according to your ``LANGUAGE_COOKIE_NAME`` setting (the default name is: ``django_language``). + * Failing that, it looks for a cookie that is named according to your ``LANGUAGE_COOKIE_NAME`` setting. (The default name is ``django_language``, and this setting is new in the Django development version. In Django version 0.96 and before, the cookie's name is hard-coded to ``django_language``.) * Failing that, it looks at the ``Accept-Language`` HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header @@ -719,8 +719,9 @@ Activate this view by adding the following line to your URLconf:: The view expects to be called via the ``POST`` method, with a ``language`` parameter set in request. If session support is enabled, the view saves the language choice in the user's session. Otherwise, it saves the -language choice in a cookie that is by default named ``django_language`` -(the name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting). +language choice in a cookie that is by default named ``django_language``. +(The name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting if you're +using the Django development version.) After setting the language choice, Django redirects the user, following this algorithm: diff --git a/docs/model-api.txt b/docs/model-api.txt index 2d8d984237..e4d3805236 100644 --- a/docs/model-api.txt +++ b/docs/model-api.txt @@ -788,10 +788,10 @@ Note, however, that this only refers to models in the same models.py file -- you cannot use a string to reference a model defined in another application or imported from elsewhere. -**New in Django development version:** to refer to models defined in another -application, you must instead explicitially specify the application label. That -is, if the ``Manufacturer`` model above is defined in another application called -``production``, you'd need to use:: +**New in Django development version:** To refer to models defined in another +application, you must instead explicitly specify the application label. For +example, if the ``Manufacturer`` model above is defined in another application +called ``production``, you'd need to use:: class Car(models.Model): manufacturer = models.ForeignKey('production.Manufacturer') @@ -1036,6 +1036,8 @@ See the `One-to-one relationship model example`_ for a full example. Custom field types ------------------ +**New in Django development version** + If one of the existing model fields cannot be used to fit your purposes, or if you wish to take advantage of some less common database column types, you can create your own field class. Full coverage of creating your own fields is diff --git a/docs/modelforms.txt b/docs/modelforms.txt index 853fb3159e..47eaa9a769 100644 --- a/docs/modelforms.txt +++ b/docs/modelforms.txt @@ -226,7 +226,7 @@ For example:: # Create a form instance with POST data. >>> a = Author() - >>> f = AuthorForm(a, request.POST) + >>> f = AuthorForm(request.POST, instance=a) # Create and save the new author instance. There's no need to do anything else. >>> new_author = f.save() @@ -238,34 +238,34 @@ In some cases, you may not want all the model fields to appear on the generated form. There are three ways of telling ``ModelForm`` to use only a subset of the model fields: - 1. Set ``editable=False`` on the model field. As a result, *any* form - created from the model via ``ModelForm`` will not include that - field. +1. Set ``editable=False`` on the model field. As a result, *any* form + created from the model via ``ModelForm`` will not include that + field. - 2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta`` class. - This attribute, if given, should be a list of field names to include in - the form. +2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta`` + class. This attribute, if given, should be a list of field names + to include in the form. - 3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta`` class. - This attribute, if given, should be a list of field names to exclude - the form. +3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta`` + class. This attribute, if given, should be a list of field names + to exclude from the form. - For example, if you want a form for the ``Author`` model (defined above) - that includes only the ``name`` and ``title`` fields, you would specify - ``fields`` or ``exclude`` like this:: +For example, if you want a form for the ``Author`` model (defined +above) that includes only the ``name`` and ``title`` fields, you would +specify ``fields`` or ``exclude`` like this:: - class PartialAuthorForm(ModelForm): - class Meta: - model = Author - fields = ('name', 'title') - - class PartialAuthorForm(ModelForm): - class Meta: - model = Author - exclude = ('birth_date',) + class PartialAuthorForm(ModelForm): + class Meta: + model = Author + fields = ('name', 'title') + + class PartialAuthorForm(ModelForm): + class Meta: + model = Author + exclude = ('birth_date',) - Since the Author model has only 3 fields, 'name', 'title', and - 'birth_date', the forms above will contain exactly the same fields. +Since the Author model has only 3 fields, 'name', 'title', and +'birth_date', the forms above will contain exactly the same fields. .. note:: diff --git a/docs/newforms.txt b/docs/newforms.txt index 9d95d88b9f..0b5559ab88 100644 --- a/docs/newforms.txt +++ b/docs/newforms.txt @@ -1564,7 +1564,7 @@ The three types of cleaning methods are: Note that any errors raised by your ``Form.clean()`` override will not be associated with any field in particular. They go into a special - "field" (called ``__all__``, which you can access via the + "field" (called ``__all__``), which you can access via the ``non_field_errors()`` method if you need to. These methods are run in the order given above, one field at a time. That is, diff --git a/docs/settings.txt b/docs/settings.txt index ace893f1b5..77e3c6692f 100644 --- a/docs/settings.txt +++ b/docs/settings.txt @@ -582,13 +582,14 @@ in standard language format. For example, U.S. English is ``"en-us"``. See the LANGUAGE_COOKIE_NAME -------------------- +**New in Django development version** + Default: ``'django_language'`` The name of the cookie to use for the language cookie. This can be whatever -you want (but should be different from SESSION_COOKIE_NAME). See the +you want (but should be different from ``SESSION_COOKIE_NAME``). See the `internationalization docs`_ for details. - LANGUAGES --------- diff --git a/docs/templates.txt b/docs/templates.txt index d473a6f06f..3360b04178 100644 --- a/docs/templates.txt +++ b/docs/templates.txt @@ -1222,14 +1222,20 @@ Built-in filter reference add ~~~ -Adds the arg to the value. +Adds the argument to the value. + +For example:: + + {{ value|add:"2" }} + +If ``value`` is ``4``, then the output will be ``6``. addslashes ~~~~~~~~~~ Adds slashes before quotes. Useful for escaping strings in CSV, for example. -**New in Django development version**: for escaping data in JavaScript strings, +**New in Django development version**: For escaping data in JavaScript strings, use the `escapejs`_ filter instead. capfirst @@ -1247,45 +1253,98 @@ cut Removes all values of arg from the given string. +For example:: + + {{ value|cut:" "}} + +If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``. + date ~~~~ Formats a date according to the given format (same as the `now`_ tag). +For example:: + + {{ value|date:"D d M Y" }} + +If ``value`` is a ``datetime`` object (e.g., the result of +``datetime.datetime.now()``), the output will be the string +``'Wed 09 Jan 2008'``. + default ~~~~~~~ -If value is unavailable, use given default. +If value evaluates to ``False``, use given default. Otherwise, use the value. + +For example:: + + {{ value|default:"nothing" }} + +If ``value`` is ``""`` (the empty string), the output will be ``nothing``. default_if_none ~~~~~~~~~~~~~~~ -If value is ``None``, use given default. +If (and only if) value is ``None``, use given default. Otherwise, use the +value. + +Note that if an empty string is given, the default value will *not* be used. +Use the ``default`` filter if you want to fallback for empty strings. + +For example:: + + {{ value|default_if_none:"nothing" }} + +If ``value`` is ``None``, the output will be the string ``"nothing"``. dictsort ~~~~~~~~ -Takes a list of dictionaries, returns that list sorted by the key given in +Takes a list of dictionaries and returns that list sorted by the key given in the argument. +For example:: + + {{ value|dictsort:"name" }} + +If ``value`` is:: + + [ + {'name': 'zed', 'age': 19}, + {'name': 'amy', 'age': 22}, + {'name': 'joe', 'age': 31}, + ] + +then the output would be:: + + [ + {'name': 'amy', 'age': 22}, + {'name': 'joe', 'age': 31}, + {'name': 'zed', 'age': 19}, + ] + dictsortreversed ~~~~~~~~~~~~~~~~ -Takes a list of dictionaries, returns that list sorted in reverse order by the -key given in the argument. +Takes a list of dictionaries and returns that list sorted in reverse order by +the key given in the argument. This works exactly the same as the above filter, +but the returned value will be in reverse order. divisibleby ~~~~~~~~~~~ -Returns true if the value is divisible by the argument. +Returns ``True`` if the value is divisible by the argument. + +For example:: + + {{ value|divisibleby:"3" }} + +If ``value`` is ``21``, the output would be ``True``. escape ~~~~~~ -**New in Django development version:** The behaviour of this filter has -changed slightly in the development version (the affects are only applied -once, after all other filters). - Escapes a string's HTML. Specifically, it makes these replacements: * ``<`` is converted to ``<`` @@ -1304,6 +1363,10 @@ applied to the result will only result in one round of escaping being done. So it is safe to use this function even in auto-escaping environments. If you want multiple escaping passes to be applied, use the ``force_escape`` filter. +**New in Django development version:** Due to auto-escaping, the behavior of +this filter has changed slightly. The replacements are only made once, after +all other filters are applied -- including filters before and after it. + escapejs ~~~~~~~~ @@ -1319,16 +1382,38 @@ filesizeformat Format the value like a 'human-readable' file size (i.e. ``'13 KB'``, ``'4.1 MB'``, ``'102 bytes'``, etc). +For example:: + + {{ value|filesizeformat }} + +If ``value`` is 123456789, the output would be ``117.7 MB``. + first ~~~~~ Returns the first item in a list. +For example:: + + {{ value|first }} + +If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``. + fix_ampersands ~~~~~~~~~~~~~~ Replaces ampersands with ``&`` entities. +For example:: + + {{ value|fix_ampersands }} + +If ``value`` is ``Tom & Jerry``, the output will be ``Tom & Jerry``. + +**New in Django development version**: This filter generally is no longer +useful, because ampersands are automatically escaped in templates. See escape_ +for more on how auto-escaping works. + floatformat ~~~~~~~~~~~ @@ -1383,10 +1468,16 @@ filter. get_digit ~~~~~~~~~ -Given a whole number, returns the requested digit of it, where 1 is the -right-most digit, 2 is the second-right-most digit, etc. Returns the original -value for invalid input (if input or argument is not an integer, or if argument -is less than 1). Otherwise, output is always an integer. +Given a whole number, returns the requested digit, where 1 is the right-most +digit, 2 is the second-right-most digit, etc. Returns the original value for +invalid input (if input or argument is not an integer, or if argument is less +than 1). Otherwise, output is always an integer. + +For example:: + + {{ value|get_digit:"2" }} + +If ``value`` is ``123456789``, the output will be ``8``. iriencode ~~~~~~~~~ @@ -1401,7 +1492,14 @@ It's safe to use this filter on a string that has already gone through the join ~~~~ -Joins a list with a string, like Python's ``str.join(list)``. +Joins a list with a string, like Python's ``str.join(list)`` + +For example:: + + {{ value|join:" // " }} + +If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string +``"a // b // c"``. last ~~~~ @@ -1410,15 +1508,34 @@ last Returns the last item in a list. +For example:: + + {{ value|last }} + +If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string +``"d"``. + length ~~~~~~ -Returns the length of the value. Useful for lists. +Returns the length of the value. This works for both strings and lists. + +For example:: + + {{ value|length }} + +If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``. length_is ~~~~~~~~~ -Returns a boolean of whether the value's length is the argument. +Returns ``True`` if the value's length is the argument, or ``False`` otherwise. + +For example:: + + {{ value|length_is:"4" }} + +If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``. linebreaks ~~~~~~~~~~ @@ -1427,6 +1544,13 @@ Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br />``) and a new line followed by a blank line becomes a paragraph break (``</p>``). +For example:: + + {{ value|linebreaks }} + +If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joe<br>is a +slug</p>``. + linebreaksbr ~~~~~~~~~~~~ @@ -1450,12 +1574,26 @@ lower Converts a string into all lowercase. +For example:: + + {{ value|lower }} + +If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``. + make_list ~~~~~~~~~ Returns the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. +For example:: + + {{ value|make_list }} + +If ``value`` is the string ``"Joe"``, the output would be the list +``[u'J', u'o', u'e']``. If ``value`` is ``123``, the output will be the list +``[1, 2, 3]``. + phone2numeric ~~~~~~~~~~~~~ @@ -1492,17 +1630,32 @@ Example:: pprint ~~~~~~ -A wrapper around pprint.pprint -- for debugging, really. +A wrapper around `pprint.pprint`__ -- for debugging, really. + +__ http://www.python.org/doc/2.5/lib/module-pprint.html random ~~~~~~ -Returns a random item from the list. +Returns a random item from the given list. + +For example:: + + {{ value|random }} + +If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``. removetags ~~~~~~~~~~ -Removes a space separated list of [X]HTML tags from the output. +Removes a space-separated list of [X]HTML tags from the output. + +For example:: + + {{ value|removetags:"b span"|safe }} + +If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the +output will be ``"Joel <button>is</button> a slug"``. rjust ~~~~~ @@ -1535,6 +1688,12 @@ Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. +For example:: + + {{ value|slugify }} + +If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``. + stringformat ~~~~~~~~~~~~ @@ -1545,11 +1704,24 @@ the leading "%" is dropped. See http://docs.python.org/lib/typesseq-strings.html for documentation of Python string formatting +For example:: + + {{ value|stringformat:"s" }} + +If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is a slug"``. + striptags ~~~~~~~~~ Strips all [X]HTML tags. +For example:: + + {{ value|striptags }} + +If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the +output will be ``"Joel is a slug"``. + time ~~~~ @@ -1558,10 +1730,17 @@ The time filter will only accept parameters in the format string that relate to the time of day, not the date (for obvious reasons). If you need to format a date, use the `date`_ filter. +For example:: + + {{ value|time:"H:i" }} + +If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be +the string ``"01:23"``. + timesince ~~~~~~~~~ -Formats a date as the time since that date (i.e. "4 days, 6 hours"). +Formats a date as the time since that date (e.g., "4 days, 6 hours"). Takes an optional argument that is a variable containing the date to use as the comparison point (without the argument, the comparison point is *now*). @@ -1599,6 +1778,12 @@ Truncates a string after a certain number of words. **Argument:** Number of words to truncate after +For example:: + + {{ value|truncatewords:2 }} + +If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is ..."``. + truncatewords_html ~~~~~~~~~~~~~~~~~~ @@ -1615,10 +1800,8 @@ unordered_list Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> tags. -**Changed in Django development version** - -The format accepted by ``unordered_list`` has changed to an easier to -understand format. +**New in Django development version:** The format accepted by +``unordered_list`` has changed to be easier to understand. The list is assumed to be in the proper format. For example, if ``var`` contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then @@ -1644,6 +1827,12 @@ upper Converts a string into all uppercase. +For example:: + + {{ value|upper }} + +If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``. + urlencode ~~~~~~~~~ @@ -1657,6 +1846,14 @@ Converts URLs in plain text into clickable links. Note that if ``urlize`` is applied to text that already contains HTML markup, things won't work as expected. Apply this filter only to *plain* text. +For example:: + + {{ value|urlize }} + +If ``value`` is ``"Check out www.djangoproject.com"``, the output will be +``"Check out <a +href="http://www.djangoproject.com">www.djangoproject.com</a>"``. + urlizetrunc ~~~~~~~~~~~ @@ -1667,6 +1864,14 @@ As with urlize_, this filter should only be applied to *plain* text. **Argument:** Length to truncate URLs to +For example:: + + {{ value|urlizetrunc:15 }} + +If ``value`` is ``"Check out www.djangoproject.com"``, the output would be +``'Check out <a +href="http://www.djangoproject.com">www.djangopr...</a>'``. + wordcount ~~~~~~~~~ @@ -1679,6 +1884,16 @@ Wraps words at specified line length. **Argument:** number of characters at which to wrap the text +For example:: + + {{ value|wordwrap:5 }} + +If ``value`` is ``Joel is a slug``, the output would be:: + + Joel + is a + slug + yesno ~~~~~ |
