A field containing either an IPv4 or an IPv6 address.
The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ::ffff:192.0.2.0. For example, 2001:0::0:01 would be normalized to 2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All characters are converted to lowercase.
Takes two optional arguments:
Limits valid inputs to the specified protocol. Accepted values are both (default), IPv4 or IPv6. Matching is case insensitive.
Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.


Limits valid inputs to the specified protocol. Accepted values are both (default), IPv4 or IPv6. Matching is case insensitive.


Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.


Note that there also is a MultipleHiddenInput widget that encapsulates a set of hidden input elements.


Using an ImageField requires that Pillow is installed with support for the image formats you use. If you encounter a corrupt image error when you upload an image, it usually means that Pillow doesn’t understand its format. To fix this, install the appropriate library and reinstall Pillow.
When you use an ImageField on a form, you must also remember to bind the file data to the form.
After the field has been cleaned and validated, the UploadedFile object will have an additional image attribute containing the Pillow Image instance used to check if the file was a valid image. Pillow closes the underlying file descriptor after verifying an image, so while non-image data attributes, such as format, height, and width, are available, methods that access the underlying image data, such as getdata() or getpixel(), cannot be used without reopening the file. For example:
Additionally, UploadedFile.content_type will be updated with the image’s content type if Pillow can determine it, otherwise it will be set to None.


The max_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit.
Takes two optional arguments for validation:
These control the range of values permitted in the field.


These control the range of values permitted in the field.


A field which accepts JSON encoded data for a JSONField.
Takes two optional arguments:
A json.JSONEncoder subclass to serialize data types not supported by the standard JSON serializer (e.g. datetime.datetime or UUID). For example, you can use the DjangoJSONEncoder class.
Defaults to json.JSONEncoder.
A json.JSONDecoder subclass to deserialize the input. Your deserialization may need to account for the fact that you can’t be certain of the input type. For example, you run the risk of returning a datetime that was actually a string that just happened to be in the same format chosen for datetimes.
The decoder can be used to validate the input. If json.JSONDecodeError is raised during the deserialization, a ValidationError will be raised.
Defaults to json.JSONDecoder.
Note
If you use a ModelForm, the encoder and decoder from JSONField will be used.
User friendly forms
JSONField is not particularly user friendly in most cases. However, it is a useful way to format data from a client-side widget for submission to the server.


A json.JSONDecoder subclass to deserialize the input. Your deserialization may need to account for the fact that you can’t be certain of the input type. For example, you run the risk of returning a datetime that was actually a string that just happened to be in the same format chosen for datetimes.
The decoder can be used to validate the input. If json.JSONDecodeError is raised during the deserialization, a ValidationError will be raised.
Defaults to json.JSONDecoder.


A json.JSONEncoder subclass to serialize data types not supported by the standard JSON serializer (e.g. datetime.datetime or UUID). For example, you can use the DjangoJSONEncoder class.
Defaults to json.JSONEncoder.


The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for ModelChoiceField becomes impractical when the number of entries increases. You should avoid using it for more than 100 items.
A single argument is required:
A QuerySet of model objects from which the choices for the field are derived and which is used to validate the user’s selection. It’s evaluated when the form is rendered.
ModelChoiceField also takes two optional arguments:
By default the <select> widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None:
Note that if a ModelChoiceField is required and has a default initial value, no empty choice is created (regardless of the value of empty_label).
This optional argument is used to specify the field to use as the value of the choices in the field’s widget. Be sure it’s a unique field for the model, otherwise the selected value could match more than one object. By default it is set to None, in which case the primary key of each object will be used. For example:
would yield:
and:
would yield:
ModelChoiceField also has the attribute:
The iterator class used to generate field choices from queryset. By default, ModelChoiceIterator.
The __str__() method of the model will be called to generate string representations of the objects for use in the field’s choices. To provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object and should return a string suitable for representing it. For example:
Support for containing %(value)s in the invalid_choice error message was added.


By default the <select> widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None:
Note that if a ModelChoiceField is required and has a default initial value, no empty choice is created (regardless of the value of empty_label).


The iterator class used to generate field choices from queryset. By default, ModelChoiceIterator.


A QuerySet of model objects from which the choices for the field are derived and which is used to validate the user’s selection. It’s evaluated when the form is rendered.


This optional argument is used to specify the field to use as the value of the choices in the field’s widget. Be sure it’s a unique field for the model, otherwise the selected value could match more than one object. By default it is set to None, in which case the primary key of each object will be used. For example:
would yield:
and:
would yield:


The default class assigned to the iterator attribute of ModelChoiceField and ModelMultipleChoiceField. An iterable that yields 2-tuple choices from the queryset.
A single argument is required:
The instance of ModelChoiceField or ModelMultipleChoiceField to iterate and yield choices.
ModelChoiceIterator has the following method:
Yields 2-tuple choices, in the (value, label) format used by ChoiceField.choices. The first value element is a ModelChoiceIteratorValue instance.


Yields 2-tuple choices, in the (value, label) format used by ChoiceField.choices. The first value element is a ModelChoiceIteratorValue instance.


The instance of ModelChoiceField or ModelMultipleChoiceField to iterate and yield choices.


Two arguments are required:
The value of the choice. This value is used to render the value attribute of an HTML <option> element.
The model instance from the queryset. The instance can be accessed in custom ChoiceWidget.create_option() implementations to adjust the rendered HTML.
ModelChoiceIteratorValue has the following method:
Return value as a string to be rendered in HTML.


Return value as a string to be rendered in HTML.


The model instance from the queryset. The instance can be accessed in custom ChoiceWidget.create_option() implementations to adjust the rendered HTML.


The value of the choice. This value is used to render the value attribute of an HTML <option> element.


The invalid_choice message may contain %(value)s and the invalid_pk_value message may contain %(pk)s, which will be substituted by the appropriate values.
Allows the selection of one or more model objects, suitable for representing a many-to-many relation. As with ModelChoiceField, you can use label_from_instance to customize the object representations.
A single argument is required:
Same as ModelChoiceField.queryset.
Takes one optional argument:
Same as ModelChoiceField.to_field_name.
ModelMultipleChoiceField also has the attribute:
Same as ModelChoiceField.iterator.


Returns an InlineFormSet using modelformset_factory() with defaults of formset=BaseInlineFormSet, can_delete=True, and extra=3.
If your model has more than one ForeignKey to the parent_model, you must specify a fk_name.
See Inline formsets for example usage.
The absolute_max and can_delete_extra arguments were added.
The renderer argument was added.


Returns a ModelForm class for the given model. You can optionally pass a form argument to use as a starting point for constructing the ModelForm.
fields is an optional list of field names. If provided, only the named fields will be included in the returned fields.
exclude is an optional list of field names. If provided, the named fields will be excluded from the returned fields, even if they are listed in the fields argument.
formfield_callback is a callable that takes a model field and returns a form field.
widgets is a dictionary of model field names mapped to a widget.
localized_fields is a list of names of fields which should be localized.
labels is a dictionary of model field names mapped to a label.
help_texts is a dictionary of model field names mapped to a help text.
error_messages is a dictionary of model field names mapped to a dictionary of error messages.
field_classes is a dictionary of model field names mapped to a form field class.
See ModelForm factory function for example usage.
You must provide the list of fields explicitly, either via keyword arguments fields or exclude, or the corresponding attributes on the form’s inner Meta class. See Selecting the fields to use for more information. Omitting any definition of the fields to use will result in an ImproperlyConfigured exception.


