Tells Django that this expression contains an aggregate and that a GROUP BY clause needs to be added to the query.
Tells Django that this expression contains a Window expression. It’s used, for example, to disallow window function expressions in queries that modify data.
Tells Django that this expression can be referenced in QuerySet.filter(). Defaults to True.
Tells Django that this expression can be used as the source expression in Window. Defaults to False.
Tells Django which value should be returned when the expression is used to apply a function over an empty result set. Defaults to NotImplemented which forces the expression to be computed on the database.
Provides the chance to do any pre-processing or validation of the expression before it’s added to the query. resolve_expression() must also be called on any nested expressions. A copy() of self should be returned with any necessary transformations.
query is the backend query implementation.
allow_joins is a boolean that allows or denies the use of joins in the query.
reuse is a set of reusable joins for multi-join scenarios.
summarize is a boolean that, when True, signals that the query being computed is a terminal aggregate query.
for_save is a boolean that, when True, signals that the query being executed is performing a create or update.
Returns an ordered list of inner expressions. For example:
Takes a list of expressions and stores them such that get_source_expressions() can return them.
Returns a clone (copy) of self, with any column aliases relabeled. Column aliases are renamed when subqueries are created. relabeled_clone() should also be called on any nested expressions and assigned to the clone.
change_map is a dictionary mapping old aliases to new aliases.
Example:
A hook allowing the expression to coerce value into a more appropriate type.
expression is the same as self.
Responsible for returning the list of columns references by this expression. get_group_by_cols() should be called on any nested expressions. F() objects, in particular, hold a reference to a column. The alias parameter will be None unless the expression has been annotated and is used for grouping.
Returns the expression ready to be sorted in ascending order.
nulls_first and nulls_last define how null values are sorted. See Using F() to sort null values for example usage.
Returns the expression ready to be sorted in descending order.
nulls_first and nulls_last define how null values are sorted. See Using F() to sort null values for example usage.
Returns self with any modifications required to reverse the sort order within an order_by call. As an example, an expression implementing NULLS LAST would change its value to be NULLS FIRST. Modifications are only required for expressions that implement sort order like OrderBy. This method is called when reverse() is called on a queryset.


Returns the expression ready to be sorted in ascending order.
nulls_first and nulls_last define how null values are sorted. See Using F() to sort null values for example usage.


Tells Django that this expression contains an aggregate and that a GROUP BY clause needs to be added to the query.


Tells Django that this expression contains a Window expression. It’s used, for example, to disallow window function expressions in queries that modify data.


A hook allowing the expression to coerce value into a more appropriate type.
expression is the same as self.


Returns the expression ready to be sorted in descending order.
nulls_first and nulls_last define how null values are sorted. See Using F() to sort null values for example usage.


Tells Django which value should be returned when the expression is used to apply a function over an empty result set. Defaults to NotImplemented which forces the expression to be computed on the database.


Tells Django that this expression can be referenced in QuerySet.filter(). Defaults to True.


Responsible for returning the list of columns references by this expression. get_group_by_cols() should be called on any nested expressions. F() objects, in particular, hold a reference to a column. The alias parameter will be None unless the expression has been annotated and is used for grouping.


Returns an ordered list of inner expressions. For example:


Returns a clone (copy) of self, with any column aliases relabeled. Column aliases are renamed when subqueries are created. relabeled_clone() should also be called on any nested expressions and assigned to the clone.
change_map is a dictionary mapping old aliases to new aliases.
Example:


Provides the chance to do any pre-processing or validation of the expression before it’s added to the query. resolve_expression() must also be called on any nested expressions. A copy() of self should be returned with any necessary transformations.
query is the backend query implementation.
allow_joins is a boolean that allows or denies the use of joins in the query.
reuse is a set of reusable joins for multi-join scenarios.
summarize is a boolean that, when True, signals that the query being computed is a terminal aggregate query.
for_save is a boolean that, when True, signals that the query being executed is performing a create or update.


Returns self with any modifications required to reverse the sort order within an order_by call. As an example, an expression implementing NULLS LAST would change its value to be NULLS FIRST. Modifications are only required for expressions that implement sort order like OrderBy. This method is called when reverse() is called on a queryset.


Takes a list of expressions and stores them such that get_source_expressions() can return them.


Tells Django that this expression can be used as the source expression in Window. Defaults to False.


This attribute is set to 'RANGE'.
PostgreSQL has limited support for ValueRange and only supports use of the standard start and end points, such as CURRENT ROW and UNBOUNDED
FOLLOWING.


Defaults to False. The SQL standard disallows referencing window functions in the WHERE clause and Django raises an exception when constructing a QuerySet that would do that.
Defaults to %(expression)s OVER (%(window)s)'. If only the expression argument is provided, the window clause will be blank.


Defaults to False. The SQL standard disallows referencing window functions in the WHERE clause and Django raises an exception when constructing a QuerySet that would do that.


Defaults to %(expression)s OVER (%(window)s)'. If only the expression argument is provided, the window clause will be blank.


Field is an abstract class that represents a database table column. Django uses fields to create the database table (db_type()), to map Python types to database (get_prep_value()) and vice-versa (from_db_value()).
A field is thus a fundamental piece in different Django APIs, notably, models and querysets.
In models, a field is instantiated as a class attribute and represents a particular table column, see Models. It has attributes such as null and unique, and methods that Django uses to map the field value to database-specific values.
A Field is a subclass of RegisterLookupMixin and thus both Transform and Lookup can be registered on it to be used in QuerySets (e.g. field_name__exact="foo"). All built-in lookups are registered by default.
All of Django’s built-in fields, such as CharField, are particular implementations of Field. If you need a custom field, you can either subclass any of the built-in fields or write a Field from scratch. In either case, see How to create custom model fields.
A verbose description of the field, e.g. for the django.contrib.admindocs application.
The description can be of the form:
where the arguments are interpolated from the field’s __dict__.
A class implementing the descriptor protocol that is instantiated and assigned to the model instance attribute. The constructor must accept a single argument, the Field instance. Overriding this class attribute allows for customizing the get and set behavior.
To map a Field to a database-specific type, Django exposes several methods:
Returns a string naming this field for backend specific purposes. By default, it returns the class name.
See Emulating built-in field types for usage in custom fields.
Returns the database column data type for the Field, taking into account the connection.
See Custom database types for usage in custom fields.
Returns the database column data type for fields such as ForeignKey and OneToOneField that point to the Field, taking into account the connection.
See Custom database types for usage in custom fields.
There are three main situations where Django needs to interact with the database backend and fields:
When querying, get_db_prep_value() and get_prep_value() are used:
value is the current value of the model’s attribute, and the method should return data in a format that has been prepared for use as a parameter in a query.
See Converting Python objects to query values for usage.
Converts value to a backend-specific value. By default it returns value if prepared=True and get_prep_value() if is False.
See Converting query values to database values for usage.
When loading data, from_db_value() is used:
Converts a value as returned by the database to a Python object. It is the reverse of get_prep_value().
This method is not used for most built-in fields as the database backend already returns the correct Python type, or the backend itself does the conversion.
expression is the same as self.
See Converting values to Python objects for usage.
Note
For performance reasons, from_db_value is not implemented as a no-op on fields which do not require it (all Django fields). Consequently you may not call super in your definition.
When saving, pre_save() and get_db_prep_save() are used:
Same as the get_db_prep_value(), but called when the field value must be saved to the database. By default returns get_db_prep_value().
Method called prior to get_db_prep_save() to prepare the value before being saved (e.g. for DateField.auto_now).
model_instance is the instance this field belongs to and add is whether the instance is being saved to the database for the first time.
It should return the value of the appropriate attribute from model_instance for this field. The attribute name is in self.attname (this is set up by Field).
See Preprocessing values before saving for usage.
Fields often receive their values as a different type, either from serialization or from forms.
Converts the value into the correct Python object. It acts as the reverse of value_to_string(), and is also called in clean().
See Converting values to Python objects for usage.
Besides saving to the database, the field also needs to know how to serialize its value:
Returns the field’s value for the given model instance.
This method is often used by value_to_string().
Converts obj to a string. Used to serialize the value of the field.
See Converting field data for serialization for usage.
When using model forms, the Field needs to know which form field it should be represented by:
Returns the default django.forms.Field of this field for ModelForm.
By default, if both form_class and choices_form_class are None, it uses CharField. If the field has choices and choices_form_class isn’t specified, it uses TypedChoiceField.
See Specifying the form field for a model field for usage.
Returns a 4-tuple with enough information to recreate the field:
This method must be added to fields prior to 1.7 to migrate its data using Migrations.


