From 535809e12161d28dacaf5161436fc05a9bb064aa Mon Sep 17 00:00:00 2001 From: Moritz Sichert Date: Mon, 10 Aug 2015 10:55:49 +0200 Subject: Fixed #25294 -- Allowed custom BoundFields on forms. --- docs/ref/forms/api.txt | 42 ++++++++++++++++++++++++++++++++++++++++++ docs/ref/forms/fields.txt | 3 +++ 2 files changed, 45 insertions(+) (limited to 'docs/ref/forms') diff --git a/docs/ref/forms/api.txt b/docs/ref/forms/api.txt index 16e8443361..ca9e4d868f 100644 --- a/docs/ref/forms/api.txt +++ b/docs/ref/forms/api.txt @@ -932,6 +932,48 @@ and using the template above, would render something like: +Customizing ``BoundField`` +-------------------------- + +.. versionadded:: 1.9 + +If you need to access some additional information about a form field in a +template and using a subclass of :class:`~django.forms.Field` isn't +sufficient, consider also customizing :class:`~django.forms.BoundField`. + +A custom form field can override ``get_bound_field()``: + +.. method:: Field.get_bound_field(form, field_name) + + Takes an instance of :class:`~django.forms.Form` and the name of the field. + The return value will be used when accessing the field in a template. Most + likely it will be an instance of a subclass of + :class:`~django.forms.BoundField`. + +If you have a ``GPSCoordinatesField``, for example, and want to be able to +access additional information about the coordinates in a template, this could +be implemented as follows:: + + class GPSCoordinatesBoundField(BoundField): + @property + def country(self): + """ + Return the country the coordinates lie in or None if it can't be + determined. + """ + value = self.value() + if value: + return get_country_from_coordinates(value) + else: + return None + + class GPSCoordinatesField(Field): + def get_bound_field(self, form, field_name): + return GPSCoordinatesBoundField(form, self, field_name) + +Now you can access the country in a template with +``{{ form.coordinates.country }}``. + .. _binding-uploaded-files: Binding uploaded files to a form diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt index 88c35829c0..ac7c6400ae 100644 --- a/docs/ref/forms/fields.txt +++ b/docs/ref/forms/fields.txt @@ -1239,3 +1239,6 @@ custom ``Field`` classes. To do this, just create a subclass of ``clean()`` method and that its ``__init__()`` method accept the core arguments mentioned above (``required``, ``label``, ``initial``, ``widget``, ``help_text``). + +You can also customize how a field will be accessed by overriding +:meth:`~django.forms.Field.get_bound_field()`. -- cgit v1.3