Returns a FormSet class for the given model class.
Arguments model, form, fields, exclude, formfield_callback, widgets, localized_fields, labels, help_texts, error_messages, and field_classes are all passed through to modelform_factory().
Arguments formset, extra, can_delete, can_order, max_num, validate_max, min_num, validate_min, absolute_max, can_delete_extra, and renderer are passed through to formset_factory(). See formsets for details.
See Model formsets for example usage.
The absolute_max and can_delete_extra arguments were added.
The renderer argument was added.


The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes one extra required argument, choices, as for ChoiceField.


A widget that handles multiple hidden widgets for fields that have a list of values.


Aggregates the logic of multiple fields that together produce a single value.
This field is abstract and must be subclassed. In contrast with the single-value fields, subclasses of MultiValueField must not implement clean() but instead - implement compress().
Takes one extra required argument:
A tuple of fields whose values are cleaned and subsequently combined into a single value. Each value of the field is cleaned by the corresponding field in fields – the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is combined into a single value by compress().
Also takes some optional arguments:
Defaults to True, in which case a required validation error will be raised if no value is supplied for any field.
When set to False, the Field.required attribute can be set to False for individual fields to make them optional. If no value is supplied for a required field, an incomplete validation error will be raised.
A default incomplete error message can be defined on the MultiValueField subclass, or different messages can be defined on each individual field. For example:
Must be a subclass of django.forms.MultiWidget. Default value is TextInput, which probably is not very useful in this case.
Takes a list of valid values and returns a “compressed” version of those values – in a single value. For example, SplitDateTimeField is a subclass which combines a time field and a date field into a datetime object.
This method must be implemented in the subclasses.


Takes a list of valid values and returns a “compressed” version of those values – in a single value. For example, SplitDateTimeField is a subclass which combines a time field and a date field into a datetime object.
This method must be implemented in the subclasses.


A tuple of fields whose values are cleaned and subsequently combined into a single value. Each value of the field is cleaned by the corresponding field in fields – the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is combined into a single value by compress().


Defaults to True, in which case a required validation error will be raised if no value is supplied for any field.
When set to False, the Field.required attribute can be set to False for individual fields to make them optional. If no value is supplied for a required field, an incomplete validation error will be raised.
A default incomplete error message can be defined on the MultiValueField subclass, or different messages can be defined on each individual field. For example:


Must be a subclass of django.forms.MultiWidget. Default value is TextInput, which probably is not very useful in this case.


A widget that is composed of multiple widgets. MultiWidget works hand in hand with the MultiValueField.
MultiWidget has one required argument:
An iterable containing the widgets needed. For example:
You may provide a dictionary in order to specify custom suffixes for the name attribute on each subwidget. In this case, for each (key, widget) pair, the key will be appended to the name of the widget in order to generate the attribute value. You may provide the empty string ('') for a single key, in order to suppress the suffix for one widget. For example:
And one required method:
This method takes a single “compressed” value from the field and returns a list of “decompressed” values. The input value can be assumed valid, but not necessarily non-empty.
This method must be implemented by the subclass, and since the value may be empty, the implementation must be defensive.
The rationale behind “decompression” is that it is necessary to “split” the combined value of the form field into the values for each widget.
An example of this is how SplitDateTimeWidget turns a datetime value into a list with date and time split into two separate values:
Tip
Note that MultiValueField has a complementary method compress() with the opposite responsibility - to combine cleaned values of all member fields into one.
It provides some custom context:
In addition to the 'widget' key described in Widget.get_context(), MultiWidget adds a widget['subwidgets'] key.
These can be looped over in the widget template:
Here’s an example widget which subclasses MultiWidget to display a date with the day, month, and year in different select boxes. This widget is intended to be used with a DateField rather than a MultiValueField, thus we have implemented value_from_datadict():
The constructor creates several Select widgets in a list. The super() method uses this list to set up the widget.
The required method decompress() breaks up a datetime.date value into the day, month, and year values corresponding to each widget. If an invalid date was selected, such as the non-existent 30th February, the DateField passes this method a string instead, so that needs parsing. The final return handles when value is None, meaning we don’t have any defaults for our subwidgets.
The default implementation of value_from_datadict() returns a list of values corresponding to each Widget. This is appropriate when using a MultiWidget with a MultiValueField. But since we want to use this widget with a DateField, which takes a single value, we have overridden this method. The implementation here combines the data from the subwidgets into a string in the format that DateField expects.


This method takes a single “compressed” value from the field and returns a list of “decompressed” values. The input value can be assumed valid, but not necessarily non-empty.
This method must be implemented by the subclass, and since the value may be empty, the implementation must be defensive.
The rationale behind “decompression” is that it is necessary to “split” the combined value of the form field into the values for each widget.
An example of this is how SplitDateTimeWidget turns a datetime value into a list with date and time split into two separate values:
Tip
Note that MultiValueField has a complementary method compress() with the opposite responsibility - to combine cleaned values of all member fields into one.


In addition to the 'widget' key described in Widget.get_context(), MultiWidget adds a widget['subwidgets'] key.
These can be looped over in the widget template:


An iterable containing the widgets needed. For example:
You may provide a dictionary in order to specify custom suffixes for the name attribute on each subwidget. In this case, for each (key, widget) pair, the key will be appended to the name of the widget in order to generate the attribute value. You may provide the empty string ('') for a single key, in order to suppress the suffix for one widget. For example:


NullBooleanField may be used with widgets such as Select or RadioSelect by providing the widget choices:


Select widget with options ‘Unknown’, ‘Yes’ and ‘No’


Beware that not all browsers support entering localized numbers in number input types. Django itself avoids using them for fields having their localize property set to True.


Takes one optional argument:
Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False).


Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False).


Similar to Select, but rendered as a list of radio buttons within <div> tags:
So they are announced more concisely by screen readers, radio buttons were changed to render in <div> tags.
For more granular control over the generated markup, you can loop over the radio buttons in the template. Assuming a form myform with a field beatles that uses a RadioSelect as its widget:
This would generate the following HTML:
That included the <label> tags. To get more granular, you can use each radio button’s tag, choice_label and id_for_label attributes. For example, this template…
…will result in the following HTML:
If you decide not to loop over the radio buttons – e.g., if your template includes {{ myform.beatles }} – they’ll be output in a <div> with <div> tags, as above.
The outer <div> container receives the id attribute of the widget, if defined, or BoundField.auto_id otherwise.
When looping over the radio buttons, the label and input tags include for and id attributes, respectively. Each radio button has an id_for_label attribute to output the element’s ID.


Takes one required argument:
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.
Defaults to False. If enabled, stripping will be applied before the regex validation.


A regular expression specified either as a string or a compiled regular expression object.


Defaults to False. If enabled, stripping will be applied before the regex validation.


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.


Wrapper around three Select widgets: one each for month, day, and year.
Takes several optional arguments:
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.
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:
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').


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').


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:


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.


Similar to Select, but allows multiple selection: <select multiple>...</select>


This field is intended for use in representing a model SlugField in forms.
Takes two optional parameters:
A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to False.
The value to use to represent “empty”. Defaults to an empty string.


A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to False.


The value to use to represent “empty”. Defaults to an empty string.


Takes two optional arguments:
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.
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.


A list of formats used to attempt to convert a string to a valid datetime.date object.


A list of formats used to attempt to convert a string to a valid datetime.time object.


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:
Similar to DateInput.format
Similar to TimeInput.format
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.


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.


