doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
class RegexField(**kwargs) Default widget: TextInput Empty value: Whatever you’ve given as empty_value. Normalizes to: A string. Uses RegexValidator to validate that the given value matches a certain regular expression. Error message keys: required, invalid Takes one required argument: regex A regular expression specified either as a string or a compiled regular expression object. Also takes max_length, min_length, strip, and empty_value which work just as they do for CharField. strip Defaults to False. If enabled, stripping will be applied before the regex validation.
django.ref.forms.fields#django.forms.RegexField
regex A regular expression specified either as a string or a compiled regular expression object.
django.ref.forms.fields#django.forms.RegexField.regex
strip Defaults to False. If enabled, stripping will be applied before the regex validation.
django.ref.forms.fields#django.forms.RegexField.strip
class DjangoTemplates
django.ref.forms.renderers#django.forms.renderers.DjangoTemplates
class Jinja2
django.ref.forms.renderers#django.forms.renderers.Jinja2
class TemplatesSetting
django.ref.forms.renderers#django.forms.renderers.TemplatesSetting
class Select template_name: 'django/forms/widgets/select.html' option_template_name: 'django/forms/widgets/select_option.html' Renders as: <select><option ...>...</select> choices This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the Field.
django.ref.forms.widgets#django.forms.Select
choices This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the Field.
django.ref.forms.widgets#django.forms.Select.choices
class SelectDateWidget template_name: 'django/forms/widgets/select_date.html' Wrapper around three Select widgets: one each for month, day, and year. Takes several optional arguments: years An optional list/tuple of years to use in the “year” select box. The default is a list containing the current year and the next 9 years. months An optional dict of months to use in the “months” select box. The keys of the dict correspond to the month number (1-indexed) and the values are the displayed months: MONTHS = { 1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'), 5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'), 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec') } empty_label If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label'). # A custom empty label with string field1 = forms.DateField(widget=SelectDateWidget(empty_label="Nothing")) # A custom empty label with tuple field1 = forms.DateField( widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), )
django.ref.forms.widgets#django.forms.SelectDateWidget
empty_label If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label'). # A custom empty label with string field1 = forms.DateField(widget=SelectDateWidget(empty_label="Nothing")) # A custom empty label with tuple field1 = forms.DateField( widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), )
django.ref.forms.widgets#django.forms.SelectDateWidget.empty_label
months An optional dict of months to use in the “months” select box. The keys of the dict correspond to the month number (1-indexed) and the values are the displayed months: MONTHS = { 1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'), 5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'), 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec') }
django.ref.forms.widgets#django.forms.SelectDateWidget.months
years An optional list/tuple of years to use in the “year” select box. The default is a list containing the current year and the next 9 years.
django.ref.forms.widgets#django.forms.SelectDateWidget.years
class SelectMultiple template_name: 'django/forms/widgets/select.html' option_template_name: 'django/forms/widgets/select_option.html' Similar to Select, but allows multiple selection: <select multiple>...</select>
django.ref.forms.widgets#django.forms.SelectMultiple
class SlugField(**kwargs) Default widget: TextInput Empty value: Whatever you’ve given as empty_value. Normalizes to: A string. Uses validate_slug or validate_unicode_slug to validate that the given value contains only letters, numbers, underscores, and hyphens. Error messages: required, invalid This field is intended for use in representing a model SlugField in forms. Takes two optional parameters: allow_unicode A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to False. empty_value The value to use to represent “empty”. Defaults to an empty string.
django.ref.forms.fields#django.forms.SlugField
allow_unicode A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to False.
django.ref.forms.fields#django.forms.SlugField.allow_unicode
empty_value The value to use to represent “empty”. Defaults to an empty string.
django.ref.forms.fields#django.forms.SlugField.empty_value
class SplitDateTimeField(**kwargs) Default widget: SplitDateTimeWidget Empty value: None Normalizes to: A Python datetime.datetime object. Validates that the given value is a datetime.datetime or string formatted in a particular datetime format. Error message keys: required, invalid, invalid_date, invalid_time Takes two optional arguments: input_date_formats A list of formats used to attempt to convert a string to a valid datetime.date object. If no input_date_formats argument is provided, the default input formats for DateField are used. input_time_formats A list of formats used to attempt to convert a string to a valid datetime.time object. If no input_time_formats argument is provided, the default input formats for TimeField are used.
django.ref.forms.fields#django.forms.SplitDateTimeField
input_date_formats A list of formats used to attempt to convert a string to a valid datetime.date object.
django.ref.forms.fields#django.forms.SplitDateTimeField.input_date_formats
input_time_formats A list of formats used to attempt to convert a string to a valid datetime.time object.
django.ref.forms.fields#django.forms.SplitDateTimeField.input_time_formats
class SplitDateTimeWidget template_name: 'django/forms/widgets/splitdatetime.html' Wrapper (using MultiWidget) around two widgets: DateInput for the date, and TimeInput for the time. Must be used with SplitDateTimeField rather than DateTimeField. SplitDateTimeWidget has several optional arguments: date_format Similar to DateInput.format time_format Similar to TimeInput.format date_attrs time_attrs Similar to Widget.attrs. A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren’t set, Widget.attrs is used instead.
django.ref.forms.widgets#django.forms.SplitDateTimeWidget
date_attrs
django.ref.forms.widgets#django.forms.SplitDateTimeWidget.date_attrs
date_format Similar to DateInput.format
django.ref.forms.widgets#django.forms.SplitDateTimeWidget.date_format
time_attrs Similar to Widget.attrs. A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren’t set, Widget.attrs is used instead.
django.ref.forms.widgets#django.forms.SplitDateTimeWidget.time_attrs
time_format Similar to TimeInput.format
django.ref.forms.widgets#django.forms.SplitDateTimeWidget.time_format
class SplitHiddenDateTimeWidget template_name: 'django/forms/widgets/splithiddendatetime.html' Similar to SplitDateTimeWidget, but uses HiddenInput for both date and time.
django.ref.forms.widgets#django.forms.SplitHiddenDateTimeWidget
class Textarea template_name: 'django/forms/widgets/textarea.html' Renders as: <textarea>...</textarea>
django.ref.forms.widgets#django.forms.Textarea
class TextInput input_type: 'text' template_name: 'django/forms/widgets/text.html' Renders as: <input type="text" ...>
django.ref.forms.widgets#django.forms.TextInput
class TimeField(**kwargs) Default widget: TimeInput Empty value: None Normalizes to: A Python datetime.time object. Validates that the given value is either a datetime.time or string formatted in a particular time format. Error message keys: required, invalid Takes one optional argument: input_formats A list of formats used to attempt to convert a string to a valid datetime.time object. If no input_formats argument is provided, the default input formats are taken from TIME_INPUT_FORMATS if USE_L10N is False, or from the active locale format TIME_INPUT_FORMATS key if localization is enabled. See also format localization.
django.ref.forms.fields#django.forms.TimeField
input_formats A list of formats used to attempt to convert a string to a valid datetime.time object.
django.ref.forms.fields#django.forms.TimeField.input_formats
class TimeInput input_type: 'text' template_name: 'django/forms/widgets/time.html' Renders as: <input type="text" ...> Takes same arguments as TextInput, with one more optional argument: format The format in which this field’s initial value will be displayed. If no format argument is provided, the default format is the first format found in TIME_INPUT_FORMATS and respects Format localization. For the treatment of microseconds, see DateTimeInput.
django.ref.forms.widgets#django.forms.TimeInput
format The format in which this field’s initial value will be displayed.
django.ref.forms.widgets#django.forms.TimeInput.format
class TypedChoiceField(**kwargs) Just like a ChoiceField, except TypedChoiceField takes two extra arguments, coerce and empty_value. Default widget: Select Empty value: Whatever you’ve given as empty_value. Normalizes to: A value of the type provided by the coerce argument. Validates that the given value exists in the list of choices and can be coerced. Error message keys: required, invalid_choice Takes extra arguments: coerce A function that takes one argument and returns a coerced value. Examples include the built-in int, float, bool and other types. Defaults to an identity function. Note that coercion happens after input validation, so it is possible to coerce to a value not present in choices. empty_value The value to use to represent “empty.” Defaults to the empty string; None is another common choice here. Note that this value will not be coerced by the function given in the coerce argument, so choose it accordingly.
django.ref.forms.fields#django.forms.TypedChoiceField
coerce A function that takes one argument and returns a coerced value. Examples include the built-in int, float, bool and other types. Defaults to an identity function. Note that coercion happens after input validation, so it is possible to coerce to a value not present in choices.
django.ref.forms.fields#django.forms.TypedChoiceField.coerce
empty_value The value to use to represent “empty.” Defaults to the empty string; None is another common choice here. Note that this value will not be coerced by the function given in the coerce argument, so choose it accordingly.
django.ref.forms.fields#django.forms.TypedChoiceField.empty_value
class TypedMultipleChoiceField(**kwargs) Just like a MultipleChoiceField, except TypedMultipleChoiceField takes two extra arguments, coerce and empty_value. Default widget: SelectMultiple Empty value: Whatever you’ve given as empty_value Normalizes to: A list of values of the type provided by the coerce argument. Validates that the given values exists in the list of choices and can be coerced. Error message keys: required, invalid_choice The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice. Takes two extra arguments, coerce and empty_value, as for TypedChoiceField.
django.ref.forms.fields#django.forms.TypedMultipleChoiceField
class URLField(**kwargs) Default widget: URLInput Empty value: Whatever you’ve given as empty_value. Normalizes to: A string. Uses URLValidator to validate that the given value is a valid URL. Error message keys: required, invalid Has three optional arguments max_length, min_length, and empty_value which work just as they do for CharField.
django.ref.forms.fields#django.forms.URLField
class URLInput input_type: 'url' template_name: 'django/forms/widgets/url.html' Renders as: <input type="url" ...>
django.ref.forms.widgets#django.forms.URLInput
class UUIDField(**kwargs) Default widget: TextInput Empty value: None Normalizes to: A UUID object. Error message keys: required, invalid This field will accept any string format accepted as the hex argument to the UUID constructor.
django.ref.forms.fields#django.forms.UUIDField
class Widget(attrs=None) This abstract class cannot be rendered, but provides the basic attribute attrs. You may also implement or override the render() method on custom widgets. attrs A dictionary containing HTML attributes to be set on the rendered widget. >>> from django import forms >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name'}) >>> name.render('name', 'A name') '<input title="Your name" type="text" name="name" value="A name" size="10">' If you assign a value of True or False to an attribute, it will be rendered as an HTML5 boolean attribute: >>> name = forms.TextInput(attrs={'required': True}) >>> name.render('name', 'A name') '<input name="name" type="text" value="A name" required>' >>> >>> name = forms.TextInput(attrs={'required': False}) >>> name.render('name', 'A name') '<input name="name" type="text" value="A name">' supports_microseconds An attribute that defaults to True. If set to False, the microseconds part of datetime and time values will be set to 0. format_value(value) Cleans and returns a value for use in the widget template. value isn’t guaranteed to be valid input, therefore subclass implementations should program defensively. get_context(name, value, attrs) Returns a dictionary of values to use when rendering the widget template. By default, the dictionary contains a single key, 'widget', which is a dictionary representation of the widget containing the following keys: 'name': The name of the field from the name argument. 'is_hidden': A boolean indicating whether or not this widget is hidden. 'required': A boolean indicating whether or not the field for this widget is required. 'value': The value as returned by format_value(). 'attrs': HTML attributes to be set on the rendered widget. The combination of the attrs attribute and the attrs argument. 'template_name': The value of self.template_name. Widget subclasses can provide custom context values by overriding this method. id_for_label(id_) Returns the HTML ID attribute of this widget for use by a <label>, given the ID of the field. Returns None if an ID isn’t available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget’s tags. render(name, value, attrs=None, renderer=None) Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the FORM_RENDERER setting is used. value_from_datadict(data, files, name) Given a dictionary of data and this widget’s name, returns the value of this widget. files may contain data coming from request.FILES. Returns None if a value wasn’t provided. Note also that value_from_datadict may be called more than once during handling of form data, so if you customize it and add expensive processing, you should implement some caching mechanism yourself. value_omitted_from_data(data, files, name) Given data and files dictionaries and this widget’s name, returns whether or not there’s data or files for the widget. The method’s result affects whether or not a field in a model form falls back to its default. Special cases are CheckboxInput, CheckboxSelectMultiple, and SelectMultiple, which always return False because an unchecked checkbox and unselected <select multiple> don’t appear in the data of an HTML form submission, so it’s unknown whether or not the user submitted a value. use_required_attribute(initial) Given a form field’s initial value, returns whether or not the widget can be rendered with the required HTML attribute. Forms use this method along with Field.required and Form.use_required_attribute to determine whether or not to display the required attribute for each field. By default, returns False for hidden widgets and True otherwise. Special cases are FileInput and ClearableFileInput, which return False when initial is set, and CheckboxSelectMultiple, which always returns False because browser validation would require all checkboxes to be checked instead of at least one. Override this method in custom widgets that aren’t compatible with browser validation. For example, a WSYSIWG text editor widget backed by a hidden textarea element may want to always return False to avoid browser validation on the hidden field.
django.ref.forms.widgets#django.forms.Widget
attrs A dictionary containing HTML attributes to be set on the rendered widget. >>> from django import forms >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name'}) >>> name.render('name', 'A name') '<input title="Your name" type="text" name="name" value="A name" size="10">' If you assign a value of True or False to an attribute, it will be rendered as an HTML5 boolean attribute: >>> name = forms.TextInput(attrs={'required': True}) >>> name.render('name', 'A name') '<input name="name" type="text" value="A name" required>' >>> >>> name = forms.TextInput(attrs={'required': False}) >>> name.render('name', 'A name') '<input name="name" type="text" value="A name">'
django.ref.forms.widgets#django.forms.Widget.attrs
format_value(value) Cleans and returns a value for use in the widget template. value isn’t guaranteed to be valid input, therefore subclass implementations should program defensively.
django.ref.forms.widgets#django.forms.Widget.format_value
get_context(name, value, attrs) Returns a dictionary of values to use when rendering the widget template. By default, the dictionary contains a single key, 'widget', which is a dictionary representation of the widget containing the following keys: 'name': The name of the field from the name argument. 'is_hidden': A boolean indicating whether or not this widget is hidden. 'required': A boolean indicating whether or not the field for this widget is required. 'value': The value as returned by format_value(). 'attrs': HTML attributes to be set on the rendered widget. The combination of the attrs attribute and the attrs argument. 'template_name': The value of self.template_name. Widget subclasses can provide custom context values by overriding this method.
django.ref.forms.widgets#django.forms.Widget.get_context
id_for_label(id_) Returns the HTML ID attribute of this widget for use by a <label>, given the ID of the field. Returns None if an ID isn’t available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget’s tags.
django.ref.forms.widgets#django.forms.Widget.id_for_label
render(name, value, attrs=None, renderer=None) Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the FORM_RENDERER setting is used.
django.ref.forms.widgets#django.forms.Widget.render
supports_microseconds An attribute that defaults to True. If set to False, the microseconds part of datetime and time values will be set to 0.
django.ref.forms.widgets#django.forms.Widget.supports_microseconds
use_required_attribute(initial) Given a form field’s initial value, returns whether or not the widget can be rendered with the required HTML attribute. Forms use this method along with Field.required and Form.use_required_attribute to determine whether or not to display the required attribute for each field. By default, returns False for hidden widgets and True otherwise. Special cases are FileInput and ClearableFileInput, which return False when initial is set, and CheckboxSelectMultiple, which always returns False because browser validation would require all checkboxes to be checked instead of at least one. Override this method in custom widgets that aren’t compatible with browser validation. For example, a WSYSIWG text editor widget backed by a hidden textarea element may want to always return False to avoid browser validation on the hidden field.
django.ref.forms.widgets#django.forms.Widget.use_required_attribute
value_from_datadict(data, files, name) Given a dictionary of data and this widget’s name, returns the value of this widget. files may contain data coming from request.FILES. Returns None if a value wasn’t provided. Note also that value_from_datadict may be called more than once during handling of form data, so if you customize it and add expensive processing, you should implement some caching mechanism yourself.
django.ref.forms.widgets#django.forms.Widget.value_from_datadict
value_omitted_from_data(data, files, name) Given data and files dictionaries and this widget’s name, returns whether or not there’s data or files for the widget. The method’s result affects whether or not a field in a model form falls back to its default. Special cases are CheckboxInput, CheckboxSelectMultiple, and SelectMultiple, which always return False because an unchecked checkbox and unselected <select multiple> don’t appear in the data of an HTML form submission, so it’s unknown whether or not the user submitted a value.
django.ref.forms.widgets#django.forms.Widget.value_omitted_from_data
Formsets class BaseFormSet A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let’s say you have the following form: >>> from django import forms >>> class ArticleForm(forms.Form): ... title = forms.CharField() ... pub_date = forms.DateField() You might want to allow the user to create several articles at once. To create a formset out of an ArticleForm you would do: >>> from django.forms import formset_factory >>> ArticleFormSet = formset_factory(ArticleForm) You now have created a formset class named ArticleFormSet. Instantiating the formset gives you the ability to iterate over the forms in the formset and display them as you would with a regular form: >>> formset = ArticleFormSet() >>> for form in formset: ... print(form.as_table()) <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr> As you can see it only displayed one empty form. The number of empty forms that is displayed is controlled by the extra parameter. By default, formset_factory() defines one extra form; the following example will create a formset class to display two blank forms: >>> ArticleFormSet = formset_factory(ArticleForm, extra=2) Iterating over a formset will render the forms in the order they were created. You can change this order by providing an alternate implementation for the __iter__() method. Formsets can also be indexed into, which returns the corresponding form. If you override __iter__, you will need to also override __getitem__ to have matching behavior. Using initial data with a formset Initial data is what drives the main usability of a formset. As shown above you can define the number of extra forms. What this means is that you are telling the formset how many additional forms to show in addition to the number of forms it generates from the initial data. Let’s take a look at an example: >>> import datetime >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, extra=2) >>> formset = ArticleFormSet(initial=[ ... {'title': 'Django is now open source', ... 'pub_date': datetime.date.today(),} ... ]) >>> for form in formset: ... print(form.as_table()) <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title"></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-12" id="id_form-0-pub_date"></td></tr> <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" id="id_form-1-title"></td></tr> <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" id="id_form-1-pub_date"></td></tr> <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr> <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr> There are now a total of three forms showing above. One for the initial data that was passed in and two extra forms. Also note that we are passing in a list of dictionaries as the initial data. If you use an initial for displaying a formset, you should pass the same initial when processing that formset’s submission so that the formset can detect which forms were changed by the user. For example, you might have something like: ArticleFormSet(request.POST, initial=[...]). See also Creating formsets from models with model formsets. Limiting the maximum number of forms The max_num parameter to formset_factory() gives you the ability to limit the number of forms the formset will display: >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1) >>> formset = ArticleFormSet() >>> for form in formset: ... print(form.as_table()) <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr> If the value of max_num is greater than the number of existing items in the initial data, up to extra additional blank forms will be added to the formset, so long as the total number of forms does not exceed max_num. For example, if extra=2 and max_num=2 and the formset is initialized with one initial item, a form for the initial item and one blank form will be displayed. If the number of items in the initial data exceeds max_num, all initial data forms will be displayed regardless of the value of max_num and no extra forms will be displayed. For example, if extra=3 and max_num=1 and the formset is initialized with two initial items, two forms with the initial data will be displayed. A max_num value of None (the default) puts a high limit on the number of forms displayed (1000). In practice this is equivalent to no limit. By default, max_num only affects how many forms are displayed and does not affect validation. If validate_max=True is passed to the formset_factory(), then max_num will affect validation. See validate_max. Limiting the maximum number of instantiated forms New in Django 3.2. The absolute_max parameter to formset_factory() allows limiting the number of forms that can be instantiated when supplying POST data. This protects against memory exhaustion attacks using forged POST requests: >>> from django.forms.formsets import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, absolute_max=1500) >>> data = { ... 'form-TOTAL_FORMS': '1501', ... 'form-INITIAL_FORMS': '0', ... } >>> formset = ArticleFormSet(data) >>> len(formset.forms) 1500 >>> formset.is_valid() False >>> formset.non_form_errors() ['Please submit at most 1000 forms.'] When absolute_max is None, it defaults to max_num + 1000. (If max_num is None, it defaults to 2000). If absolute_max is less than max_num, a ValueError will be raised. Formset validation Validation with a formset is almost identical to a regular Form. There is an is_valid method on the formset to provide a convenient way to validate all forms in the formset: >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm) >>> data = { ... 'form-TOTAL_FORMS': '1', ... 'form-INITIAL_FORMS': '0', ... } >>> formset = ArticleFormSet(data) >>> formset.is_valid() True We passed in no data to the formset which is resulting in a valid form. The formset is smart enough to ignore extra forms that were not changed. If we provide an invalid article: >>> data = { ... 'form-TOTAL_FORMS': '2', ... 'form-INITIAL_FORMS': '0', ... 'form-0-title': 'Test', ... 'form-0-pub_date': '1904-06-16', ... 'form-1-title': 'Test', ... 'form-1-pub_date': '', # <-- this date is missing but required ... } >>> formset = ArticleFormSet(data) >>> formset.is_valid() False >>> formset.errors [{}, {'pub_date': ['This field is required.']}] As we can see, formset.errors is a list whose entries correspond to the forms in the formset. Validation was performed for each of the two forms, and the expected error message appears for the second item. Just like when using a normal Form, each field in a formset’s forms may include HTML attributes such as maxlength for browser validation. However, form fields of formsets won’t include the required attribute as that validation may be incorrect when adding and deleting forms. BaseFormSet.total_error_count() To check how many errors there are in the formset, we can use the total_error_count method: >>> # Using the previous example >>> formset.errors [{}, {'pub_date': ['This field is required.']}] >>> len(formset.errors) 2 >>> formset.total_error_count() 1 We can also check if form data differs from the initial data (i.e. the form was sent without any data): >>> data = { ... 'form-TOTAL_FORMS': '1', ... 'form-INITIAL_FORMS': '0', ... 'form-0-title': '', ... 'form-0-pub_date': '', ... } >>> formset = ArticleFormSet(data) >>> formset.has_changed() False Understanding the ManagementForm You may have noticed the additional data (form-TOTAL_FORMS, form-INITIAL_FORMS) that was required in the formset’s data above. This data is required for the ManagementForm. This form is used by the formset to manage the collection of forms contained in the formset. If you don’t provide this management data, the formset will be invalid: >>> data = { ... 'form-0-title': 'Test', ... 'form-0-pub_date': '', ... } >>> formset = ArticleFormSet(data) >>> formset.is_valid() False It is used to keep track of how many form instances are being displayed. If you are adding new forms via JavaScript, you should increment the count fields in this form as well. On the other hand, if you are using JavaScript to allow deletion of existing objects, then you need to ensure the ones being removed are properly marked for deletion by including form-#-DELETE in the POST data. It is expected that all forms are present in the POST data regardless. The management form is available as an attribute of the formset itself. When rendering a formset in a template, you can include all the management data by rendering {{ my_formset.management_form }} (substituting the name of your formset as appropriate). Note As well as the form-TOTAL_FORMS and form-INITIAL_FORMS fields shown in the examples here, the management form also includes form-MIN_NUM_FORMS and form-MAX_NUM_FORMS fields. They are output with the rest of the management form, but only for the convenience of client-side code. These fields are not required and so are not shown in the example POST data. Changed in Django 3.2: formset.is_valid() now returns False rather than raising an exception when the management form is missing or has been tampered with. total_form_count and initial_form_count BaseFormSet has a couple of methods that are closely related to the ManagementForm, total_form_count and initial_form_count. total_form_count returns the total number of forms in this formset. initial_form_count returns the number of forms in the formset that were pre-filled, and is also used to determine how many forms are required. You will probably never need to override either of these methods, so please be sure you understand what they do before doing so. empty_form BaseFormSet provides an additional attribute empty_form which returns a form instance with a prefix of __prefix__ for easier use in dynamic forms with JavaScript. error_messages New in Django 3.2. The error_messages argument lets you override the default messages that the formset will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message when the management form is missing: >>> formset = ArticleFormSet({}) >>> formset.is_valid() False >>> formset.non_form_errors() ['ManagementForm data is missing or has been tampered with. Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. You may need to file a bug report if the issue persists.'] And here is a custom error message: >>> formset = ArticleFormSet({}, error_messages={'missing_management_form': 'Sorry, something went wrong.'}) >>> formset.is_valid() False >>> formset.non_form_errors() ['Sorry, something went wrong.'] Custom formset validation A formset has a clean method similar to the one on a Form class. This is where you define your own validation that works at the formset level: >>> from django.core.exceptions import ValidationError >>> from django.forms import BaseFormSet >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> class BaseArticleFormSet(BaseFormSet): ... def clean(self): ... """Checks that no two articles have the same title.""" ... if any(self.errors): ... # Don't bother validating the formset unless each form is valid on its own ... return ... titles = [] ... for form in self.forms: ... if self.can_delete and self._should_delete_form(form): ... continue ... title = form.cleaned_data.get('title') ... if title in titles: ... raise ValidationError("Articles in a set must have distinct titles.") ... titles.append(title) >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet) >>> data = { ... 'form-TOTAL_FORMS': '2', ... 'form-INITIAL_FORMS': '0', ... 'form-0-title': 'Test', ... 'form-0-pub_date': '1904-06-16', ... 'form-1-title': 'Test', ... 'form-1-pub_date': '1912-06-23', ... } >>> formset = ArticleFormSet(data) >>> formset.is_valid() False >>> formset.errors [{}, {}] >>> formset.non_form_errors() ['Articles in a set must have distinct titles.'] The formset clean method is called after all the Form.clean methods have been called. The errors will be found using the non_form_errors() method on the formset. Non-form errors will be rendered with an additional class of nonform to help distinguish them from form-specific errors. For example, {{ formset.non_form_errors }} would look like: <ul class="errorlist nonform"> <li>Articles in a set must have distinct titles.</li> </ul> Changed in Django 4.0: The additional nonform class was added. Validating the number of forms in a formset Django provides a couple ways to validate the minimum or maximum number of submitted forms. Applications which need more customizable validation of the number of forms should use custom formset validation. validate_max If validate_max=True is passed to formset_factory(), validation will also check that the number of forms in the data set, minus those marked for deletion, is less than or equal to max_num. >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True) >>> data = { ... 'form-TOTAL_FORMS': '2', ... 'form-INITIAL_FORMS': '0', ... 'form-0-title': 'Test', ... 'form-0-pub_date': '1904-06-16', ... 'form-1-title': 'Test 2', ... 'form-1-pub_date': '1912-06-23', ... } >>> formset = ArticleFormSet(data) >>> formset.is_valid() False >>> formset.errors [{}, {}] >>> formset.non_form_errors() ['Please submit at most 1 form.'] validate_max=True validates against max_num strictly even if max_num was exceeded because the amount of initial data supplied was excessive. Note Regardless of validate_max, if the number of forms in a data set exceeds absolute_max, then the form will fail to validate as if validate_max were set, and additionally only the first absolute_max forms will be validated. The remainder will be truncated entirely. This is to protect against memory exhaustion attacks using forged POST requests. See Limiting the maximum number of instantiated forms. validate_min If validate_min=True is passed to formset_factory(), validation will also check that the number of forms in the data set, minus those marked for deletion, is greater than or equal to min_num. >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True) >>> data = { ... 'form-TOTAL_FORMS': '2', ... 'form-INITIAL_FORMS': '0', ... 'form-0-title': 'Test', ... 'form-0-pub_date': '1904-06-16', ... 'form-1-title': 'Test 2', ... 'form-1-pub_date': '1912-06-23', ... } >>> formset = ArticleFormSet(data) >>> formset.is_valid() False >>> formset.errors [{}, {}] >>> formset.non_form_errors() ['Please submit at least 3 forms.'] Note Regardless of validate_min, if a formset contains no data, then extra + min_num empty forms will be displayed. Dealing with ordering and deletion of forms The formset_factory() provides two optional parameters can_order and can_delete to help with ordering of forms in formsets and deletion of forms from a formset. can_order BaseFormSet.can_order Default: False Lets you create a formset with the ability to order: >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True) >>> formset = ArticleFormSet(initial=[ ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)}, ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)}, ... ]) >>> for form in formset: ... print(form.as_table()) <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></td></tr> <tr><th><label for="id_form-0-ORDER">Order:</label></th><td><input type="number" name="form-0-ORDER" value="1" id="id_form-0-ORDER"></td></tr> <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></td></tr> <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></td></tr> <tr><th><label for="id_form-1-ORDER">Order:</label></th><td><input type="number" name="form-1-ORDER" value="2" id="id_form-1-ORDER"></td></tr> <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr> <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr> <tr><th><label for="id_form-2-ORDER">Order:</label></th><td><input type="number" name="form-2-ORDER" id="id_form-2-ORDER"></td></tr> This adds an additional field to each form. This new field is named ORDER and is an forms.IntegerField. For the forms that came from the initial data it automatically assigned them a numeric value. Let’s look at what will happen when the user changes these values: >>> data = { ... 'form-TOTAL_FORMS': '3', ... 'form-INITIAL_FORMS': '2', ... 'form-0-title': 'Article #1', ... 'form-0-pub_date': '2008-05-10', ... 'form-0-ORDER': '2', ... 'form-1-title': 'Article #2', ... 'form-1-pub_date': '2008-05-11', ... 'form-1-ORDER': '1', ... 'form-2-title': 'Article #3', ... 'form-2-pub_date': '2008-05-01', ... 'form-2-ORDER': '0', ... } >>> formset = ArticleFormSet(data, initial=[ ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)}, ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)}, ... ]) >>> formset.is_valid() True >>> for form in formset.ordered_forms: ... print(form.cleaned_data) {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': 'Article #3'} {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': 'Article #2'} {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': 'Article #1'} BaseFormSet also provides an ordering_widget attribute and get_ordering_widget() method that control the widget used with can_order. ordering_widget BaseFormSet.ordering_widget Default: NumberInput Set ordering_widget to specify the widget class to be used with can_order: >>> from django.forms import BaseFormSet, formset_factory >>> from myapp.forms import ArticleForm >>> class BaseArticleFormSet(BaseFormSet): ... ordering_widget = HiddenInput >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True) get_ordering_widget BaseFormSet.get_ordering_widget() Override get_ordering_widget() if you need to provide a widget instance for use with can_order: >>> from django.forms import BaseFormSet, formset_factory >>> from myapp.forms import ArticleForm >>> class BaseArticleFormSet(BaseFormSet): ... def get_ordering_widget(self): ... return HiddenInput(attrs={'class': 'ordering'}) >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True) can_delete BaseFormSet.can_delete Default: False Lets you create a formset with the ability to select forms for deletion: >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True) >>> formset = ArticleFormSet(initial=[ ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)}, ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)}, ... ]) >>> for form in formset: ... print(form.as_table()) <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title"></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date"></td></tr> <tr><th><label for="id_form-0-DELETE">Delete:</label></th><td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE"></td></tr> <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title"></td></tr> <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date"></td></tr> <tr><th><label for="id_form-1-DELETE">Delete:</label></th><td><input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE"></td></tr> <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title"></td></tr> <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date"></td></tr> <tr><th><label for="id_form-2-DELETE">Delete:</label></th><td><input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE"></td></tr> Similar to can_order this adds a new field to each form named DELETE and is a forms.BooleanField. When data comes through marking any of the delete fields you can access them with deleted_forms: >>> data = { ... 'form-TOTAL_FORMS': '3', ... 'form-INITIAL_FORMS': '2', ... 'form-0-title': 'Article #1', ... 'form-0-pub_date': '2008-05-10', ... 'form-0-DELETE': 'on', ... 'form-1-title': 'Article #2', ... 'form-1-pub_date': '2008-05-11', ... 'form-1-DELETE': '', ... 'form-2-title': '', ... 'form-2-pub_date': '', ... 'form-2-DELETE': '', ... } >>> formset = ArticleFormSet(data, initial=[ ... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)}, ... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)}, ... ]) >>> [form.cleaned_data for form in formset.deleted_forms] [{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': 'Article #1'}] If you are using a ModelFormSet, model instances for deleted forms will be deleted when you call formset.save(). If you call formset.save(commit=False), objects will not be deleted automatically. You’ll need to call delete() on each of the formset.deleted_objects to actually delete them: >>> instances = formset.save(commit=False) >>> for obj in formset.deleted_objects: ... obj.delete() On the other hand, if you are using a plain FormSet, it’s up to you to handle formset.deleted_forms, perhaps in your formset’s save() method, as there’s no general notion of what it means to delete a form. BaseFormSet also provides a deletion_widget attribute and get_deletion_widget() method that control the widget used with can_delete. deletion_widget New in Django 4.0. BaseFormSet.deletion_widget Default: CheckboxInput Set deletion_widget to specify the widget class to be used with can_delete: >>> from django.forms import BaseFormSet, formset_factory >>> from myapp.forms import ArticleForm >>> class BaseArticleFormSet(BaseFormSet): ... deletion_widget = HiddenInput >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True) get_deletion_widget New in Django 4.0. BaseFormSet.get_deletion_widget() Override get_deletion_widget() if you need to provide a widget instance for use with can_delete: >>> from django.forms import BaseFormSet, formset_factory >>> from myapp.forms import ArticleForm >>> class BaseArticleFormSet(BaseFormSet): ... def get_deletion_widget(self): ... return HiddenInput(attrs={'class': 'deletion'}) >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_delete=True) can_delete_extra New in Django 3.2. BaseFormSet.can_delete_extra Default: True While setting can_delete=True, specifying can_delete_extra=False will remove the option to delete extra forms. Adding additional fields to a formset If you need to add additional fields to the formset this can be easily accomplished. The formset base class provides an add_fields method. You can override this method to add your own fields or even redefine the default fields/attributes of the order and deletion fields: >>> from django.forms import BaseFormSet >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> class BaseArticleFormSet(BaseFormSet): ... def add_fields(self, form, index): ... super().add_fields(form, index) ... form.fields["my_field"] = forms.CharField() >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet) >>> formset = ArticleFormSet() >>> for form in formset: ... print(form.as_table()) <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title"></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date"></td></tr> <tr><th><label for="id_form-0-my_field">My field:</label></th><td><input type="text" name="form-0-my_field" id="id_form-0-my_field"></td></tr> Passing custom parameters to formset forms Sometimes your form class takes custom parameters, like MyArticleForm. You can pass this parameter when instantiating the formset: >>> from django.forms import BaseFormSet >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> class MyArticleForm(ArticleForm): ... def __init__(self, *args, user, **kwargs): ... self.user = user ... super().__init__(*args, **kwargs) >>> ArticleFormSet = formset_factory(MyArticleForm) >>> formset = ArticleFormSet(form_kwargs={'user': request.user}) The form_kwargs may also depend on the specific form instance. The formset base class provides a get_form_kwargs method. The method takes a single argument - the index of the form in the formset. The index is None for the empty_form: >>> from django.forms import BaseFormSet >>> from django.forms import formset_factory >>> class BaseArticleFormSet(BaseFormSet): ... def get_form_kwargs(self, index): ... kwargs = super().get_form_kwargs(index) ... kwargs['custom_kwarg'] = index ... return kwargs Customizing a formset’s prefix In the rendered HTML, formsets include a prefix on each field’s name. By default, the prefix is 'form', but it can be customized using the formset’s prefix argument. For example, in the default case, you might see: <label for="id_form-0-title">Title:</label> <input type="text" name="form-0-title" id="id_form-0-title"> But with ArticleFormset(prefix='article') that becomes: <label for="id_article-0-title">Title:</label> <input type="text" name="article-0-title" id="id_article-0-title"> This is useful if you want to use more than one formset in a view. Using a formset in views and templates Formsets have five attributes and five methods associated with rendering. BaseFormSet.renderer New in Django 4.0. Specifies the renderer to use for the formset. Defaults to the renderer specified by the FORM_RENDERER setting. BaseFormSet.template_name New in Django 4.0. The name of the template used when calling __str__ or render(). This template renders the formset’s management form and then each form in the formset as per the template defined by the form’s template_name. This is a proxy of as_table by default. BaseFormSet.template_name_p New in Django 4.0. The name of the template used when calling as_p(). By default this is 'django/forms/formsets/p.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_p() method. BaseFormSet.template_name_table New in Django 4.0. The name of the template used when calling as_table(). By default this is 'django/forms/formsets/table.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_table() method. BaseFormSet.template_name_ul New in Django 4.0. The name of the template used when calling as_ul(). By default this is 'django/forms/formsets/ul.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_ul() method. BaseFormSet.get_context() New in Django 4.0. Returns the context for rendering a formset in a template. The available context is: formset : The instance of the formset. BaseFormSet.render(template_name=None, context=None, renderer=None) New in Django 4.0. The render method is called by __str__ as well as the as_p(), as_ul(), and as_table() methods. All arguments are optional and will default to: template_name: template_name context: Value returned by get_context() renderer: Value returned by renderer BaseFormSet.as_p() Renders the formset with the template_name_p template. BaseFormSet.as_table() Renders the formset with the template_name_table template. BaseFormSet.as_ul() Renders the formset with the template_name_ul template. Using a formset inside a view is not very different from using a regular Form class. The only thing you will want to be aware of is making sure to use the management form inside the template. Let’s look at a sample view: from django.forms import formset_factory from django.shortcuts import render from myapp.forms import ArticleForm def manage_articles(request): ArticleFormSet = formset_factory(ArticleForm) if request.method == 'POST': formset = ArticleFormSet(request.POST, request.FILES) if formset.is_valid(): # do something with the formset.cleaned_data pass else: formset = ArticleFormSet() return render(request, 'manage_articles.html', {'formset': formset}) The manage_articles.html template might look like this: <form method="post"> {{ formset.management_form }} <table> {% for form in formset %} {{ form }} {% endfor %} </table> </form> However there’s a slight shortcut for the above by letting the formset itself deal with the management form: <form method="post"> <table> {{ formset }} </table> </form> The above ends up calling the BaseFormSet.render() method on the formset class. This renders the formset using the template specified by the template_name attribute. Similar to forms, by default the formset will be rendered as_table, with other helper methods of as_p and as_ul being available. The rendering of the formset can be customized by specifying the template_name attribute, or more generally by overriding the default template. Changed in Django 4.0: Rendering of formsets was moved to the template engine. Manually rendered can_delete and can_order If you manually render fields in the template, you can render can_delete parameter with {{ form.DELETE }}: <form method="post"> {{ formset.management_form }} {% for form in formset %} <ul> <li>{{ form.title }}</li> <li>{{ form.pub_date }}</li> {% if formset.can_delete %} <li>{{ form.DELETE }}</li> {% endif %} </ul> {% endfor %} </form> Similarly, if the formset has the ability to order (can_order=True), it is possible to render it with {{ form.ORDER }}. Using more than one formset in a view You are able to use more than one formset in a view if you like. Formsets borrow much of its behavior from forms. With that said you are able to use prefix to prefix formset form field names with a given value to allow more than one formset to be sent to a view without name clashing. Let’s take a look at how this might be accomplished: from django.forms import formset_factory from django.shortcuts import render from myapp.forms import ArticleForm, BookForm def manage_articles(request): ArticleFormSet = formset_factory(ArticleForm) BookFormSet = formset_factory(BookForm) if request.method == 'POST': article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles') book_formset = BookFormSet(request.POST, request.FILES, prefix='books') if article_formset.is_valid() and book_formset.is_valid(): # do something with the cleaned_data on the formsets. pass else: article_formset = ArticleFormSet(prefix='articles') book_formset = BookFormSet(prefix='books') return render(request, 'manage_articles.html', { 'article_formset': article_formset, 'book_formset': book_formset, }) You would then render the formsets as normal. It is important to point out that you need to pass prefix on both the POST and non-POST cases so that it is rendered and processed correctly. Each formset’s prefix replaces the default form prefix that’s added to each field’s name and id HTML attributes.
django.topics.forms.formsets
GeoDjango GeoDjango intends to be a world-class geographic web framework. Its goal is to make it as easy as possible to build GIS web applications and harness the power of spatially enabled data. GeoDjango Tutorial Introduction Setting Up Geographic Data Geographic Models Importing Spatial Data Spatial Queries Putting your data on the map GeoDjango Installation Overview Requirements Installation Troubleshooting Platform-specific instructions GeoDjango Model API Spatial Field Types Spatial Field Options Geometry Field Options GeoDjango Database API Spatial Backends Creating and Saving Models with Geometry Fields Creating and Saving Models with Raster Fields Spatial Lookups Distance Queries Compatibility Tables GeoDjango Forms API Field arguments Form field classes Form widgets GIS QuerySet API Reference Spatial Lookups Distance Lookups Geographic Database Functions Area AsGeoJSON AsGML AsKML AsSVG AsWKB AsWKT Azimuth BoundingCircle Centroid Difference Distance Envelope ForcePolygonCW GeoHash GeometryDistance Intersection IsValid Length LineLocatePoint MakeValid MemSize NumGeometries NumPoints Perimeter PointOnSurface Reverse Scale SnapToGrid SymDifference Transform Translate Union Measurement Objects Example Supported units Measurement API GEOS API Background Tutorial Geometry Objects Geometry Collections Prepared Geometries Geometry Factories I/O Objects Settings Exceptions GDAL API Overview Vector Data Source Objects OGR Geometries Coordinate System Objects Raster Data Objects Settings Exceptions Geolocation with GeoIP2 Example API Reference Methods Settings Exceptions GeoDjango Utilities LayerMapping data import utility OGR Inspection GeoJSON Serializer GeoDjango Management Commands inspectdb ogrinspect GeoDjango’s admin site GISModelAdmin GeoModelAdmin OSMGeoAdmin Geographic Feeds Example API Reference Geographic Sitemaps Example Reference Testing GeoDjango apps PostGIS GeoDjango tests Deploying GeoDjango
django.ref.contrib.gis.index
class GeoModelAdmin default_lon The default center longitude. default_lat The default center latitude. default_zoom The default zoom level to use. Defaults to 4. extra_js Sequence of URLs to any extra JavaScript to include. map_template Override the template used to generate the JavaScript slippy map. Default is 'gis/admin/openlayers.html'. map_width Width of the map, in pixels. Defaults to 600. map_height Height of the map, in pixels. Defaults to 400. openlayers_url Link to the URL of the OpenLayers JavaScript. Defaults to 'https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js'. modifiable Defaults to True. When set to False, disables editing of existing geometry fields in the admin. Note This is different from adding the geometry field to readonly_fields, which will only display the WKT of the geometry. Setting modifiable=False, actually displays the geometry in a map, but disables the ability to edit its vertices. Deprecated since version 4.0: This class is deprecated. Use ModelAdmin instead.
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin
default_lat
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.default_lat
default_lon
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.default_lon
default_zoom
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.default_zoom
extra_js
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.extra_js
map_height
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.map_height
map_template
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.map_template
map_width
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.map_width
modifiable
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.modifiable
openlayers_url
django.ref.contrib.gis.admin#django.contrib.gis.admin.GeoModelAdmin.openlayers_url
class GISModelAdmin gis_widget The widget class to be used for GeometryField. Defaults to OSMWidget. gis_widget_kwargs The keyword arguments that would be passed to the gis_widget. Defaults to an empty dictionary.
django.ref.contrib.gis.admin#django.contrib.gis.admin.GISModelAdmin
gis_widget The widget class to be used for GeometryField. Defaults to OSMWidget.
django.ref.contrib.gis.admin#django.contrib.gis.admin.GISModelAdmin.gis_widget
gis_widget_kwargs The keyword arguments that would be passed to the gis_widget. Defaults to an empty dictionary.
django.ref.contrib.gis.admin#django.contrib.gis.admin.GISModelAdmin.gis_widget_kwargs
class OSMGeoAdmin A subclass of GeoModelAdmin that uses a Spherical Mercator projection with OpenStreetMap street data tiles. Deprecated since version 4.0: This class is deprecated. Use GISModelAdmin instead.
django.ref.contrib.gis.admin#django.contrib.gis.admin.OSMGeoAdmin
BaseSpatialField.spatial_index
django.ref.contrib.gis.model-api#django.contrib.gis.db.models.BaseSpatialField.spatial_index
BaseSpatialField.srid
django.ref.contrib.gis.model-api#django.contrib.gis.db.models.BaseSpatialField.srid
class Collect(geo_field)
django.ref.contrib.gis.geoquerysets#django.contrib.gis.db.models.Collect
class Extent(geo_field)
django.ref.contrib.gis.geoquerysets#django.contrib.gis.db.models.Extent
class Extent3D(geo_field)
django.ref.contrib.gis.geoquerysets#django.contrib.gis.db.models.Extent3D
class Area(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Area
class AsGeoJSON(expression, bbox=False, crs=False, precision=8, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.AsGeoJSON
class AsGML(expression, version=2, precision=8, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.AsGML
class AsKML(expression, precision=8, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.AsKML
class AsSVG(expression, relative=False, precision=8, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.AsSVG
class AsWKB(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.AsWKB
class AsWKT(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.AsWKT
class Azimuth(point_a, point_b, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Azimuth
class BoundingCircle(expression, num_seg=48, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.BoundingCircle
class Centroid(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Centroid
class Difference(expr1, expr2, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Difference
class Distance(expr1, expr2, spheroid=None, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Distance
class Envelope(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Envelope
class ForcePolygonCW(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.ForcePolygonCW
class GeoHash(expression, precision=None, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.GeoHash
class GeometryDistance(expr1, expr2, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.GeometryDistance
class Intersection(expr1, expr2, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Intersection
class IsValid(expr)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.IsValid
class Length(expression, spheroid=True, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Length
class LineLocatePoint(linestring, point, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.LineLocatePoint
class MakeValid(expr)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.MakeValid
class MemSize(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.MemSize
class NumGeometries(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.NumGeometries
class NumPoints(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.NumPoints
class Perimeter(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Perimeter
class PointOnSurface(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.PointOnSurface
class Reverse(expression, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Reverse
class Scale(expression, x, y, z=0.0, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Scale
class SnapToGrid(expression, *args, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.SnapToGrid
class SymDifference(expr1, expr2, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.SymDifference
class Transform(expression, srid, **extra)
django.ref.contrib.gis.functions#django.contrib.gis.db.models.functions.Transform