Boolean flag that indicates if the field was automatically created, such as the OneToOneField used by model inheritance.


Boolean flag that indicates if the field has a database column associated with it.


Returns the database column data type for the Field, taking into account the connection.
See Custom database types for usage in custom fields.


Returns a 4-tuple with enough information to recreate the field:
This method must be added to fields prior to 1.7 to migrate its data using Migrations.


A verbose description of the field, e.g. for the django.contrib.admindocs application.
The description can be of the form:
where the arguments are interpolated from the field’s __dict__.


A class implementing the descriptor protocol that is instantiated and assigned to the model instance attribute. The constructor must accept a single argument, the Field instance. Overriding this class attribute allows for customizing the get and set behavior.


Returns the default django.forms.Field of this field for ModelForm.
By default, if both form_class and choices_form_class are None, it uses CharField. If the field has choices and choices_form_class isn’t specified, it uses TypedChoiceField.
See Specifying the form field for a model field for usage.


Converts a value as returned by the database to a Python object. It is the reverse of get_prep_value().
This method is not used for most built-in fields as the database backend already returns the correct Python type, or the backend itself does the conversion.
expression is the same as self.
See Converting values to Python objects for usage.
Note
For performance reasons, from_db_value is not implemented as a no-op on fields which do not require it (all Django fields). Consequently you may not call super in your definition.


Same as the get_db_prep_value(), but called when the field value must be saved to the database. By default returns get_db_prep_value().


Converts value to a backend-specific value. By default it returns value if prepared=True and get_prep_value() if is False.
See Converting query values to database values for usage.


Returns a string naming this field for backend specific purposes. By default, it returns the class name.
See Emulating built-in field types for usage in custom fields.


value is the current value of the model’s attribute, and the method should return data in a format that has been prepared for use as a parameter in a query.
See Converting Python objects to query values for usage.


Boolean flag that indicates if a field is used to back another non-hidden field’s functionality (e.g. the content_type and object_id fields that make up a GenericForeignKey). The hidden flag is used to distinguish what constitutes the public subset of fields on the model from all the fields on the model.
Note
Options.get_fields() excludes hidden fields by default. Pass in include_hidden=True to return hidden fields in the results.


Boolean flag that indicates if a field contains references to one or more other models for its functionality (e.g. ForeignKey, ManyToManyField, OneToOneField, etc.).


Boolean flag that is True if the field has a many-to-many relation; False otherwise. The only field included with Django where this is True is ManyToManyField.


Boolean flag that is True if the field has a many-to-one relation, such as a ForeignKey; False otherwise.


Returns the model on which the field is defined. If a field is defined on a superclass of a model, model will refer to the superclass, not the class of the instance.


Boolean flag that is True if the field has a one-to-many relation, such as a GenericRelation or the reverse of a ForeignKey; False otherwise.


Boolean flag that is True if the field has a one-to-one relation, such as a OneToOneField; False otherwise.


Method called prior to get_db_prep_save() to prepare the value before being saved (e.g. for DateField.auto_now).
model_instance is the instance this field belongs to and add is whether the instance is being saved to the database for the first time.
It should return the value of the appropriate attribute from model_instance for this field. The attribute name is in self.attname (this is set up by Field).
See Preprocessing values before saving for usage.


Returns the database column data type for fields such as ForeignKey and OneToOneField that point to the Field, taking into account the connection.
See Custom database types for usage in custom fields.


Points to the model the field relates to. For example, Author in ForeignKey(Author, on_delete=models.CASCADE). The related_model for a GenericForeignKey is always None.


Converts the value into the correct Python object. It acts as the reverse of value_to_string(), and is also called in clean().
See Converting values to Python objects for usage.


Returns the field’s value for the given model instance.
This method is often used by value_to_string().


Converts obj to a string. Used to serialize the value of the field.
See Converting field data for serialization for usage.


A “related manager” is a manager used in a one-to-many or many-to-many related context. This happens in two cases:
The “other side” of a ForeignKey relation. That is:
In the above example, the methods below will be available on the manager blog.entry_set.
Both sides of a ManyToManyField relation:
In this example, the methods below will be available both on topping.pizza_set and on pizza.toppings.
Adds the specified model objects to the related object set.
Example:
In the example above, in the case of a ForeignKey relationship, QuerySet.update() is used to perform the update. This requires the objects to already be saved.
You can use the bulk=False argument to instead have the related manager perform the update by calling e.save().
Using add() with a many-to-many relationship, however, will not call any save() methods (the bulk argument doesn’t exist), but rather create the relationships using QuerySet.bulk_create(). If you need to execute some custom logic when a relationship is created, listen to the m2m_changed signal, which will trigger pre_add and post_add actions.
Using add() on a relation that already exists won’t duplicate the relation, but it will still trigger signals.
For many-to-many relationships add() accepts either model instances or field values, normally primary keys, as the *objs argument.
Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s).
Creates a new object, saves it and puts it in the related object set. Returns the newly created object:
This is equivalent to (but simpler than):
Note that there’s no need to specify the keyword argument of the model that defines the relationship. In the above example, we don’t pass the parameter blog to create(). Django figures out that the new Entry object’s blog field should be set to b.
Use the through_defaults argument to specify values for the new intermediate model instance, if needed. You can use callables as values in the through_defaults dictionary.
Removes the specified model objects from the related object set:
Similar to add(), e.save() is called in the example above to perform the update. Using remove() with a many-to-many relationship, however, will delete the relationships using QuerySet.delete() which means no model save() methods are called; listen to the m2m_changed signal if you wish to execute custom code when a relationship is deleted.
For many-to-many relationships remove() accepts either model instances or field values, normally primary keys, as the *objs argument.
For ForeignKey objects, this method only exists if null=True. If the related field can’t be set to None (NULL), then an object can’t be removed from a relation without being added to another. In the above example, removing e from b.entry_set() is equivalent to doing e.blog = None, and because the blog ForeignKey doesn’t have null=True, this is invalid.
For ForeignKey objects, this method accepts a bulk argument to control how to perform the operation. If True (the default), QuerySet.update() is used. If bulk=False, the save() method of each individual model instance is called instead. This triggers the pre_save and post_save signals and comes at the expense of performance.
For many-to-many relationships, the bulk keyword argument doesn’t exist.
Removes all objects from the related object set:
Note this doesn’t delete the related objects – it just disassociates them.
Just like remove(), clear() is only available on ForeignKeys where null=True and it also accepts the bulk keyword argument.
For many-to-many relationships, the bulk keyword argument doesn’t exist.
Replace the set of related objects:
This method accepts a clear argument to control how to perform the operation. If False (the default), the elements missing from the new set are removed using remove() and only the new ones are added. If clear=True, the clear() method is called instead and the whole set is added at once.
For ForeignKey objects, the bulk argument is passed on to add() and remove().
For many-to-many relationships, the bulk keyword argument doesn’t exist.
Note that since set() is a compound operation, it is subject to race conditions. For instance, new objects may be added to the database in between the call to clear() and the call to add().
For many-to-many relationships set() accepts a list of either model instances or field values, normally primary keys, as the objs argument.
Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s).
Note
Note that add(), create(), remove(), clear(), and set() all apply database changes immediately for all types of related fields. In other words, there is no need to call save() on either end of the relationship.
If you use prefetch_related(), the add(), remove(), clear(), and set() methods clear the prefetched cache.


Adds the specified model objects to the related object set.
Example:
In the example above, in the case of a ForeignKey relationship, QuerySet.update() is used to perform the update. This requires the objects to already be saved.
You can use the bulk=False argument to instead have the related manager perform the update by calling e.save().
Using add() with a many-to-many relationship, however, will not call any save() methods (the bulk argument doesn’t exist), but rather create the relationships using QuerySet.bulk_create(). If you need to execute some custom logic when a relationship is created, listen to the m2m_changed signal, which will trigger pre_add and post_add actions.
Using add() on a relation that already exists won’t duplicate the relation, but it will still trigger signals.
For many-to-many relationships add() accepts either model instances or field values, normally primary keys, as the *objs argument.
Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s).