Similar to SplitDateTimeWidget, but uses HiddenInput for both date and time.


Takes one optional argument:
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.


Takes same arguments as TextInput, with one more optional argument:
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.


The format in which this field’s initial value will be displayed.


Just like a ChoiceField, except TypedChoiceField takes two extra arguments, coerce and empty_value.
Takes extra arguments:
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.
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.


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.


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.


Just like a MultipleChoiceField, except TypedMultipleChoiceField takes two extra arguments, coerce and empty_value.
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.


Has three optional arguments max_length, min_length, and empty_value which work just as they do for CharField.


This field will accept any string format accepted as the hex argument to the UUID constructor.


This abstract class cannot be rendered, but provides the basic attribute attrs. You may also implement or override the render() method on custom widgets.
A dictionary containing HTML attributes to be set on the rendered widget.
If you assign a value of True or False to an attribute, it will be rendered as an HTML5 boolean attribute:
An attribute that defaults to True. If set to False, the microseconds part of datetime and time values will be set to 0.
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.
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:
Widget subclasses can provide custom context values by overriding this method.
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.
Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the FORM_RENDERER setting is used.
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.
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.
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.


A dictionary containing HTML attributes to be set on the rendered widget.
If you assign a value of True or False to an attribute, it will be rendered as an HTML5 boolean attribute:


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.


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:
Widget subclasses can provide custom context values by overriding this method.


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.


Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the FORM_RENDERER setting is used.


An attribute that defaults to True. If set to False, the microseconds part of datetime and time values will be set to 0.


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.


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.


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.


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:
You might want to allow the user to create several articles at once. To create a formset out of an ArticleForm you would do:
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:
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:
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.
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:
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.
The max_num parameter to formset_factory() gives you the ability to limit the number of forms the formset will display:
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.
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:
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.
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:
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:
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.
To check how many errors there are in the formset, we can use the total_error_count method:
We can also check if form data differs from the initial data (i.e. the form was sent without any data):
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:
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.
formset.is_valid() now returns False rather than raising an exception when the management form is missing or has been tampered with.
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.
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.
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:
And here is a custom error message:
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:
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:
The additional nonform class was added.
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.
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.
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.
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.
Note
Regardless of validate_min, if a formset contains no data, then extra + min_num empty forms will be displayed.
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.
Default: False
Lets you create a formset with the ability to order:
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:
BaseFormSet also provides an ordering_widget attribute and get_ordering_widget() method that control the widget used with can_order.
Default: NumberInput
Set ordering_widget to specify the widget class to be used with can_order:
Override get_ordering_widget() if you need to provide a widget instance for use with can_order:
Default: False
Lets you create a formset with the ability to select forms for deletion:
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:
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:
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.
Default: CheckboxInput
Set deletion_widget to specify the widget class to be used with can_delete:
Override get_deletion_widget() if you need to provide a widget instance for use with can_delete:
Default: True
While setting can_delete=True, specifying can_delete_extra=False will remove the option to delete extra forms.
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:
Sometimes your form class takes custom parameters, like MyArticleForm. You can pass this parameter when instantiating the formset:
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:
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:
But with ArticleFormset(prefix='article') that becomes:
This is useful if you want to use more than one formset in a view.
Formsets have five attributes and five methods associated with rendering.
Specifies the renderer to use for the formset. Defaults to the renderer specified by the FORM_RENDERER setting.
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.
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.
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.
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.
Returns the context for rendering a formset in a template.
The available context is:
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:
Renders the formset with the template_name_p template.
Renders the formset with the template_name_table template.
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:
The manage_articles.html template might look like this:
However there’s a slight shortcut for the above by letting the formset itself deal with the management 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.
Rendering of formsets was moved to the template engine.
If you manually render fields in the template, you can render can_delete parameter with {{ form.DELETE }}:
Similarly, if the formset has the ability to order (can_order=True), it is possible to render it with {{ form.ORDER }}.
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:
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.


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.


The default center longitude.
The default center latitude.
The default zoom level to use. Defaults to 4.
Sequence of URLs to any extra JavaScript to include.
Override the template used to generate the JavaScript slippy map. Default is 'gis/admin/openlayers.html'.
Width of the map, in pixels. Defaults to 600.
Height of the map, in pixels. Defaults to 400.
Link to the URL of the OpenLayers JavaScript. Defaults to 'https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js'.
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.


The widget class to be used for GeometryField. Defaults to OSMWidget.
The keyword arguments that would be passed to the gis_widget. Defaults to an empty dictionary.


The widget class to be used for GeometryField. Defaults to OSMWidget.


The keyword arguments that would be passed to the gis_widget. Defaults to an empty dictionary.


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.


In addition to methods provided by the django.contrib.syndication.views.Feed base class, GeoDjango’s Feed class provides the following overrides. Note that these overrides may be done in multiple ways:
Takes the object returned by get_object() and returns the feed’s geometry. Typically this is a GEOSGeometry instance, or can be a tuple to represent a point or a box. For example:
Set this to return the geometry for each item in the feed. This can be a GEOSGeometry instance, or a tuple that represents a point coordinate or bounding box. For example:


You generally shouldn’t have to set or change that attribute which should be set up depending on the field class. It matches the OpenGIS standard geometry name.


This is the SRID code that the field value should be transformed to. For example, if the map widget SRID is different from the SRID more generally used by your application or database, the field will automatically convert input values into that SRID.


This is an abstract base widget containing the logic needed by subclasses. You cannot directly use this widget for a geometry field. Note that the rendering of GeoDjango widgets is based on a template, identified by the template_name class attribute.


Boolean value specifying if a textarea input showing the serialized representation of the current geometry is visible, mainly for debugging purposes (default is False).


The OpenGIS geometry type, generally set by the form field.


SRID code used by the map (default is 4326).


Height and width of the widget map (default is 400x600).


Indicates if the widget supports edition of 3D data (default is False).


The template used to render the map widget.


This is the default widget used by all GeoDjango form fields. template_name is gis/openlayers.html.
OpenLayersWidget and OSMWidget use the openlayers.js file hosted on the cdnjs.cloudflare.com content-delivery network. You can subclass these widgets in order to specify your own version of the OpenLayers.js file in the js property of the inner Media class (see Assets as a static definition).


This widget uses an OpenStreetMap base layer to display geographic objects on. Attributes are:
gis/openlayers-osm.html
The default center latitude and longitude are 47 and 5, respectively, which is a location in eastern France.
The default map zoom is 12.
The OpenLayersWidget note about JavaScript file hosting above also applies here. See also this FAQ answer about https access to map tiles.


The default center latitude and longitude are 47 and 5, respectively, which is a location in eastern France.


The constructor for DataSource only requires one parameter: the path of the file you want to read. However, OGR also supports a variety of more complex data sources, including databases, that may be accessed by passing a special name string instead of a path. For more information, see the OGR Vector Formats documentation. The name property of a DataSource instance gives the OGR name of the underlying data source that it is using.
The optional encoding parameter allows you to specify a non-standard encoding of the strings in the source. This is typically useful when you obtain DjangoUnicodeDecodeError exceptions while reading field values.
Once you’ve created your DataSource, you can find out how many layers of data it contains by accessing the layer_count property, or (equivalently) by using the len() function. For information on accessing the layers of data themselves, see the next section:
Returns the number of layers in the data source.
Returns the name of the data source.
Support for pathlib.Path ds_input was added.


