forms.Field.get_bound_field()

Field.get_bound_field(form, field_name) [source]

Takes an instance of 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 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 }}.

doc_Django
2016-10-09 18:36:45
Comments
Leave a Comment

Please login to continue.