Removes all objects from the related object set:
Note this doesn’t delete the related objects – it just disassociates them.
Just like remove(), clear() is only available on ForeignKeys where null=True and it also accepts the bulk keyword argument.
For many-to-many relationships, the bulk keyword argument doesn’t exist.


Creates a new object, saves it and puts it in the related object set. Returns the newly created object:
This is equivalent to (but simpler than):
Note that there’s no need to specify the keyword argument of the model that defines the relationship. In the above example, we don’t pass the parameter blog to create(). Django figures out that the new Entry object’s blog field should be set to b.
Use the through_defaults argument to specify values for the new intermediate model instance, if needed. You can use callables as values in the through_defaults dictionary.


Removes the specified model objects from the related object set:
Similar to add(), e.save() is called in the example above to perform the update. Using remove() with a many-to-many relationship, however, will delete the relationships using QuerySet.delete() which means no model save() methods are called; listen to the m2m_changed signal if you wish to execute custom code when a relationship is deleted.
For many-to-many relationships remove() accepts either model instances or field values, normally primary keys, as the *objs argument.
For ForeignKey objects, this method only exists if null=True. If the related field can’t be set to None (NULL), then an object can’t be removed from a relation without being added to another. In the above example, removing e from b.entry_set() is equivalent to doing e.blog = None, and because the blog ForeignKey doesn’t have null=True, this is invalid.
For ForeignKey objects, this method accepts a bulk argument to control how to perform the operation. If True (the default), QuerySet.update() is used. If bulk=False, the save() method of each individual model instance is called instead. This triggers the pre_save and post_save signals and comes at the expense of performance.
For many-to-many relationships, the bulk keyword argument doesn’t exist.


Replace the set of related objects:
This method accepts a clear argument to control how to perform the operation. If False (the default), the elements missing from the new set are removed using remove() and only the new ones are added. If clear=True, the clear() method is called instead and the whole set is added at once.
For ForeignKey objects, the bulk argument is passed on to add() and remove().
For many-to-many relationships, the bulk keyword argument doesn’t exist.
Note that since set() is a compound operation, it is subject to race conditions. For instance, new objects may be added to the database in between the call to clear() and the call to add().
For many-to-many relationships set() accepts a list of either model instances or field values, normally primary keys, as the objs argument.
Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s).


A storage object, or a callable which returns a storage object. This handles the storage and retrieval of your files. See Managing files for details on how to provide this object.


This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method.
If you specify a string value or a Path, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example:
If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored. If you are using a different storage, check that storage’s documentation to see how it handles upload_to.
upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are:
An instance of the model where the FileField is defined. More specifically, this is the particular instance where the current file is being attached.
In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field.
For example:


Optional. Either True or False. Default is True. Specifies whether files in the specified location should be included. Either this or allow_folders must be True.


Optional. Either True or False. Default is False. Specifies whether folders in the specified location should be included. Either this or allow_files must be True.


Optional. A regular expression, as a string, that FilePathField will use to filter filenames. Note that the regex will be applied to the base filename, not the full path. Example: "foo.*\.txt$", which will match a file called foo23.txt but not bar.txt or foo23.png.


Required. The absolute filesystem path to a directory from which this FilePathField should get its choices. Example: "/home/images".
path may also be a callable, such as a function to dynamically set the path at runtime. Example:


Optional. Either True or False. Default is False. Specifies whether all subdirectories of path should be included


The name of the field on which you’d like to filter the relation.
A Q object to control the filtering.


The name of the field on which you’d like to filter the relation.


Controls whether or not a constraint should be created in the database for this foreign key. The default is True, and that’s almost certainly what you want; setting this to False can be very bad for data integrity. That said, here are some scenarios where you might want to do this:
If this is set to False, accessing a related object that doesn’t exist will raise its DoesNotExist exception.


Sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.
For example:
causes the corresponding field on the ModelForm to list only Users that have is_staff=True. This may be helpful in the Django admin.
The callable form can be helpful, for instance, when used in conjunction with the Python datetime module to limit selections by date range. For example:
If limit_choices_to is or returns a Q object, which is useful for complex queries, then it will only have an effect on the choices available in the admin when the field is not listed in raw_id_fields in the ModelAdmin for the model.
Note
If a callable is used for limit_choices_to, it will be invoked every time a new form is instantiated. It may also be invoked when a model is validated, for example by management commands or the admin. The admin constructs querysets to validate its form inputs in various edge cases multiple times, so there is a possibility your callable may be invoked several times.


When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:
on_delete doesn’t create an SQL constraint in the database. Support for database-level cascade options may be implemented later.