The Driver class is used internally to wrap an OGR DataSource driver.
Returns the number of OGR vector drivers currently registered.


Represents an OGR Envelope structure that contains the minimum and maximum X, Y coordinates for a rectangle bounding box. The naming of the variables is compatible with the OGR Envelope C structure.
The value of the minimum X coordinate.
The value of the maximum X coordinate.
The value of the minimum Y coordinate.
The value of the maximum Y coordinate.
The upper-right coordinate, as a tuple.
The lower-left coordinate, as a tuple.
A tuple representing the envelope.
A string representing this envelope as a polygon in WKT format.


Feature wraps an OGR feature. You never create a Feature object directly. Instead, you retrieve them from a Layer object. Each feature consists of a geometry and a set of fields containing additional properties. The geometry of a field is accessible via its geom property, which returns an OGRGeometry object. A Feature behaves like a standard Python container for its fields, which it returns as Field objects: you can access a field directly by its index or name, or you can iterate over a feature’s fields, e.g. in a for loop.
Returns the geometry for this feature, as an OGRGeometry object:
A method that returns the value of the given field (specified by name) for this feature, not a Field wrapper object:
Returns the type of geometry for this feature, as an OGRGeomType object. This will be the same for all features in a given layer and is equivalent to the Layer.geom_type property of the Layer object the feature came from.
Returns the number of fields of data associated with the feature. This will be the same for all features in a given layer and is equivalent to the Layer.num_fields property of the Layer object the feature came from.
Returns a list of the names of the fields of data associated with the feature. This will be the same for all features in a given layer and is equivalent to the Layer.fields property of the Layer object the feature came from.
Returns the feature identifier within the layer:
Returns the name of the Layer that the feature came from. This will be the same for all features in a given layer:
A method that returns the index of the given field name. This will be the same for all features in a given layer:


Returns the name of this field:
Returns the OGR type of this field, as an integer. The FIELD_CLASSES dictionary maps these values onto subclasses of Field:
Returns a string with the name of the data type of this field:
Returns the value of this field. The Field class itself returns the value as a string, but each subclass returns the value in the most appropriate form:
Returns the width of this field:
Returns the numeric precision of this field. This is meaningless (and set to zero) for non-numeric fields:
Returns the value of the field as a double (float):
Returns the value of the field as an integer:
Returns the value of the field as a string:
Returns the value of the field as a tuple of date and time components:


GDALBand instances are not created explicitly, but rather obtained from a GDALRaster object, through its bands attribute. The GDALBands contain the actual pixel values of the raster.
The name or description of the band, if any.
The width of the band in pixels (X-axis).
The height of the band in pixels (Y-axis).
The total number of pixels in this band. Is equal to width * height.
Compute statistics on the pixel values of this band. The return value is a tuple with the following structure: (minimum, maximum, mean, standard deviation).
If the approximate argument is set to True, the statistics may be computed based on overviews or a subset of image tiles.
If the refresh argument is set to True, the statistics will be computed from the data directly, and the cache will be updated with the result.
If a persistent cache value is found, that value is returned. For raster formats using Persistent Auxiliary Metadata (PAM) services, the statistics might be cached in an auxiliary file. In some cases this metadata might be out of sync with the pixel values or cause values from a previous call to be returned which don’t reflect the value of the approximate argument. In such cases, use the refresh argument to get updated values and store them in the cache.
For empty bands (where all pixel values are “no data”), all statistics are returned as None.
The statistics can also be retrieved directly by accessing the min, max, mean, and std properties.
The minimum pixel value of the band (excluding the “no data” value).
The maximum pixel value of the band (excluding the “no data” value).
The mean of all pixel values of the band (excluding the “no data” value).
The standard deviation of all pixel values of the band (excluding the “no data” value).
The “no data” value for a band is generally a special marker value used to mark pixels that are not valid data. Such pixels should generally not be displayed, nor contribute to analysis operations.
To delete an existing “no data” value, set this property to None (requires GDAL ≥ 2.1).
The data type contained in the band, as an integer constant between 0 (Unknown) and 11. If as_string is True, the data type is returned as a string with the following possible values: GDT_Unknown, GDT_Byte, GDT_UInt16, GDT_Int16, GDT_UInt32, GDT_Int32, GDT_Float32, GDT_Float64, GDT_CInt16, GDT_CInt32, GDT_CFloat32, and GDT_CFloat64.
The color interpretation for the band, as an integer between 0and 16. If as_string is True, the data type is returned as a string with the following possible values: GCI_Undefined, GCI_GrayIndex, GCI_PaletteIndex, GCI_RedBand, GCI_GreenBand, GCI_BlueBand, GCI_AlphaBand, GCI_HueBand, GCI_SaturationBand, GCI_LightnessBand, GCI_CyanBand, GCI_MagentaBand, GCI_YellowBand, GCI_BlackBand, GCI_YCbCr_YBand, GCI_YCbCr_CbBand, and GCI_YCbCr_CrBand. GCI_YCbCr_CrBand also represents GCI_Max because both correspond to the integer 16, but only GCI_YCbCr_CrBand is returned as a string.
The accessor to the pixel values of the GDALBand. Returns the complete data array if no parameters are provided. A subset of the pixel array can be requested by specifying an offset and block size as tuples.
If NumPy is available, the data is returned as NumPy array. For performance reasons, it is highly recommended to use NumPy.
Data is written to the GDALBand if the data parameter is provided. The input can be of one of the following types - packed string, buffer, list, array, and NumPy array. The number of items in the input should normally correspond to the total number of pixels in the band, or to the number of pixels for a specific block of pixel values if the offset and size parameters are provided.
If the number of items in the input is different from the target pixel block, the shape parameter must be specified. The shape is a tuple that specifies the width and height of the input data in pixels. The data is then replicated to update the pixel values of the selected block. This is useful to fill an entire band with a single value, for instance.
For example:
The metadata of this band. The functionality is identical to GDALRaster.metadata.


The color interpretation for the band, as an integer between 0and 16. If as_string is True, the data type is returned as a string with the following possible values: GCI_Undefined, GCI_GrayIndex, GCI_PaletteIndex, GCI_RedBand, GCI_GreenBand, GCI_BlueBand, GCI_AlphaBand, GCI_HueBand, GCI_SaturationBand, GCI_LightnessBand, GCI_CyanBand, GCI_MagentaBand, GCI_YellowBand, GCI_BlackBand, GCI_YCbCr_YBand, GCI_YCbCr_CbBand, and GCI_YCbCr_CrBand. GCI_YCbCr_CrBand also represents GCI_Max because both correspond to the integer 16, but only GCI_YCbCr_CrBand is returned as a string.


The accessor to the pixel values of the GDALBand. Returns the complete data array if no parameters are provided. A subset of the pixel array can be requested by specifying an offset and block size as tuples.
If NumPy is available, the data is returned as NumPy array. For performance reasons, it is highly recommended to use NumPy.
Data is written to the GDALBand if the data parameter is provided. The input can be of one of the following types - packed string, buffer, list, array, and NumPy array. The number of items in the input should normally correspond to the total number of pixels in the band, or to the number of pixels for a specific block of pixel values if the offset and size parameters are provided.
If the number of items in the input is different from the target pixel block, the shape parameter must be specified. The shape is a tuple that specifies the width and height of the input data in pixels. The data is then replicated to update the pixel values of the selected block. This is useful to fill an entire band with a single value, for instance.
For example:


The data type contained in the band, as an integer constant between 0 (Unknown) and 11. If as_string is True, the data type is returned as a string with the following possible values: GDT_Unknown, GDT_Byte, GDT_UInt16, GDT_Int16, GDT_UInt32, GDT_Int32, GDT_Float32, GDT_Float64, GDT_CInt16, GDT_CInt32, GDT_CFloat32, and GDT_CFloat64.


The name or description of the band, if any.


The height of the band in pixels (Y-axis).


The maximum pixel value of the band (excluding the “no data” value).


The mean of all pixel values of the band (excluding the “no data” value).


The metadata of this band. The functionality is identical to GDALRaster.metadata.


The minimum pixel value of the band (excluding the “no data” value).


The “no data” value for a band is generally a special marker value used to mark pixels that are not valid data. Such pixels should generally not be displayed, nor contribute to analysis operations.
To delete an existing “no data” value, set this property to None (requires GDAL ≥ 2.1).


The total number of pixels in this band. Is equal to width * height.


Compute statistics on the pixel values of this band. The return value is a tuple with the following structure: (minimum, maximum, mean, standard deviation).
If the approximate argument is set to True, the statistics may be computed based on overviews or a subset of image tiles.
If the refresh argument is set to True, the statistics will be computed from the data directly, and the cache will be updated with the result.
If a persistent cache value is found, that value is returned. For raster formats using Persistent Auxiliary Metadata (PAM) services, the statistics might be cached in an auxiliary file. In some cases this metadata might be out of sync with the pixel values or cause values from a previous call to be returned which don’t reflect the value of the approximate argument. In such cases, use the refresh argument to get updated values and store them in the cache.
For empty bands (where all pixel values are “no data”), all statistics are returned as None.
The statistics can also be retrieved directly by accessing the min, max, mean, and std properties.


The standard deviation of all pixel values of the band (excluding the “no data” value).


The width of the band in pixels (X-axis).


The constructor for GDALRaster accepts two parameters. The first parameter defines the raster source, and the second parameter defines if a raster should be opened in write mode. For newly-created rasters, the second parameter is ignored and the new raster is always created in write mode.
The first parameter can take three forms: a string representing a file path (filesystem or GDAL virtual filesystem), a dictionary with values defining a new raster, or a bytes object representing a raster file.
If the input is a file path, the raster is opened from there. If the input is raw data in a dictionary, the parameters width, height, and srid are required. If the input is a bytes object, it will be opened using a GDAL virtual filesystem.
For a detailed description of how to create rasters using dictionary input, see Creating rasters from data. For a detailed description of how to create rasters in the virtual filesystem, see Using GDAL’s Virtual Filesystem.
The following example shows how rasters can be created from different input sources (using the sample data from the GeoDjango tests; see also the Sample Data section).
Creating rasters in any GDAL virtual filesystem was allowed.
The name of the source which is equivalent to the input file path or the name provided upon instantiation.
The name of the GDAL driver used to handle the input file. For GDALRasters created from a file, the driver type is detected automatically. The creation of rasters from scratch is an in-memory raster by default ('MEM'), but can be altered as needed. For instance, use GTiff for a GeoTiff file. For a list of file types, see also the GDAL Raster Formats list.
An in-memory raster is created through the following example:
A file based GeoTiff raster is created through the following example:
The width of the source in pixels (X-axis).
The height of the source in pixels (Y-axis).
The spatial reference system of the raster, as a SpatialReference instance. The SRS can be changed by setting it to an other SpatialReference or providing any input that is accepted by the SpatialReference constructor.
The Spatial Reference System Identifier (SRID) of the raster. This property is a shortcut to getting or setting the SRID through the srs attribute.
The affine transformation matrix used to georeference the source, as a tuple of six coefficients which map pixel/line coordinates into georeferenced space using the following relationship:
The same values can be retrieved by accessing the origin (indices 0 and 3), scale (indices 1 and 5) and skew (indices 2 and 4) properties.
The default is [0.0, 1.0, 0.0, 0.0, 0.0, -1.0].
Coordinates of the top left origin of the raster in the spatial reference system of the source, as a point object with x and y members.
Pixel width and height used for georeferencing the raster, as a point object with x and y members. See geotransform for more information.
Skew coefficients used to georeference the raster, as a point object with x and y members. In case of north up images, these coefficients are both 0.
Extent (boundary values) of the raster source, as a 4-tuple (xmin, ymin, xmax, ymax) in the spatial reference system of the source.
List of all bands of the source, as GDALBand instances.
Returns a warped version of this raster.
The warping parameters can be specified through the ds_input argument. The use of ds_input is analogous to the corresponding argument of the class constructor. It is a dictionary with the characteristics of the target raster. Allowed dictionary key values are width, height, SRID, origin, scale, skew, datatype, driver, and name (filename).
By default, the warp functions keeps most parameters equal to the values of the original source raster, so only parameters that should be changed need to be specified. Note that this includes the driver, so for file-based rasters the warp function will create a new raster on disk.
The only parameter that is set differently from the source raster is the name. The default value of the raster name is the name of the source raster appended with '_copy' + source_driver_name. For file-based rasters it is recommended to provide the file path of the target raster.
The resampling algorithm used for warping can be specified with the resampling argument. The default is NearestNeighbor, and the other allowed values are Bilinear, Cubic, CubicSpline, Lanczos, Average, and Mode.
The max_error argument can be used to specify the maximum error measured in input pixels that is allowed in approximating the transformation. The default is 0.0 for exact calculations.
For users familiar with GDAL, this function has a similar functionality to the gdalwarp command-line utility.
For example, the warp function can be used for aggregating a raster to the double of its original pixel scale:
Transforms this raster to a different spatial reference system (srs), which may be a SpatialReference object, or any other input accepted by SpatialReference (including spatial reference WKT and PROJ strings, or an integer SRID).
It calculates the bounds and scale of the current raster in the new spatial reference system and warps the raster using the warp function.
By default, the driver of the source raster is used and the name of the raster is the original name appended with '_copy' + source_driver_name. A different driver or name can be specified with the driver and name arguments.
The default resampling algorithm is NearestNeighbour but can be changed using the resampling argument. The default maximum allowed error for resampling is 0.0 and can be changed using the max_error argument. Consult the warp documentation for detail on those arguments.
Support for SpatialReference srs was added
Returns a string with a summary of the raster. This is equivalent to the gdalinfo command line utility.
The metadata of this raster, represented as a nested dictionary. The first-level key is the metadata domain. The second-level contains the metadata item names and values from each domain.
To set or update a metadata item, pass the corresponding metadata item to the method using the nested structure described above. Only keys that are in the specified dictionary are updated; the rest of the metadata remains unchanged.
To remove a metadata item, use None as the metadata value.
A bytes representation of this raster. Returns None for rasters that are not stored in GDAL’s virtual filesystem.
A boolean indicating if this raster is stored in GDAL’s virtual filesystem.


List of all bands of the source, as GDALBand instances.


The name of the GDAL driver used to handle the input file. For GDALRasters created from a file, the driver type is detected automatically. The creation of rasters from scratch is an in-memory raster by default ('MEM'), but can be altered as needed. For instance, use GTiff for a GeoTiff file. For a list of file types, see also the GDAL Raster Formats list.
An in-memory raster is created through the following example:
A file based GeoTiff raster is created through the following example:


Extent (boundary values) of the raster source, as a 4-tuple (xmin, ymin, xmax, ymax) in the spatial reference system of the source.