The name to use for the relation from the related object back to this one. It’s also the default value for related_query_name (the name to use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available.
If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model won’t have a backwards relation to this model:


The name to use for the reverse filter name from the target model. It defaults to the value of related_name or default_related_name if set, otherwise it defaults to the name of the model:
Like related_name, related_query_name supports app label and class interpolation via some special syntax.


Controls the migration framework’s reaction if this ForeignKey is pointing at a swappable model. If it is True - the default - then if the ForeignKey is pointing at a model which matches the current value of settings.AUTH_USER_MODEL (or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.
You only want to override this to be False if you are sure your model should always point toward the swapped-in model - for example, if it is a profile model designed specifically for your custom user model.
Setting it to False does not mean you can reference a swappable model even if it is swapped out - False means that the migrations made with this ForeignKey will always reference the exact model you specify (so it will fail hard if the user tries to run with a User model you don’t support, for example).
If in doubt, leave it to its default of True.


The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True.


A class attribute describing the function that will be generated. Specifically, the function will be interpolated as the function placeholder within template. Defaults to None.
A class attribute, as a format string, that describes the SQL that is generated for this function. Defaults to '%(function)s(%(expressions)s)'.
If you’re constructing SQL like strftime('%W', 'date') and need a literal % character in the query, quadruple it (%%%%) in the template attribute because the string is interpolated twice: once during the template interpolation in as_sql() and once in the SQL interpolation with the query parameters in the database cursor.
A class attribute that denotes the character used to join the list of expressions together. Defaults to ', '.
A class attribute that denotes the number of arguments the function accepts. If this attribute is set and the function is called with a different number of expressions, TypeError will be raised. Defaults to None.
Generates the SQL fragment for the database function. Returns a tuple (sql, params), where sql is the SQL string, and params is the list or tuple of query parameters.
The as_vendor() methods should use the function, template, arg_joiner, and any other **extra_context parameters to customize the SQL as needed. For example:
To avoid an SQL injection vulnerability, extra_context must not contain untrusted user input as these values are interpolated into the SQL string rather than passed as query parameters, where the database driver would escape them.


A class attribute that denotes the character used to join the list of expressions together. Defaults to ', '.


A class attribute that denotes the number of arguments the function accepts. If this attribute is set and the function is called with a different number of expressions, TypeError will be raised. Defaults to None.


Generates the SQL fragment for the database function. Returns a tuple (sql, params), where sql is the SQL string, and params is the list or tuple of query parameters.
The as_vendor() methods should use the function, template, arg_joiner, and any other **extra_context parameters to customize the SQL as needed. For example:
To avoid an SQL injection vulnerability, extra_context must not contain untrusted user input as these values are interpolated into the SQL string rather than passed as query parameters, where the database driver would escape them.


A class attribute describing the function that will be generated. Specifically, the function will be interpolated as the function placeholder within template. Defaults to None.


A class attribute, as a format string, that describes the SQL that is generated for this function. Defaults to '%(function)s(%(expressions)s)'.
If you’re constructing SQL like strftime('%W', 'date') and need a literal % character in the query, quadruple it (%%%%) in the template attribute because the string is interpolated twice: once during the template interpolation in as_sql() and once in the SQL interpolation with the query parameters in the database cursor.


Returns the ISO-8601 week day with day 1 being Monday and day 7 being Sunday.


Returns the ISO-8601 week-numbering year.


Truncates to midnight on the Monday of the week.


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


Must return the lookup named lookup_name. For instance, by returning self.output_field.get_lookup(lookup_name).


Must return the lookup named transform_name. For instance, by returning self.output_field.get_transform(transform_name).


Name of a model field which will be auto-populated with the height of the image each time the model instance is saved.


Name of a model field which will be auto-populated with the width of the image each time the model instance is saved.


Creates an index (B-Tree) in the database.


An optional json.JSONDecoder subclass to deserialize the value retrieved from the database. The value will be in the format chosen by the custom encoder (most often a string). 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.
Defaults to json.JSONDecoder.


An optional 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 Lookup is a generic class to implement lookups. A lookup is a query expression with a left-hand side, lhs; a right-hand side, rhs; and a lookup_name that is used to produce a boolean comparison between lhs and rhs such as lhs in rhs or lhs > rhs.
The primary notation to use a lookup in an expression is <lhs>__<lookup_name>=<rhs>. Lookups can also be used directly in QuerySet filters:
…or annotations:
The left-hand side - what is being looked up. The object typically follows the Query Expression API. It may also be a plain value.
The right-hand side - what lhs is being compared against. It can be a plain value, or something that compiles into SQL, typically an F() object or a QuerySet.
The name of this lookup, used to identify it on parsing query expressions. It cannot contain the string "__".
Returns a tuple (lhs_string, lhs_params), as returned by compiler.compile(lhs). This method can be overridden to tune how the lhs is processed.
compiler is an SQLCompiler object, to be used like compiler.compile(lhs) for compiling lhs. The connection can be used for compiling vendor specific SQL. If lhs is not None, use it as the processed lhs instead of self.lhs.
Behaves the same way as process_lhs(), for the right-hand side.
Support for using lookups in QuerySet annotations, aggregations, and directly in filters was added.


The left-hand side - what is being looked up. The object typically follows the Query Expression API. It may also be a plain value.


The name of this lookup, used to identify it on parsing query expressions. It cannot contain the string "__".


Returns a tuple (lhs_string, lhs_params), as returned by compiler.compile(lhs). This method can be overridden to tune how the lhs is processed.
compiler is an SQLCompiler object, to be used like compiler.compile(lhs) for compiling lhs. The connection can be used for compiling vendor specific SQL. If lhs is not None, use it as the processed lhs instead of self.lhs.


Behaves the same way as process_lhs(), for the right-hand side.


The right-hand side - what lhs is being compared against. It can be a plain value, or something that compiles into SQL, typically an F() object or a QuerySet.


A mixin that implements the lookup API on a class.
Registers a new lookup in the class. For example DateField.register_lookup(YearExact) will register YearExact lookup on DateField. It overrides a lookup that already exists with the same name. lookup_name will be used for this lookup if provided, otherwise lookup.lookup_name will be used.
Returns the Lookup named lookup_name registered in the class. The default implementation looks recursively on all parent classes and checks if any has a registered lookup named lookup_name, returning the first match.
Returns a dictionary of each lookup name registered in the class mapped to the Lookup class.
Returns a Transform named transform_name. The default implementation looks recursively on all parent classes to check if any has the registered transform named transform_name, returning the first match.


Returns the Lookup named lookup_name registered in the class. The default implementation looks recursively on all parent classes and checks if any has a registered lookup named lookup_name, returning the first match.


Returns a dictionary of each lookup name registered in the class mapped to the Lookup class.


Returns a Transform named transform_name. The default implementation looks recursively on all parent classes to check if any has the registered transform named transform_name, returning the first match.


Controls whether or not constraints should be created in the database for the foreign keys in the intermediary table. The default is True, and that’s almost certainly what you want; setting this to False can be very bad for data integrity. That said, here are some scenarios where you might want to do this:
It is an error to pass both db_constraint and through.


The name of the table to create for storing the many-to-many data. If this is not provided, Django will assume a default name based upon the names of: the table for the model defining the relationship and the name of the field itself.


Controls the migration framework’s reaction if this ManyToManyField is pointing at a swappable model. If it is True - the default - then if the ManyToManyField is pointing at a model which matches the current value of settings.AUTH_USER_MODEL (or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.
You only want to override this to be False if you are sure your model should always point toward the swapped-in model - for example, if it is a profile model designed specifically for your custom user model.
If in doubt, leave it to its default of True.


Only used in the definition of ManyToManyFields on self. Consider the following model:
When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn’t add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical – that is, if I am your friend, then you are my friend.
If you do not want symmetry in many-to-many relationships with self, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships to be non-symmetrical.


Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use.
The most common use for this option is when you want to associate extra data with a many-to-many relationship.
Note
If you don’t want multiple associations between the same instances, add a UniqueConstraint including the from and to fields. Django’s automatically generated many-to-many tables include such a constraint.
Note
Recursive relationships using an intermediary model can’t determine the reverse accessors names, as they would be the same. You need to set a related_name to at least one of them. If you’d prefer Django not to create a backwards relation, set related_name to '+'.
If you don’t specify an explicit through model, there is still an implicit through model class you can use to directly access the table created to hold the association. It has three fields to link the models.
If the source and target models differ, the following fields are generated:
If the ManyToManyField points from and to the same model, the following fields are generated:
This class can be used to query associated records for a given model instance like a normal model:


Only used when a custom intermediary model is specified. Django will normally determine which fields of the intermediary model to use in order to establish a many-to-many relationship automatically. However, consider the following models:
Membership has two foreign keys to Person (person and inviter), which makes the relationship ambiguous and Django can’t know which one to use. In this case, you must explicitly specify which foreign keys Django should use using through_fields, as in the example above.
through_fields accepts a 2-tuple ('field1', 'field2'), where field1 is the name of the foreign key to the model the ManyToManyField is defined on (group in this case), and field2 the name of the foreign key to the target model (person in this case).
When you have more than one foreign key on an intermediary model to any (or even both) of the models participating in a many-to-many relationship, you must specify through_fields. This also applies to recursive relationships when an intermediary model is used and there are more than two foreign keys to the model, or you want to explicitly specify which two Django should use.


Returns the maximum value of the given expression.


Returns the minimum value of the given expression.


The _state attribute refers to a ModelState object that tracks the lifecycle of the model instance.
The ModelState object has two attributes: adding, a flag which is True if the model has not been saved to the database yet, and db, a string referring to the database alias the instance was loaded from or saved to.
Newly instantiated instances have adding=True and db=None, since they are yet to be saved. Instances fetched from a QuerySet will have adding=False and db set to the alias of the associated database.


Each non-abstract Model class must have a Manager instance added to it. Django ensures that in your model class you have at least a default Manager specified. If you don’t add your own Manager, Django will add an attribute objects containing default Manager instance. If you add your own Manager instance attribute, the default one does not appear. Consider the following example:
For more details on model managers see Managers and Retrieving objects.


When True and used in a model which inherits from another concrete model, indicates that this field should be used as the link back to the parent class, rather than the extra OneToOneField which would normally be implicitly created by subclassing.


If abstract = True, this model will be an abstract base class.


If a model is defined outside of an application in INSTALLED_APPS, it must declare which app it belongs to:
If you want to represent a model with the format app_label.object_name or app_label.model_name you can use model._meta.label or model._meta.label_lower respectively.


The attribute name of the manager, for example, 'objects', to use for the model’s _base_manager.


A list of constraints that you want to define on the model:


The name of the database table to use for the model:


The name of the database tablespace to use for this model. The default is the project’s DEFAULT_TABLESPACE setting, if set. If the backend doesn’t support tablespaces, this option is ignored.


The name of the manager to use for the model’s _default_manager.


Defaults to ('add', 'change', 'delete', 'view'). You may customize this list, for example, by setting this to an empty list if your app doesn’t require any of the default permissions. It must be specified on the model before the model is created by migrate in order to prevent any omitted permissions from being created.


The name that will be used by default for the relation from a related object back to this one. The default is <model_name>_set.
This option also sets related_query_name.
As the reverse name for a field should be unique, be careful if you intend to subclass your model. To work around name collisions, part of the name should contain '%(app_label)s' and '%(model_name)s', which are replaced respectively by the name of the application the model is in, and the name of the model, both lowercased. See the paragraph on related names for abstract models.


The name of a field or a list of field names in the model, typically DateField, DateTimeField, or IntegerField. This specifies the default field(s) to use in your model Manager’s latest() and earliest() methods.
Example:
See the latest() docs for more.


Use the indexes option instead.
The newer indexes option provides more functionality than index_together. index_together may be deprecated in the future.
Sets of field names that, taken together, are indexed:
This list of fields will be indexed together (i.e. the appropriate CREATE INDEX statement will be issued.)
For convenience, index_together can be a single list when dealing with a single set of fields:


A list of indexes that you want to define on the model:


Representation of the object, returns app_label.object_name, e.g. 'polls.Question'.


Representation of the model, returns app_label.model_name, e.g. 'polls.question'.


Defaults to True, meaning Django will create the appropriate database tables in migrate or as part of migrations and remove them as part of a flush management command. That is, Django manages the database tables’ lifecycles.
If False, no database table creation, modification, or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal. This includes
If a model with managed=False contains a ManyToManyField that points to another unmanaged model, then the intermediate table for the many-to-many join will also not be created. However, the intermediary table between one managed and one unmanaged model will be created.
If you need to change this default behavior, create the intermediary table as an explicit model (with managed set as needed) and use the ManyToManyField.through attribute to make the relation use your custom model.
For tests involving models with managed=False, it’s up to you to ensure the correct tables are created as part of the test setup.
If you’re interested in changing the Python-level behavior of a model class, you could use managed=False and create a copy of an existing model. However, there’s a better approach for that situation: Proxy models.


Returns the field instance given a name of a field.
field_name can be the name of a field on the model, a field on an abstract or inherited model, or a field defined on another model that points to the model. In the latter case, the field_name will be (in order of preference) the related_query_name set by the user, the related_name set by the user, or the name automatically generated by Django.
Hidden fields cannot be retrieved by name.
If a field with the given name is not found a FieldDoesNotExist exception will be raised.


Returns a tuple of fields associated with a model. get_fields() accepts two parameters that can be used to control which fields are returned:


Makes this object orderable with respect to the given field, usually a ForeignKey. This can be used to make related objects orderable with respect to a parent object. For example, if an Answer relates to a Question object, and a question has more than one answer, and the order of answers matters, you’d do this:
When order_with_respect_to is set, two additional methods are provided to retrieve and to set the order of the related objects: get_RELATED_order() and set_RELATED_order(), where RELATED is the lowercased model name. For example, assuming that a Question object has multiple related Answer objects, the list returned contains the primary keys of the related Answer objects:
The order of a Question object’s related Answer objects can be set by passing in a list of Answer primary keys:
The related objects also get two methods, get_next_in_order() and get_previous_in_order(), which can be used to access those objects in their proper order. Assuming the Answer objects are ordered by id:


The default ordering for the object, for use when obtaining lists of objects:
This is a tuple or list of strings and/or query expressions. Each string is a field name with an optional “-” prefix, which indicates descending order. Fields without a leading “-” will be ordered ascending. Use the string “?” to order randomly.
For example, to order by a pub_date field ascending, use this:
To order by pub_date descending, use this:
To order by pub_date descending, then by author ascending, use this:
You can also use query expressions. To order by author ascending and make null values sort last, use this:


Extra permissions to enter into the permissions table when creating this object. Add, change, delete, and view permissions are automatically created for each model. This example specifies an extra permission, can_deliver_pizzas:
This is a list or tuple of 2-tuples in the format (permission_code,
human_readable_permission_name).


If proxy = True, a model which subclasses another model will be treated as a proxy model.


List of database features that the current connection should have so that the model is considered during the migration phase. For example, if you set this list to ['gis_enabled'], the model will only be synchronized on GIS-enabled databases. It’s also useful to skip some models when testing with several database backends. Avoid relations between models that may or may not be created as the ORM doesn’t handle this.


Name of a supported database vendor that this model is specific to. Current built-in vendor names are: sqlite, postgresql, mysql, oracle. If this attribute is not empty and the current connection vendor doesn’t match it, the model will not be synchronized.


Determines if Django will use the pre-1.6 django.db.models.Model.save() algorithm. The old algorithm uses SELECT to determine if there is an existing row to be updated. The new algorithm tries an UPDATE directly. In some rare cases the UPDATE of an existing row isn’t visible to Django. An example is the PostgreSQL ON UPDATE trigger which returns NULL. In such cases the new algorithm will end up doing an INSERT even when a row exists in the database.
Usually there is no need to set this attribute. The default is False.
See django.db.models.Model.save() for more about the old and new saving algorithm.


Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.
Sets of field names that, taken together, must be unique:
This is a list of lists that must be unique when considered together. It’s used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).
For convenience, unique_together can be a single list when dealing with a single set of fields:
A ManyToManyField cannot be included in unique_together. (It’s not clear what that would even mean!) If you need to validate uniqueness related to a ManyToManyField, try using a signal or an explicit through model.
The ValidationError raised during model validation when the constraint is violated has the unique_together error code.


A human-readable name for the object, singular:
If this isn’t given, Django will use a munged version of the class name: CamelCase becomes camel case.


The plural name for the object:
If this isn’t given, Django will use verbose_name + "s".


Defines the type of class returned by the get_lookup() method. It must be a Field instance.


Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.


Usually when you’ll interact with a QuerySet you’ll use it by chaining filters. To make this work, most QuerySet methods return new querysets. These methods are covered in detail later in this section.
The QuerySet class has two public attributes you can use for introspection:
True if the QuerySet is ordered — i.e. has an order_by() clause or a default ordering on the model. False otherwise.
The database that will be used if this query is executed now.
Note
The query parameter to QuerySet exists so that specialized query subclasses can reconstruct internal query state. The value of the parameter is an opaque representation of that query state and is not part of a public API.


The database that will be used if this query is executed now.


True if the QuerySet is ordered — i.e. has an order_by() clause or a default ordering on the model. False otherwise.


Prevent deletion of the referenced object by raising RestrictedError (a subclass of django.db.IntegrityError). Unlike PROTECT, deletion of the referenced object is allowed if it also references a different object that is being deleted in the same operation, but via a CASCADE relationship.
Consider this set of models:
Artist can be deleted even if that implies deleting an Album which is referenced by a Song, because Song also references Artist itself through a cascading relationship. For example:


Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported:


Set the ForeignKey to its default value; a default for the ForeignKey must be set.


Set the ForeignKey null; this is only possible if null is True.


If True, the field accepts Unicode letters in addition to ASCII letters. Defaults to False.


Returns the standard deviation of the data in the provided expression.
Has one optional argument:
By default, StdDev returns the population standard deviation. However, if sample=True, the return value will be the sample standard deviation.


By default, StdDev returns the population standard deviation. However, if sample=True, the return value will be the sample standard deviation.


Computes the sum of all values of the given expression.
Has one optional argument:
If distinct=True, Sum returns the sum of unique values. This is the SQL equivalent of SUM(DISTINCT <field>). The default value is False.


If distinct=True, Sum returns the sum of unique values. This is the SQL equivalent of SUM(DISTINCT <field>). The default value is False.


The database collation name of the field.
Note
Collation names are not standardized. As such, this will not be portable across multiple database backends.
Oracle
Oracle does not support collations for a TextField.


A Transform is a generic class to implement field transformations. A prominent example is __year that transforms a DateField into a IntegerField.
The notation to use a Transform in a lookup expression is <expression>__<transformation> (e.g. date__year).
This class follows the Query Expression API, which implies that you can use <expression>__<transform1>__<transform2>. It’s a specialized Func() expression that only accepts one argument. It can also be used on the right hand side of a filter or directly as an annotation.
A boolean indicating whether this transformation should apply to both lhs and rhs. Bilateral transformations will be applied to rhs in the same order as they appear in the lookup expression. By default it is set to False. For example usage, see How to write custom lookups.
The left-hand side - what is being transformed. It must follow the Query Expression API.
The name of the lookup, used for identifying it on parsing query expressions. It cannot contain the string "__".
Defines the class this transformation outputs. It must be a Field instance. By default is the same as its lhs.output_field.


A boolean indicating whether this transformation should apply to both lhs and rhs. Bilateral transformations will be applied to rhs in the same order as they appear in the lookup expression. By default it is set to False. For example usage, see How to write custom lookups.


The left-hand side - what is being transformed. It must follow the Query Expression API.


The name of the lookup, used for identifying it on parsing query expressions. It cannot contain the string "__".


Defines the class this transformation outputs. It must be a Field instance. By default is the same as its lhs.output_field.


Creates a unique constraint in the database.


Returns the variance of the data in the provided expression.
Has one optional argument:
By default, Variance returns the population variance. However, if sample=True, the return value will be the sample variance.


By default, Variance returns the population variance. However, if sample=True, the return value will be the sample variance.


Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.
atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point.
It is sometimes useful to ensure an atomic block is always the outermost atomic block, ensuring that any database changes are committed when the block is exited without errors. This is known as durability and can be achieved by setting durable=True. If the atomic block is nested within another it raises a RuntimeError.
atomic is usable both as a decorator:
and as a context manager:
Wrapping atomic in a try/except block allows for natural handling of integrity errors:
In this example, even if generate_relationships() causes a database error by breaking an integrity constraint, you can execute queries in add_children(), and the changes from create_parent() are still there and bound to the same transaction. Note that any operations attempted in generate_relationships() will already have been rolled back safely when handle_exception() is called, so the exception handler can also operate on the database if necessary.
Avoid catching exceptions inside atomic!
When exiting an atomic block, Django looks at whether it’s exited normally or with an exception to determine whether to commit or roll back. If you catch and handle exceptions inside an atomic block, you may hide from Django the fact that a problem has happened. This can result in unexpected behavior.
This is mostly a concern for DatabaseError and its subclasses such as IntegrityError. After such an error, the transaction is broken and Django will perform a rollback at the end of the atomic block. If you attempt to run database queries before the rollback happens, Django will raise a TransactionManagementError. You may also encounter this behavior when an ORM-related signal handler raises an exception.
The correct way to catch database errors is around an atomic block as shown above. If necessary, add an extra atomic block for this purpose. This pattern has another advantage: it delimits explicitly which operations will be rolled back if an exception occurs.
If you catch exceptions raised by raw SQL queries, Django’s behavior is unspecified and database-dependent.
You may need to manually revert model state when rolling back a transaction.
The values of a model’s fields won’t be reverted when a transaction rollback happens. This could lead to an inconsistent model state unless you manually restore the original field values.
For example, given MyModel with an active field, this snippet ensures that the if obj.active check at the end uses the correct value if updating active to True fails in the transaction:
In order to guarantee atomicity, atomic disables some APIs. Attempting to commit, roll back, or change the autocommit state of the database connection within an atomic block will raise an exception.
atomic takes a using argument which should be the name of a database. If this argument isn’t provided, Django uses the "default" database.
Under the hood, Django’s transaction management code:
You can disable the creation of savepoints for inner blocks by setting the savepoint argument to False. If an exception occurs, Django will perform the rollback when exiting the first parent block with a savepoint if there is one, and the outermost block otherwise. Atomicity is still guaranteed by the outer transaction. This option should only be used if the overhead of savepoints is noticeable. It has the drawback of breaking the error handling described above.
You may use atomic when autocommit is turned off. It will only use savepoints, even for the outermost block.


Resets the counter used to generate unique savepoint IDs.


This decorator will negate the effect of ATOMIC_REQUESTS for a given view:
It only works if it’s applied to the view itself.


Creates a new savepoint. This marks a point in the transaction that is known to be in a “good” state. Returns the savepoint ID (sid).


Releases savepoint sid. The changes performed since the savepoint was created become part of the transaction.


Rolls back the transaction to savepoint sid.


This document provides API reference material for the components of Django’s authentication system. For more details on the usage of these components or how to customize authentication and authorization see the authentication topic guide.
User objects have the following fields:
Required. 150 characters or fewer. Usernames may contain alphanumeric, _, @, +, . and - characters.
The max_length should be sufficient for many use cases. If you need a longer length, please use a custom user model. If you use MySQL with the utf8mb4 encoding (recommended for proper Unicode support), specify at most max_length=191 because MySQL can only create unique indexes with 191 characters in that case by default.
Optional (blank=True). 150 characters or fewer.
Optional (blank=True). 150 characters or fewer.
Optional (blank=True). Email address.
Required. A hash of, and metadata about, the password. (Django doesn’t store the raw password.) Raw passwords can be arbitrarily long and can contain any character. See the password documentation.
Many-to-many relationship to Group
Many-to-many relationship to Permission
Boolean. Designates whether this user can access the admin site.
Boolean. Designates whether this user account should be considered active. We recommend that you set this flag to False instead of deleting accounts; that way, if your applications have any foreign keys to users, the foreign keys won’t break.
This doesn’t necessarily control whether or not the user can log in. Authentication backends aren’t required to check for the is_active flag but the default backend (ModelBackend) and the RemoteUserBackend do. You can use AllowAllUsersModelBackend or AllowAllUsersRemoteUserBackend if you want to allow inactive users to login. In this case, you’ll also want to customize the AuthenticationForm used by the LoginView as it rejects inactive users. Be aware that the permission-checking methods such as has_perm() and the authentication in the Django admin all return False for inactive users.
Boolean. Designates that this user has all permissions without explicitly assigning them.
A datetime of the user’s last login.
A datetime designating when the account was created. Is set to the current date/time by default when the account is created.
Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance.
Read-only attribute which is always False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated to this attribute.
Returns the username for the user. Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.
Returns the first_name plus the last_name, with a space in between.
Returns the first_name.
Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the User object.
When the raw_password is None, the password will be set to an unusable password, as if set_unusable_password() were used.
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)
Marks the user as having no password set. This isn’t the same as having a blank string for a password. check_password() for this user will never return True. Doesn’t save the User object.
You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.
Returns False if set_unusable_password() has been called for this user.
Returns a set of permission strings that the user has directly.
If obj is passed in, only returns the user permissions for this specific object.
Returns a set of permission strings that the user has, through their groups.
If obj is passed in, only returns the group permissions for this specific object.
Returns a set of permission strings that the user has, both through group and user permissions.
If obj is passed in, only returns the permissions for this specific object.
Returns True if the user has the specified permission, where perm is in the format "<app label>.<permission codename>". (see documentation on permissions). If the user is inactive, this method will always return False. For an active superuser, this method will always return True.
If obj is passed in, this method won’t check for a permission for the model, but for this specific object.
Returns True if the user has each of the specified permissions, where each perm is in the format "<app label>.<permission codename>". If the user is inactive, this method will always return False. For an active superuser, this method will always return True.
If obj is passed in, this method won’t check for permissions for the model, but for the specific object.
Returns True if the user has any permissions in the given package (the Django app label). If the user is inactive, this method will always return False. For an active superuser, this method will always return True.
Sends an email to the user. If from_email is None, Django uses the DEFAULT_FROM_EMAIL. Any **kwargs are passed to the underlying send_mail() call.
The User model has a custom manager that has the following helper methods (in addition to the methods provided by BaseUserManager):
Creates, saves and returns a User.
The username and password are set as given. The domain portion of email is automatically converted to lowercase, and the returned User object will have is_active set to True.
If no password is provided, set_unusable_password() will be called.
The extra_fields keyword arguments are passed through to the User’s __init__ method to allow setting arbitrary fields on a custom user model.
See Creating users for example usage.
Same as create_user(), but sets is_staff and is_superuser to True.
Returns users that have the given permission perm either in the "<app label>.<permission codename>" format or as a Permission instance. Returns an empty queryset if no users who have the perm found.
If is_active is True (default), returns only active users, or if False, returns only inactive users. Use None to return all users irrespective of active state.
If include_superusers is True (default), the result will include superusers.
If backend is passed in and it’s defined in AUTHENTICATION_BACKENDS, then this method will use it. Otherwise, it will use the backend in AUTHENTICATION_BACKENDS, if there is only one, or raise an exception.
django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface, with these differences:
In practice, you probably won’t need to use AnonymousUser objects on your own, but they’re used by web requests, as explained in the next section.
Permission objects have the following fields:
Required. 255 characters or fewer. Example: 'Can vote'.
Required. A reference to the django_content_type database table, which contains a record for each installed model.
Required. 100 characters or fewer. Example: 'can_vote'.
Permission objects have the standard data-access methods like any other Django model.
Group objects have the following fields:
Required. 150 characters or fewer. Any characters are permitted. Example: 'Awesome Users'.
Many-to-many field to Permission:
A field validator allowing only ASCII letters and numbers, in addition to @, ., +, -, and _.
A field validator allowing Unicode characters, in addition to @, ., +, -, and _. The default validator for User.username.
The auth framework uses the following signals that can be used for notification when a user logs in or out.
Sent when a user logs in successfully.
Arguments sent with this signal:
Sent when the logout method is called.
Sent when the user failed to login successfully
This section details the authentication backends that come with Django. For information on how to use them and how to write your own authentication backends, see the Other authentication sources section of the User authentication guide.
The following backends are available in django.contrib.auth.backends:
A base class that provides default implementations for all required methods. By default, it will reject any user and provide no permissions.
Returns an empty set.
Returns an empty set.
Uses get_user_permissions() and get_group_permissions() to get the set of permission strings the user_obj has.
Uses get_all_permissions() to check if user_obj has the permission string perm.
This is the default authentication backend used by Django. It authenticates using credentials consisting of a user identifier and password. For Django’s default user model, the user identifier is the username, for custom user models it is the field specified by USERNAME_FIELD (see Customizing Users and authentication).
It also handles the default permissions model as defined for User and PermissionsMixin.
has_perm(), get_all_permissions(), get_user_permissions(), and get_group_permissions() allow an object to be passed as a parameter for object-specific permissions, but this backend does not implement them other than returning an empty set of permissions if obj is not None.
with_perm() also allows an object to be passed as a parameter, but unlike others methods it returns an empty queryset if obj is not None.
Tries to authenticate username with password by calling User.check_password. If no username is provided, it tries to fetch a username from kwargs using the key CustomUser.USERNAME_FIELD. Returns an authenticated user or None.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
Returns the set of permission strings the user_obj has from their own user permissions. Returns an empty set if is_anonymous or is_active is False.
Returns the set of permission strings the user_obj has from the permissions of the groups they belong. Returns an empty set if is_anonymous or is_active is False.
Returns the set of permission strings the user_obj has, including both user permissions and group permissions. Returns an empty set if is_anonymous or is_active is False.
Uses get_all_permissions() to check if user_obj has the permission string perm. Returns False if the user is not is_active.
Returns whether the user_obj has any permissions on the app app_label.
Returns whether the user is allowed to authenticate. To match the behavior of AuthenticationForm which prohibits inactive users from logging in, this method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.
Returns all active users who have the permission perm either in the form of "<app label>.<permission codename>" or a Permission instance. Returns an empty queryset if no users who have the perm found.
If is_active is True (default), returns only active users, or if False, returns only inactive users. Use None to return all users irrespective of active state.
If include_superusers is True (default), the result will include superusers.
Same as ModelBackend except that it doesn’t reject inactive users because user_can_authenticate() always returns True.
When using this backend, you’ll likely want to customize the AuthenticationForm used by the LoginView by overriding the confirm_login_allowed() method as it rejects inactive users.
Use this backend to take advantage of external-to-Django-handled authentication. It authenticates using usernames passed in request.META['REMOTE_USER']. See the Authenticating against REMOTE_USER documentation.
If you need more control, you can create your own authentication backend that inherits from this class and override these attributes or methods:
True or False. Determines whether or not a user object is created if not already in the database Defaults to True.
The username passed as remote_user is considered trusted. This method returns the user object with the given username, creating a new user object if create_unknown_user is True.
Returns None if create_unknown_user is False and a User object with the given username is not found in the database.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
Performs any cleaning on the username (e.g. stripping LDAP DN information) prior to using it to get or create a user object. Returns the cleaned username.
Configures a newly created user. This method is called immediately after a new user is created, and can be used to perform custom setup actions, such as setting the user’s groups based on attributes in an LDAP directory. Returns the user object.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
Returns whether the user is allowed to authenticate. This method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.
Same as RemoteUserBackend except that it doesn’t reject inactive users because user_can_authenticate always returns True.
Returns the user model instance associated with the given request’s session.
It checks if the authentication backend stored in the session is present in AUTHENTICATION_BACKENDS. If so, it uses the backend’s get_user() method to retrieve the user model instance and then verifies the session by calling the user model’s get_session_auth_hash() method.
Returns an instance of AnonymousUser if the authentication backend stored in the session is no longer in AUTHENTICATION_BACKENDS, if a user isn’t returned by the backend’s get_user() method, or if the session auth hash doesn’t validate.


A set of Django template filters useful for adding a “human touch” to data.
To activate these filters, add 'django.contrib.humanize' to your INSTALLED_APPS setting. Once you’ve done that, use {% load humanize %} in a template, and you’ll have access to the following filters.
For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style.
Examples:
You can pass in either an integer or a string representation of an integer.
Converts an integer or float (or a string representation of either) to a string containing commas every three digits.
Examples:
Format localization will be respected if enabled, e.g. with the 'de' language:
Converts a large integer (or a string representation of an integer) to a friendly text representation. Translates 1.0 as a singular phrase and all other numeric values as plural, this may be incorrect for some languages. Works best for numbers over 1 million.
Examples:
Values up to 10^100 (Googol) are supported.
Format localization will be respected if enabled, e.g. with the 'de' language:
For dates that are the current day or within one day, return “today”, “tomorrow” or “yesterday”, as appropriate. Otherwise, format the date using the passed in format string.
Argument: Date formatting string as described in the date tag.
Examples (when ‘today’ is 17 Feb 2007):
For datetime values, returns a string representing how many seconds, minutes or hours ago it was – falling back to the timesince format if the value is more than a day old. In case the datetime value is in the future the return value will automatically use an appropriate phrase.
Examples (when ‘now’ is 17 Feb 2007 16:30:00):
Converts an integer to its ordinal as a string.
Examples:
You can pass in either an integer or a string representation of an integer.


PostgreSQL has a number of features which are not shared by the other databases Django supports. This optional module contains model fields and form fields for a number of PostgreSQL specific data types.
Note
Django is, and will continue to be, a database-agnostic web framework. We would encourage those writing reusable applications for the Django community to write database-agnostic code where practical. However, we recognize that real world projects written using Django need not be database-agnostic. In fact, once a project reaches a given size changing the underlying data store is already a significant challenge and is likely to require changing the code base in some ways to handle differences between the data stores.
Django provides support for a number of data types which will only work with PostgreSQL. There is no fundamental reason why (for example) a contrib.mysql module does not exist, except that PostgreSQL has the richest feature set of the supported databases so its users have the most to gain.


Each time any Django application raises a 404 error, this middleware checks the flatpages database for the requested URL as a last resort. Specifically, it checks for a flatpage with the given URL with a site ID that corresponds to the SITE_ID setting.
If it finds a match, it follows this algorithm:
The middleware will only add a trailing slash and redirect (by looking at the APPEND_SLASH setting) if the resulting URL refers to a valid flatpage. Redirects are permanent (301 status code).
If it doesn’t find a match, the request continues to be processed as usual.
The middleware only gets activated for 404s – not for 500s or responses of any other status code.


Flatpages are represented by a standard Django model, which lives in django/contrib/flatpages/models.py. You can access flatpage objects via the Django database API.


The sitemaps.FlatPageSitemap class looks at all publicly visible flatpages defined for the current SITE_ID (see the sites documentation) and creates an entry in the sitemap. These entries include only the location attribute – not lastmod, changefreq or priority.


Detailed form API reference. For introductory material, see the Working with forms topic guide.


Note
Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.


Used to display HTML or access attributes for a single field of a Form instance.
The __str__() method of this object displays the HTML for this field.


Returns a string of HTML for representing this as an <input type="hidden">.
**kwargs are passed to as_widget().
This method is primarily used internally. You should use a widget instead.


Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field’s default widget will be used.
only_initial is used by Django internals and should not be set explicitly.


The HTML ID attribute for this BoundField. Returns an empty string if Form.auto_id is False.


When you use Django’s rendering shortcuts, CSS classes are used to indicate required form fields or fields that contain errors. If you’re manually rendering a form, you can access these CSS classes using the css_classes method:
If you want to provide some additional classes in addition to the error and required classes that may be required, you can provide those classes as an argument:


This property returns the data for this BoundField extracted by the widget’s value_from_datadict() method, or None if it wasn’t given:


A list-like object that is displayed as an HTML <ul class="errorlist"> when printed:


The form Field instance from the form class that this BoundField wraps.


The Form instance this BoundField is bound to.


The name that will be used in the widget’s HTML name attribute. It takes the form prefix into account.


Use this property to render the ID of this field. For example, if you are manually constructing a <label> in your template (despite the fact that label_tag() will do this for you):
By default, this will be the field’s name prefixed by id_ (“id_my_field” for the example above). You may modify the ID by setting attrs on the field’s widget. For example, declaring a field like this:
and using the template above, would render something like:


Use BoundField.initial to retrieve initial data for a form field. It retrieves the data from Form.initial if present, otherwise trying Field.initial. Callable values are evaluated. See Initial form values for more examples.
BoundField.initial caches its return value, which is useful especially when dealing with callables whose return values can change (e.g. datetime.now or uuid.uuid4):
Using BoundField.initial is recommended over get_initial_for_field().


Returns True if this BoundField’s widget is hidden.


The label of the field. This is used in label_tag().


Renders a label tag for the form field using the template specified by Form.template_name_label.
The available context is:
Tip
In your template field is the instance of the BoundField. Therefore field.field accesses BoundField.field being the field you declare, e.g. forms.CharField.
To separately render the label tag of a form field, you can call its label_tag() method:
If you’d like to customize the rendering this can be achieved by overriding the Form.template_name_label attribute or more generally by overriding the default template, see also Overriding built-in form templates.
The label is now rendered using the template engine.


Use this method to render the raw value of this field as it would be rendered by a Widget:


Returns the lowercased class name of the wrapped field’s widget, with any trailing input or widget removed. This may be used when building forms where the layout is dependent upon the widget type. For example:


Has four optional arguments for validation:
If provided, these arguments ensure that the string is at most or at least the given length.
If True (default), the value will be stripped of leading and trailing whitespace.
The value to use to represent “empty”. Defaults to an empty string.


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


If provided, these arguments ensure that the string is at most or at least the given length.


If True (default), the value will be stripped of leading and trailing whitespace.


Takes one optional argument:
A callable that takes the value of the CheckboxInput and returns True if the checkbox should be checked for that value.


A callable that takes the value of the CheckboxInput and returns True if the checkbox should be checked for that value.


Similar to SelectMultiple, but rendered as a list of checkboxes:
The outer <div> container receives the id attribute of the widget, if defined, or BoundField.auto_id otherwise.
So they are announced more concisely by screen readers, checkboxes were changed to render in <div> tags.


The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes one extra argument:
Either an iterable of 2-tuples to use as choices for this field, enumeration choices, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. See the model field reference documentation on choices for more details. If the argument is a callable, it is evaluated each time the field’s form is initialized, in addition to during rendering. Defaults to an empty list.


Either an iterable of 2-tuples to use as choices for this field, enumeration choices, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. See the model field reference documentation on choices for more details. If the argument is a callable, it is evaluated each time the field’s form is initialized, in addition to during rendering. Defaults to an empty list.


Takes one extra required argument:
The list of fields that should be used to validate the field’s value (in the order in which they are provided).


The list of fields that should be used to validate the field’s value (in the order in which they are provided).


Takes one optional argument:
A list of formats used to attempt to convert a string to a valid datetime.date object.
If no input_formats argument is provided, the default input formats are taken from DATE_INPUT_FORMATS if USE_L10N is False, or from the active locale format DATE_INPUT_FORMATS key if localization is enabled. See also format localization.


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


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 DATE_INPUT_FORMATS and respects Format localization.


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


Takes one optional argument:
A list of formats used to attempt to convert a string to a valid datetime.datetime object, in addition to ISO 8601 formats.
The field always accepts strings in ISO 8601 formatted dates or similar recognized by parse_datetime(). Some examples are:
If no input_formats argument is provided, the default input formats are taken from DATETIME_INPUT_FORMATS and DATE_INPUT_FORMATS if USE_L10N is False, or from the active locale format DATETIME_INPUT_FORMATS and DATE_INPUT_FORMATS keys if localization is enabled. See also format localization.


A list of formats used to attempt to convert a string to a valid datetime.datetime object, in addition to ISO 8601 formats.


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 DATETIME_INPUT_FORMATS and respects Format localization.
By default, the microseconds part of the time value is always set to 0. If microseconds are required, use a subclass with the supports_microseconds attribute set to True.


The max_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit. Similarly, the max_digits, max_decimal_places and max_whole_digits error messages may contain %(max)s.
Takes four optional arguments:
These control the range of values permitted in the field, and should be given as decimal.Decimal values.
The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value.
The maximum number of decimal places permitted.


The maximum number of decimal places permitted.


The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value.


These control the range of values permitted in the field, and should be given as decimal.Decimal values.


Accepts any format understood by parse_duration().


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


By default, forms use django.forms.utils.ErrorList to format validation errors. ErrorList is a list like object where initlist is the list of errors. In addition this class has the following attributes and methods.
The CSS classes to be used when rendering the error list. Any provided classes are added to the default errorlist class.
Specifies the renderer to use for ErrorList. Defaults to None which means to use the default renderer specified by the FORM_RENDERER setting.
The name of the template used when calling __str__ or render(). By default this is 'django/forms/errors/list/default.html' which is a proxy for the 'ul.html' template.
The name of the template used when calling as_text(). By default this is 'django/forms/errors/list/text.html'. This template renders the errors as a list of bullet points.
The name of the template used when calling as_ul(). By default this is 'django/forms/errors/list/ul.html'. This template renders the errors in <li> tags with a wrapping <ul> with the CSS classes as defined by error_class.
Return context for rendering of errors in a template.
The available context is:
The render method is called by __str__ as well as by the as_ul() method.
All arguments are optional and will default to:
Renders the error list using the template defined by template_name_text.
Renders the error list using the template defined by template_name_ul.
If you’d like to customize the rendering of errors this can be achieved by overriding the template_name attribute or more generally by overriding the default template, see also Overriding built-in form templates.


Renders the error list using the template defined by template_name_text.


Renders the error list using the template defined by template_name_ul.


The CSS classes to be used when rendering the error list. Any provided classes are added to the default errorlist class.


Return context for rendering of errors in a template.
The available context is:


The render method is called by __str__ as well as by the as_ul() method.
All arguments are optional and will default to:


Specifies the renderer to use for ErrorList. Defaults to None which means to use the default renderer specified by the FORM_RENDERER setting.


The name of the template used when calling __str__ or render(). By default this is 'django/forms/errors/list/default.html' which is a proxy for the 'ul.html' template.


The name of the template used when calling as_text(). By default this is 'django/forms/errors/list/text.html'. This template renders the errors as a list of bullet points.


The name of the template used when calling as_ul(). By default this is 'django/forms/errors/list/ul.html'. This template renders the errors in <li> tags with a wrapping <ul> with the CSS classes as defined by error_class.


Takes an instance of Form and the name of the field. The return value will be used when accessing the field in a template. Most likely it will be an instance of a subclass of BoundField.


Has two optional arguments for validation, max_length and allow_empty_file. If provided, these ensure that the file name is at most the given length, and that validation will succeed even if the file content is empty.
To learn more about the UploadedFile object, see the file uploads documentation.
When you use a FileField in a form, you must also remember to bind the file data to the form.
The max_length error refers to the length of the filename. In the error message for that key, %(max)d will be replaced with the maximum filename length and %(length)d will be replaced with the current filename length.


The field allows choosing from files inside a certain directory. It takes five extra arguments; only path is required:
The absolute path to the directory whose contents you want listed. This directory must exist.
If False (the default) only the direct contents of path will be offered as choices. If True, the directory will be descended into recursively and all descendants will be listed as choices.
A regular expression pattern; only files with names matching this expression will be allowed as choices.
Optional. Either True or False. Default is True. Specifies whether files in the specified location should be included. Either this or allow_folders must be True.
Optional. Either True or False. Default is False. Specifies whether folders in the specified location should be included. Either this or allow_files must be True.


Optional. Either True or False. Default is True. Specifies whether files in the specified location should be included. Either this or allow_folders must be True.


Optional. Either True or False. Default is False. Specifies whether folders in the specified location should be included. Either this or allow_files must be True.


A regular expression pattern; only files with names matching this expression will be allowed as choices.


The absolute path to the directory whose contents you want listed. This directory must exist.


If False (the default) only the direct contents of path will be offered as choices. If True, the directory will be descended into recursively and all descendants will be listed as choices.


Takes two optional arguments for validation, max_value and min_value. These control the range of values permitted in the field.


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.


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:


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 a FormSet class for the given form class.
See formsets for example usage.
The absolute_max and can_delete_extra arguments were added.
The renderer argument was added.