The affine transformation matrix used to georeference the source, as a tuple of six coefficients which map pixel/line coordinates into georeferenced space using the following relationship:
The same values can be retrieved by accessing the origin (indices 0 and 3), scale (indices 1 and 5) and skew (indices 2 and 4) properties.
The default is [0.0, 1.0, 0.0, 0.0, 0.0, -1.0].


The height of the source in pixels (Y-axis).


Returns a string with a summary of the raster. This is equivalent to the gdalinfo command line utility.


A boolean indicating if this raster is stored in GDAL’s virtual filesystem.


The metadata of this raster, represented as a nested dictionary. The first-level key is the metadata domain. The second-level contains the metadata item names and values from each domain.
To set or update a metadata item, pass the corresponding metadata item to the method using the nested structure described above. Only keys that are in the specified dictionary are updated; the rest of the metadata remains unchanged.
To remove a metadata item, use None as the metadata value.


The name of the source which is equivalent to the input file path or the name provided upon instantiation.


Coordinates of the top left origin of the raster in the spatial reference system of the source, as a point object with x and y members.


Pixel width and height used for georeferencing the raster, as a point object with x and y members. See geotransform for more information.


Skew coefficients used to georeference the raster, as a point object with x and y members. In case of north up images, these coefficients are both 0.


The Spatial Reference System Identifier (SRID) of the raster. This property is a shortcut to getting or setting the SRID through the srs attribute.


The spatial reference system of the raster, as a SpatialReference instance. The SRS can be changed by setting it to an other SpatialReference or providing any input that is accepted by the SpatialReference constructor.


Transforms this raster to a different spatial reference system (srs), which may be a SpatialReference object, or any other input accepted by SpatialReference (including spatial reference WKT and PROJ strings, or an integer SRID).
It calculates the bounds and scale of the current raster in the new spatial reference system and warps the raster using the warp function.
By default, the driver of the source raster is used and the name of the raster is the original name appended with '_copy' + source_driver_name. A different driver or name can be specified with the driver and name arguments.
The default resampling algorithm is NearestNeighbour but can be changed using the resampling argument. The default maximum allowed error for resampling is 0.0 and can be changed using the max_error argument. Consult the warp documentation for detail on those arguments.
Support for SpatialReference srs was added


A bytes representation of this raster. Returns None for rasters that are not stored in GDAL’s virtual filesystem.


Returns a warped version of this raster.
The warping parameters can be specified through the ds_input argument. The use of ds_input is analogous to the corresponding argument of the class constructor. It is a dictionary with the characteristics of the target raster. Allowed dictionary key values are width, height, SRID, origin, scale, skew, datatype, driver, and name (filename).
By default, the warp functions keeps most parameters equal to the values of the original source raster, so only parameters that should be changed need to be specified. Note that this includes the driver, so for file-based rasters the warp function will create a new raster on disk.
The only parameter that is set differently from the source raster is the name. The default value of the raster name is the name of the source raster appended with '_copy' + source_driver_name. For file-based rasters it is recommended to provide the file path of the target raster.
The resampling algorithm used for warping can be specified with the resampling argument. The default is NearestNeighbor, and the other allowed values are Bilinear, Cubic, CubicSpline, Lanczos, Average, and Mode.
The max_error argument can be used to specify the maximum error measured in input pixels that is allowed in approximating the transformation. The default is 0.0 for exact calculations.
For users familiar with GDAL, this function has a similar functionality to the gdalwarp command-line utility.
For example, the warp function can be used for aggregating a raster to the double of its original pixel scale:


The width of the source in pixels (X-axis).


Adds a geometry to this geometry collection. Not applicable to other geometry types.


Layer is a wrapper for a layer of data in a DataSource object. You never create a Layer object directly. Instead, you retrieve them from a DataSource object, which is essentially a standard Python container of Layer objects. For example, you can access a specific layer by its index (e.g. ds[0] to access the first layer), or you can iterate over all the layers in the container in a for loop. The Layer itself acts as a container for geometric features.
Typically, all the features in a given layer have the same geometry type. The geom_type property of a layer is an OGRGeomType that identifies the feature type. We can use it to print out some basic information about each layer in a DataSource:
The example output is from the cities data source, loaded above, which evidently contains one layer, called "cities", which contains three point features. For simplicity, the examples below assume that you’ve stored that layer in the variable layer:
Returns the name of this layer in the data source.
Returns the number of features in the layer. Same as len(layer):
Returns the geometry type of the layer, as an OGRGeomType object:
Returns the number of fields in the layer, i.e the number of fields of data associated with each feature in the layer:
Returns a list of the names of each of the fields in this layer:
Returns a list of the data types of each of the fields in this layer. These are subclasses of Field, discussed below:
Returns a list of the maximum field widths for each of the fields in this layer:
Returns a list of the numeric precisions for each of the fields in this layer. This is meaningless (and set to zero) for non-numeric fields:
Returns the spatial extent of this layer, as an Envelope object:
Property that returns the SpatialReference associated with this layer:
If the Layer has no spatial reference information associated with it, None is returned.
Property that may be used to retrieve or set a spatial filter for this layer. A spatial filter can only be set with an OGRGeometry instance, a 4-tuple extent, or None. When set with something other than None, only features that intersect the filter will be returned when iterating over the layer:
A method that returns a list of the values of a given field for each feature in the layer:
A method that returns a list containing the geometry of each feature in the layer. If the optional argument geos is set to True then the geometries are converted to GEOSGeometry objects. Otherwise, they are returned as OGRGeometry objects:
Returns a boolean indicating whether this layer supports the given capability (a string). Examples of valid capability strings include: 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter', 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions', 'DeleteFeature', and 'FastSetNextByIndex'.


Returns a list of X coordinates in this line:
Returns a list of Y coordinates in this line:
Returns a list of Z coordinates in this line, or None if the line does not have Z coordinates:


This object is a wrapper for the OGR Geometry class. These objects are instantiated directly from the given geom_input parameter, which may be a string containing WKT, HEX, GeoJSON, a buffer containing WKB data, or an OGRGeomType object. These objects are also returned from the Feature.geom attribute, when reading vector data from Layer (which is in turn a part of a DataSource).
Constructs an OGRGeometry from the given GML string.
Constructs a Polygon from the given bounding-box (a 4-tuple).
Returns the number of points in a LineString, the number of rings in a Polygon, or the number of geometries in a GeometryCollection. Not applicable to other geometry types.
Iterates over the points in a LineString, the rings in a Polygon, or the geometries in a GeometryCollection. Not applicable to other geometry types.
Returns the point at the specified index for a LineString, the interior ring at the specified index for a Polygon, or the geometry at the specified index in a GeometryCollection. Not applicable to other geometry types.
Returns the number of coordinated dimensions of the geometry, i.e. 0 for points, 1 for lines, and so forth:
Returns or sets the coordinate dimension of this geometry. For example, the value would be 2 for two-dimensional geometries.
Returns the number of elements in this geometry:
Returns the number of points used to describe this geometry:
Alias for point_count.
Alias for point_count.
Returns the type of this geometry, as an OGRGeomType object.
Returns the name of the type of this geometry:
Returns the area of this geometry, or 0 for geometries that do not contain an area:
Returns the envelope of this geometry, as an Envelope object.
Returns the envelope of this geometry as a 4-tuple, instead of as an Envelope object:
This property controls the spatial reference for this geometry, or None if no spatial reference system has been assigned to it. If assigned, accessing this property returns a SpatialReference object. It may be set with another SpatialReference object, or any input that SpatialReference accepts. Example:
Returns or sets the spatial reference identifier corresponding to SpatialReference of this geometry. Returns None if there is no spatial reference information associated with this geometry, or if an SRID cannot be determined.
Returns a GEOSGeometry object corresponding to this geometry.
Returns a string representation of this geometry in GML format:
Returns a string representation of this geometry in HEX WKB format:
Returns a string representation of this geometry in JSON format:
Returns a string representation of this geometry in KML format.
Returns the size of the WKB buffer needed to hold a WKB representation of this geometry:
Returns a buffer containing a WKB representation of this geometry.
Returns a string representation of this geometry in WKT format.
Returns the EWKT representation of this geometry.
Returns a new OGRGeometry clone of this geometry object.
If there are any rings within this geometry that have not been closed, this routine will do so by adding the starting point to the end:
Transforms this geometry to a different spatial reference system. May take a CoordTransform object, a SpatialReference object, or any other input accepted by SpatialReference (including spatial reference WKT and PROJ strings, or an integer SRID).
By default nothing is returned and the geometry is transformed in-place. However, if the clone keyword is set to True then a transformed clone of this geometry is returned instead.
Returns True if this geometry intersects the other, otherwise returns False.
Returns True if this geometry is equivalent to the other, otherwise returns False.
Returns True if this geometry is spatially disjoint to (i.e. does not intersect) the other, otherwise returns False.
Returns True if this geometry touches the other, otherwise returns False.
Returns True if this geometry crosses the other, otherwise returns False.
Returns True if this geometry is contained within the other, otherwise returns False.
Returns True if this geometry contains the other, otherwise returns False.
Returns True if this geometry overlaps the other, otherwise returns False.
The boundary of this geometry, as a new OGRGeometry object.
The smallest convex polygon that contains this geometry, as a new OGRGeometry object.
Returns the region consisting of the difference of this geometry and the other, as a new OGRGeometry object.
Returns the region consisting of the intersection of this geometry and the other, as a new OGRGeometry object.
Returns the region consisting of the symmetric difference of this geometry and the other, as a new OGRGeometry object.
Returns the region consisting of the union of this geometry and the other, as a new OGRGeometry object.
Returns the coordinates of a point geometry as a tuple, the coordinates of a line geometry as a tuple of tuples, and so forth:
An alias for tuple.


This class allows for the representation of an OGR geometry type in any of several ways:
Returns a short-hand string form of the OGR Geometry type:
Returns the number corresponding to the OGR geometry type:
Returns the Django field type (a subclass of GeometryField) to use for storing this OGR type, or None if there is no appropriate Django type:


Returns the X coordinate of this point:
Returns the Y coordinate of this point:
Returns the Z coordinate of this point, or None if the point does not have a Z coordinate:


Returns the shell or exterior ring of this polygon, as a LinearRing geometry.
An alias for shell.
Returns a Point representing the centroid of this polygon.


Spatial reference objects are initialized on the given srs_input, which may be one of the following:
Example:
Returns the value of the given string attribute node, None if the node doesn’t exist. Can also take a tuple as a parameter, (target, child), where child is the index of the attribute in the WKT. For example:
The attribute value for the given target node (e.g. 'PROJCS'). The index keyword specifies an index of the child node to return.
Returns the authority name for the given string target node.
Returns the authority code for the given string target node.
Returns a clone of this spatial reference object.
This method inspects the WKT of this SpatialReference and will add EPSG authority nodes where an EPSG identifier is applicable.
Morphs this SpatialReference from ESRI’s format to EPSG
Morphs this SpatialReference to ESRI’s format.
Checks to see if the given spatial reference is valid, if not an exception will be raised.
Import spatial reference from EPSG code.
Import spatial reference from PROJ string.
Import spatial reference from WKT.
Import spatial reference from XML.
Returns the name of this Spatial Reference.
Returns the SRID of top-level authority, or None if undefined.
Returns the name of the linear units.
Returns the value of the linear units.
Returns the name of the angular units.”
Returns the value of the angular units.
Returns a 2-tuple of the units value and the units name and will automatically determines whether to return the linear or angular units.
Returns a tuple of the ellipsoid parameters for this spatial reference: (semimajor axis, semiminor axis, and inverse flattening).
Returns the semi major axis of the ellipsoid for this spatial reference.
Returns the semi minor axis of the ellipsoid for this spatial reference.
Returns the inverse flattening of the ellipsoid for this spatial reference.
Returns True if this spatial reference is geographic (root node is GEOGCS).
Returns True if this spatial reference is local (root node is LOCAL_CS).
Returns True if this spatial reference is a projected coordinate system (root node is PROJCS).
Returns the WKT representation of this spatial reference.
Returns the ‘pretty’ representation of the WKT.
Returns the PROJ representation for this spatial reference.
Alias for SpatialReference.proj.
Returns the XML representation of this spatial reference.


a GEOSGeometry corresponding to the spatial data in the string
fromstr(string, srid) is equivalent to GEOSGeometry(string, srid).
Example:


GeometryCollection objects may be instantiated by passing in other GEOSGeometry as arguments, or a single sequence of GEOSGeometry objects:


This property returns the area of the Geometry.


Returns the boundary as a newly allocated Geometry object.


Returns a GEOSGeometry that represents all points whose distance from this geometry is less than or equal to the given width. The optional quadsegs keyword sets the number of segments used to approximate a quarter circle (defaults is 8).


Same as buffer(), but allows customizing the style of the buffer.


Returns a Point object representing the geometric center of the geometry. The point is not guaranteed to be on the interior of the geometry.


This method returns a GEOSGeometry that is a clone of the original.


Returns True if other.within(this) returns True.


Returns the smallest Polygon that contains all the points in the geometry.


Returns the coordinates of the geometry as a tuple.


Returns True if this geometry covers the specified geometry.
The covers predicate has the following equivalent definitions:
If either geometry is empty, returns False.
This predicate is similar to GEOSGeometry.contains(), but is more inclusive (i.e. returns True for more cases). In particular, unlike contains() it does not distinguish between points in the boundary and in the interior of geometries. For most situations, covers() should be preferred to contains(). As an added benefit, covers() is more amenable to optimization and hence should outperform contains().


Returns True if the DE-9IM intersection matrix for the two Geometries is T*T****** (for a point and a curve,a point and an area or a line and an area) 0******** (for two curves).


Returns a GEOSGeometry representing the points making up this geometry that do not make up other.


Returns True if the DE-9IM intersection matrix for the two geometries is FF*FF****.


Returns the distance between the closest points on this geometry and the given geom (another GEOSGeometry object).
Note
GEOS distance calculations are linear – in other words, GEOS does not perform a spherical calculation even if the SRID specifies a geographic coordinate system.


Returns whether or not the set of points in the geometry is empty.


Returns a Polygon that represents the bounding envelope of this geometry. Note that it can also return a Point if the input geometry is a point.


Returns True if the DE-9IM intersection matrix for the two geometries is T*F**FFF*.


Returns true if the two geometries are exactly equal, up to a specified tolerance. The tolerance value should be a floating point number representing the error tolerance in the comparison, e.g., poly1.equals_exact(poly2, 0.001) will compare equality to within one thousandth of a unit.


Return the EWKB representation of this Geometry as a Python buffer. This is an extension of the WKB specification that includes any SRID value that are a part of this geometry.


Returns the “extended” Well-Known Text of the geometry. This representation is specific to PostGIS and is a superset of the OGC WKT standard. [1] Essentially the SRID is prepended to the WKT representation, for example SRID=4326;POINT(5 23).
Note
The output from this property does not include the 3dm, 3dz, and 4d information that PostGIS supports in its EWKT representations.


This property returns the extent of this geometry as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).


Returns a string corresponding to the type of geometry. For example:


Returns the GEOS geometry type identification number. The following table shows the value for each geometry type:


Returns a boolean indicating whether the geometry is three-dimensional.


Returns the WKB of this Geometry in hexadecimal form. Please note that the SRID value is not included in this representation because it is not a part of the OGC specification (use the GEOSGeometry.hexewkb property instead).


Returns the EWKB of this Geometry in hexadecimal form. This is an extension of the WKB specification that includes the SRID value that are a part of this geometry.


Given a distance (float), returns the point (or closest point) within the geometry (LineString or MultiLineString) at that distance. The normalized version takes the distance as a float between 0 (origin) and 1 (endpoint).
Reverse of GEOSGeometry.project().


Returns a GEOSGeometry representing the points shared by this geometry and other.


Returns True if GEOSGeometry.disjoint() is False.


Returns the GeoJSON representation of the geometry. Note that the result is not a complete GeoJSON structure but only the geometry key content of a GeoJSON structure. See also GeoJSON Serializer.


Returns a KML (Keyhole Markup Language) representation of the geometry. This should only be used for geometries with an SRID of 4326 (WGS84), but this restriction is not enforced.


Returns the length of this geometry (e.g., 0 for a Point, the length of a LineString, or the circumference of a Polygon).


Converts this geometry to canonical form:


Returns the number of coordinates in the geometry.


Returns the number of geometries in this geometry. In other words, will return 1 on anything but geometry collections.


Returns an OGRGeometry object corresponding to the GEOS geometry.


Returns true if the DE-9IM intersection matrix for the two geometries is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves).


Computes and returns a Point guaranteed to be on the interior of this geometry.


Returns a GEOS PreparedGeometry for the contents of this geometry. PreparedGeometry objects are optimized for the contains, intersects, covers, crosses, disjoint, overlaps, touches and within operations. Refer to the Prepared Geometries documentation for more information.


Returns the distance (float) from the origin of the geometry (LineString or MultiLineString) to the point projected on the geometry (that is to a point of the line the closest to the given point). The normalized version returns the distance as a float between 0 (origin) and 1 (endpoint).
Reverse of GEOSGeometry.interpolate().


Returns the DE-9IM intersection matrix (a string) representing the topological relationship between this geometry and the other.


Returns True if the elements in the DE-9IM intersection matrix for this geometry and the other matches the given pattern – a string of nine characters from the alphabet: {T, F, *, 0}.


Returns a boolean indicating whether the geometry is a LinearRing.


Returns a boolean indicating whether the geometry is ‘simple’. A geometry is simple if and only if it does not intersect itself (except at boundary points). For example, a LineString object is not simple if it intersects itself. Thus, LinearRing and Polygon objects are always simple because they do cannot intersect themselves, by definition.


Returns a new GEOSGeometry, simplified to the specified tolerance using the Douglas-Peucker algorithm. A higher tolerance value implies fewer points in the output. If no tolerance is provided, it defaults to 0.
By default, this function does not preserve topology. For example, Polygon objects can be split, be collapsed into lines, or disappear. Polygon holes can be created or disappear, and lines may cross. By specifying preserve_topology=True, the result will have the same dimension and number of components as the input; this is significantly slower, however.


Property that may be used to retrieve or set the SRID associated with the geometry. For example:


Returns a SpatialReference object corresponding to the SRID of the geometry or None.


Returns a GEOSGeometry combining the points in this geometry not in other, and the points in other not in this geometry.


Returns True if the DE-9IM intersection matrix for the two geometries is FT*******, F**T***** or F***T****.


Transforms the geometry according to the given coordinate transformation parameter (ct), which may be an integer SRID, spatial reference WKT string, a PROJ string, a SpatialReference object, or a CoordTransform object. By default, the geometry is transformed in-place and nothing is returned. However if the clone keyword is set, then the geometry is not modified and a transformed clone of the geometry is returned instead.
Note
Raises GEOSException if GDAL is not available or if the geometry’s SRID is None or less than 0. It doesn’t impose any constraints on the geometry’s SRID if called with a CoordTransform object.


Computes the union of all the elements of this geometry.
The result obeys the following contract:


Returns a GEOSGeometry representing all the points in this geometry and the other.


Returns a boolean indicating whether the geometry is valid.


Returns a string describing the reason why a geometry is invalid.


Returns True if the DE-9IM intersection matrix for the two geometries is T*F**F***.


Returns the WKB (Well-Known Binary) representation of this Geometry as a Python buffer. SRID value is not included, use the GEOSGeometry.ewkb property instead.


Returns the Well-Known Text of the geometry (an OGC standard).


LinearRing objects are constructed in the exact same way as LineString objects, however the coordinates must be closed, in other words, the first coordinates must be the same as the last coordinates. For example:
Notice that (0, 0) is the first and last coordinate – if they were not equal, an error would be raised.
Returns whether this LinearRing is counterclockwise.


Returns whether this LinearRing is counterclockwise.


LineString objects are instantiated using arguments that are either a sequence of coordinates or Point objects. For example, the following are equivalent:
In addition, LineString objects may also be created by passing in a single sequence of coordinate or Point objects:
Empty LineString objects may be instantiated by passing no arguments or an empty sequence. The following are equivalent:
Returns whether or not this LineString is closed.


Returns whether or not this LineString is closed.


MultiLineString objects may be instantiated by passing in LineString objects as arguments, or a single sequence of LineString objects:
Returns a LineString representing the line merge of all the components in this MultiLineString.
Returns True if and only if all elements are closed.


Returns True if and only if all elements are closed.


Returns a LineString representing the line merge of all the components in this MultiLineString.


MultiPoint objects may be instantiated by passing in Point objects as arguments, or a single sequence of Point objects:


MultiPolygon objects may be instantiated by passing Polygon objects as arguments, or a single sequence of Polygon objects:


Point objects are instantiated using arguments that represent the component coordinates of the point or with a single sequence coordinates. For example, the following are equivalent:
Empty Point objects may be instantiated by passing no arguments or an empty sequence. The following are equivalent:


Polygon objects may be instantiated by passing in parameters that represent the rings of the polygon. The parameters must either be LinearRing instances, or a sequence that may be used to construct a LinearRing:
Returns a polygon object from the given bounding-box, a 4-tuple comprising (xmin, ymin, xmax, ymax).
Returns the number of interior rings in this geometry.


Returns the number of interior rings in this geometry.


All methods on PreparedGeometry take an other argument, which must be a GEOSGeometry instance.


WKBWriter provides the most control over its output. By default it returns OGC-compliant WKB when its write method is called. However, it has properties that allow for the creation of EWKB, a superset of the WKB standard that includes additional information. See the WKBWriter.outdim documentation for more details about the dim argument.
Returns the WKB of the given geometry as a Python buffer object. Example:
Returns WKB of the geometry in hexadecimal. Example:
This property may be set to change the byte-order of the geometry representation.
Example:
This property may be set to change the output dimension of the geometry representation. In other words, if you have a 3D geometry then set to 3 so that the Z value is included in the WKB.
Example:
Set this property with a boolean to indicate whether the SRID of the geometry should be included with the WKB representation. Example: