doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None) [source] Parameters: receiver – The callback function which will be connected to this signal. See Receiver functions for more information. sender – Specifies a particular sender to receive signals from. See Connecting to signals sent by specific senders for more information. weak – Django stores signal handlers as weak references by default. Thus, if your receiver is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the signal’s connect() method. dispatch_uid – A unique identifier for a signal receiver in cases where duplicate signals may be sent. See Preventing duplicate signals for more information.
django.topics.signals#django.dispatch.Signal.connect
Signal.disconnect(receiver=None, sender=None, dispatch_uid=None) [source]
django.topics.signals#django.dispatch.Signal.disconnect
Signal.send(sender, **kwargs) [source]
django.topics.signals#django.dispatch.Signal.send
Signal.send_robust(sender, **kwargs) [source]
django.topics.signals#django.dispatch.Signal.send_robust
django.contrib.auth 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 model class models.User Fields class models.User User objects have the following fields: username 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. first_name Optional (blank=True). 150 characters or fewer. last_name Optional (blank=True). 150 characters or fewer. email Optional (blank=True). Email address. password 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. groups Many-to-many relationship to Group user_permissions Many-to-many relationship to Permission is_staff Boolean. Designates whether this user can access the admin site. is_active 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. is_superuser Boolean. Designates that this user has all permissions without explicitly assigning them. last_login A datetime of the user’s last login. date_joined A datetime designating when the account was created. Is set to the current date/time by default when the account is created. Attributes class models.User is_authenticated 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. is_anonymous 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. Methods class models.User get_username() 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. get_full_name() Returns the first_name plus the last_name, with a space in between. get_short_name() Returns the first_name. set_password(raw_password) 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. check_password(raw_password) 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.) set_unusable_password() 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. has_usable_password() Returns False if set_unusable_password() has been called for this user. get_user_permissions(obj=None) 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. get_group_permissions(obj=None) 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. get_all_permissions(obj=None) 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. has_perm(perm, obj=None) 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. has_perms(perm_list, obj=None) 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. has_module_perms(package_name) 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. email_user(subject, message, from_email=None, **kwargs) 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. Manager methods class models.UserManager The User model has a custom manager that has the following helper methods (in addition to the methods provided by BaseUserManager): create_user(username, email=None, password=None, **extra_fields) 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. create_superuser(username, email=None, password=None, **extra_fields) Same as create_user(), but sets is_staff and is_superuser to True. with_perm(perm, is_active=True, include_superusers=True, backend=None, obj=None) 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. AnonymousUser object class models.AnonymousUser django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface, with these differences: id is always None. username is always the empty string. get_username() always returns the empty string. is_anonymous is True instead of False. is_authenticated is False instead of True. is_staff and is_superuser are always False. is_active is always False. groups and user_permissions are always empty. set_password(), check_password(), save() and delete() raise NotImplementedError. 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 model class models.Permission Fields Permission objects have the following fields: class models.Permission name Required. 255 characters or fewer. Example: 'Can vote'. content_type Required. A reference to the django_content_type database table, which contains a record for each installed model. codename Required. 100 characters or fewer. Example: 'can_vote'. Methods Permission objects have the standard data-access methods like any other Django model. Group model class models.Group Fields Group objects have the following fields: class models.Group name Required. 150 characters or fewer. Any characters are permitted. Example: 'Awesome Users'. permissions Many-to-many field to Permission: group.permissions.set([permission_list]) group.permissions.add(permission, permission, ...) group.permissions.remove(permission, permission, ...) group.permissions.clear() Validators class validators.ASCIIUsernameValidator A field validator allowing only ASCII letters and numbers, in addition to @, ., +, -, and _. class validators.UnicodeUsernameValidator A field validator allowing Unicode characters, in addition to @, ., +, -, and _. The default validator for User.username. Login and logout signals The auth framework uses the following signals that can be used for notification when a user logs in or out. user_logged_in() Sent when a user logs in successfully. Arguments sent with this signal: sender The class of the user that just logged in. request The current HttpRequest instance. user The user instance that just logged in. user_logged_out() Sent when the logout method is called. sender As above: the class of the user that just logged out or None if the user was not authenticated. request The current HttpRequest instance. user The user instance that just logged out or None if the user was not authenticated. user_login_failed() Sent when the user failed to login successfully sender The name of the module used for authentication. credentials A dictionary of keyword arguments containing the user credentials that were passed to authenticate() or your own custom authentication backend. Credentials matching a set of ‘sensitive’ patterns, (including password) will not be sent in the clear as part of the signal. request The HttpRequest object, if one was provided to authenticate(). Authentication backends 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. Available authentication backends The following backends are available in django.contrib.auth.backends: class BaseBackend A base class that provides default implementations for all required methods. By default, it will reject any user and provide no permissions. get_user_permissions(user_obj, obj=None) Returns an empty set. get_group_permissions(user_obj, obj=None) Returns an empty set. get_all_permissions(user_obj, obj=None) Uses get_user_permissions() and get_group_permissions() to get the set of permission strings the user_obj has. has_perm(user_obj, perm, obj=None) Uses get_all_permissions() to check if user_obj has the permission string perm. class ModelBackend 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. authenticate(request, username=None, password=None, **kwargs) 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). get_user_permissions(user_obj, obj=None) 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. get_group_permissions(user_obj, obj=None) 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. get_all_permissions(user_obj, obj=None) 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. has_perm(user_obj, perm, obj=None) Uses get_all_permissions() to check if user_obj has the permission string perm. Returns False if the user is not is_active. has_module_perms(user_obj, app_label) Returns whether the user_obj has any permissions on the app app_label. user_can_authenticate() 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. with_perm(perm, is_active=True, include_superusers=True, obj=None) 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. class AllowAllUsersModelBackend 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. class RemoteUserBackend 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: create_unknown_user True or False. Determines whether or not a user object is created if not already in the database Defaults to True. authenticate(request, remote_user) 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). clean_username(username) 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. configure_user(request, user) 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). user_can_authenticate() 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. class AllowAllUsersRemoteUserBackend Same as RemoteUserBackend except that it doesn’t reject inactive users because user_can_authenticate always returns True. Utility functions get_user(request) 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.
django.ref.contrib.auth
django.contrib.humanize 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. apnumber For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. Examples: 1 becomes one. 2 becomes two. 10 becomes 10. You can pass in either an integer or a string representation of an integer. intcomma Converts an integer or float (or a string representation of either) to a string containing commas every three digits. Examples: 4500 becomes 4,500. 4500.2 becomes 4,500.2. 45000 becomes 45,000. 450000 becomes 450,000. 4500000 becomes 4,500,000. Format localization will be respected if enabled, e.g. with the 'de' language: 45000 becomes '45.000'. 450000 becomes '450.000'. intword 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: 1000000 becomes 1.0 million. 1200000 becomes 1.2 million. 1200000000 becomes 1.2 billion. -1200000000 becomes -1.2 billion. Values up to 10^100 (Googol) are supported. Format localization will be respected if enabled, e.g. with the 'de' language: 1000000 becomes '1,0 Million'. 1200000 becomes '1,2 Millionen'. 1200000000 becomes '1,2 Milliarden'. -1200000000 becomes '-1,2 Milliarden'. naturalday 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): 16 Feb 2007 becomes yesterday. 17 Feb 2007 becomes today. 18 Feb 2007 becomes tomorrow. Any other day is formatted according to given argument or the DATE_FORMAT setting if no argument is given. naturaltime 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): 17 Feb 2007 16:30:00 becomes now. 17 Feb 2007 16:29:31 becomes 29 seconds ago. 17 Feb 2007 16:29:00 becomes a minute ago. 17 Feb 2007 16:25:35 becomes 4 minutes ago. 17 Feb 2007 15:30:29 becomes 59 minutes ago. 17 Feb 2007 15:30:01 becomes 59 minutes ago. 17 Feb 2007 15:30:00 becomes an hour ago. 17 Feb 2007 13:31:29 becomes 2 hours ago. 16 Feb 2007 13:31:29 becomes 1 day, 2 hours ago. 16 Feb 2007 13:30:01 becomes 1 day, 2 hours ago. 16 Feb 2007 13:30:00 becomes 1 day, 3 hours ago. 17 Feb 2007 16:30:30 becomes 30 seconds from now. 17 Feb 2007 16:30:29 becomes 29 seconds from now. 17 Feb 2007 16:31:00 becomes a minute from now. 17 Feb 2007 16:34:35 becomes 4 minutes from now. 17 Feb 2007 17:30:29 becomes an hour from now. 17 Feb 2007 18:31:29 becomes 2 hours from now. 18 Feb 2007 16:31:29 becomes 1 day from now. 26 Feb 2007 18:31:29 becomes 1 week, 2 days from now. ordinal Converts an integer to its ordinal as a string. Examples: 1 becomes 1st. 2 becomes 2nd. 3 becomes 3rd. You can pass in either an integer or a string representation of an integer.
django.ref.contrib.humanize
django.contrib.postgres 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. PostgreSQL specific aggregation functions General-purpose aggregation functions Aggregate functions for statistics Usage examples PostgreSQL specific database constraints ExclusionConstraint PostgreSQL specific query expressions ArraySubquery() expressions PostgreSQL specific model fields Indexing these fields ArrayField CIText fields HStoreField Range Fields PostgreSQL specific form fields and widgets Fields Widgets PostgreSQL specific database functions RandomUUID TransactionNow PostgreSQL specific model indexes BloomIndex BrinIndex BTreeIndex GinIndex GistIndex HashIndex SpGistIndex OpClass() expressions PostgreSQL specific lookups Trigram similarity Unaccent Database migration operations Creating extension using migrations CreateExtension BloomExtension BtreeGinExtension BtreeGistExtension CITextExtension CryptoExtension HStoreExtension TrigramExtension UnaccentExtension Managing collations using migrations Concurrent index operations Adding constraints without enforcing validation Full text search The search lookup SearchVector SearchQuery SearchRank SearchHeadline Changing the search configuration Weighting queries Performance Trigram similarity Validators KeysValidator Range validators
django.ref.contrib.postgres.index
class FlatpageFallbackMiddleware 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: If the flatpage has a custom template, it loads that template. Otherwise, it loads the template flatpages/default.html. It passes that template a single context variable, flatpage, which is the flatpage object. It uses RequestContext in rendering the template. 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.
django.ref.contrib.flatpages#django.contrib.flatpages.middleware.FlatpageFallbackMiddleware
class FlatPage 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.
django.ref.contrib.flatpages#django.contrib.flatpages.models.FlatPage
class FlatPageSitemap 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.
django.ref.contrib.flatpages#django.contrib.flatpages.sitemaps.FlatPageSitemap
Forms Detailed form API reference. For introductory material, see the Working with forms topic guide. The Forms API Bound and unbound forms Using forms to validate data Initial form values Checking which form data has changed Accessing the fields from the form Accessing “clean” data Outputting forms as HTML More granular output Customizing BoundField Binding uploaded files to a form Subclassing forms Prefixes for forms Form fields Core field arguments Checking if the field data has changed Built-in Field classes Slightly complex built-in Field classes Fields which handle relationships Creating custom fields Model Form Functions modelform_factory modelformset_factory inlineformset_factory Formset Functions formset_factory The form rendering API The low-level render API Built-in-template form renderers Context available in formset templates Context available in form templates Context available in widget templates Overriding built-in formset templates Overriding built-in form templates Overriding built-in widget templates Widgets Specifying widgets Setting arguments for widgets Widgets inheriting from the Select widget Customizing widget instances Base widget classes Built-in widgets Form and field validation Raising ValidationError Using validation in practice
django.ref.forms.index
class BooleanField(**kwargs) Default widget: CheckboxInput Empty value: False Normalizes to: A Python True or False value. Validates that the value is True (e.g. the check box is checked) if the field has required=True. Error message keys: required 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.
django.ref.forms.fields#django.forms.BooleanField
class BoundField 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.
django.ref.forms.api#django.forms.BoundField
BoundField.as_hidden(attrs=None, **kwargs) 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.
django.ref.forms.api#django.forms.BoundField.as_hidden
BoundField.as_widget(widget=None, attrs=None, only_initial=False) 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.
django.ref.forms.api#django.forms.BoundField.as_widget
BoundField.auto_id The HTML ID attribute for this BoundField. Returns an empty string if Form.auto_id is False.
django.ref.forms.api#django.forms.BoundField.auto_id
BoundField.css_classes(extra_classes=None) 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: >>> f = ContactForm(data={'message': ''}) >>> f['message'].css_classes() 'required' 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: >>> f = ContactForm(data={'message': ''}) >>> f['message'].css_classes('foo bar') 'foo bar required'
django.ref.forms.api#django.forms.BoundField.css_classes
BoundField.data This property returns the data for this BoundField extracted by the widget’s value_from_datadict() method, or None if it wasn’t given: >>> unbound_form = ContactForm() >>> print(unbound_form['subject'].data) None >>> bound_form = ContactForm(data={'subject': 'My Subject'}) >>> print(bound_form['subject'].data) My Subject
django.ref.forms.api#django.forms.BoundField.data
BoundField.errors A list-like object that is displayed as an HTML <ul class="errorlist"> when printed: >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''} >>> f = ContactForm(data, auto_id=False) >>> print(f['message']) <input type="text" name="message" required> >>> f['message'].errors ['This field is required.'] >>> print(f['message'].errors) <ul class="errorlist"><li>This field is required.</li></ul> >>> f['subject'].errors [] >>> print(f['subject'].errors) >>> str(f['subject'].errors) ''
django.ref.forms.api#django.forms.BoundField.errors
BoundField.field The form Field instance from the form class that this BoundField wraps.
django.ref.forms.api#django.forms.BoundField.field
BoundField.form The Form instance this BoundField is bound to.
django.ref.forms.api#django.forms.BoundField.form
BoundField.help_text The help_text of the field.
django.ref.forms.api#django.forms.BoundField.help_text
BoundField.html_name The name that will be used in the widget’s HTML name attribute. It takes the form prefix into account.
django.ref.forms.api#django.forms.BoundField.html_name
BoundField.id_for_label 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): <label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }} 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: my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'})) and using the template above, would render something like: <label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
django.ref.forms.api#django.forms.BoundField.id_for_label
BoundField.initial 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): >>> from datetime import datetime >>> class DatedCommentForm(CommentForm): ... created = forms.DateTimeField(initial=datetime.now) >>> f = DatedCommentForm() >>> f['created'].initial datetime.datetime(2021, 7, 27, 9, 5, 54) >>> f['created'].initial datetime.datetime(2021, 7, 27, 9, 5, 54) Using BoundField.initial is recommended over get_initial_for_field().
django.ref.forms.api#django.forms.BoundField.initial
BoundField.is_hidden Returns True if this BoundField’s widget is hidden.
django.ref.forms.api#django.forms.BoundField.is_hidden
BoundField.label The label of the field. This is used in label_tag().
django.ref.forms.api#django.forms.BoundField.label
BoundField.label_tag(contents=None, attrs=None, label_suffix=None) Renders a label tag for the form field using the template specified by Form.template_name_label. The available context is: field: This instance of the BoundField. contents: By default a concatenated string of BoundField.label and Form.label_suffix (or Field.label_suffix, if set). This can be overridden by the contents and label_suffix arguments. attrs: A dict containing for, Form.required_css_class, and id. id is generated by the field’s widget attrs or BoundField.auto_id. Additional attributes can be provided by the attrs argument. use_tag: A boolean which is True if the label has an id. If False the default template omits the <label> tag. 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: >>> f = ContactForm(data={'message': ''}) >>> print(f['message'].label_tag()) <label for="id_message">Message:</label> 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. Changed in Django 4.0: The label is now rendered using the template engine.
django.ref.forms.api#django.forms.BoundField.label_tag
BoundField.name The name of this field in the form: >>> f = ContactForm() >>> print(f['subject'].name) subject >>> print(f['message'].name) message
django.ref.forms.api#django.forms.BoundField.name
BoundField.value() Use this method to render the raw value of this field as it would be rendered by a Widget: >>> initial = {'subject': 'welcome'} >>> unbound_form = ContactForm(initial=initial) >>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial) >>> print(unbound_form['subject'].value()) welcome >>> print(bound_form['subject'].value()) hi
django.ref.forms.api#django.forms.BoundField.value
BoundField.widget_type 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: {% for field in form %} {% if field.widget_type == 'checkbox' %} # render one way {% else %} # render another way {% endif %} {% endfor %}
django.ref.forms.api#django.forms.BoundField.widget_type
class CharField(**kwargs) Default widget: TextInput Empty value: Whatever you’ve given as empty_value. Normalizes to: A string. Uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. Error message keys: required, max_length, min_length Has four optional arguments for validation: max_length min_length If provided, these arguments ensure that the string is at most or at least the given length. strip If True (default), the value will be stripped of leading and trailing whitespace. empty_value The value to use to represent “empty”. Defaults to an empty string.
django.ref.forms.fields#django.forms.CharField
empty_value The value to use to represent “empty”. Defaults to an empty string.
django.ref.forms.fields#django.forms.CharField.empty_value
max_length
django.ref.forms.fields#django.forms.CharField.max_length
min_length If provided, these arguments ensure that the string is at most or at least the given length.
django.ref.forms.fields#django.forms.CharField.min_length
strip If True (default), the value will be stripped of leading and trailing whitespace.
django.ref.forms.fields#django.forms.CharField.strip
class CheckboxInput input_type: 'checkbox' template_name: 'django/forms/widgets/checkbox.html' Renders as: <input type="checkbox" ...> Takes one optional argument: check_test A callable that takes the value of the CheckboxInput and returns True if the checkbox should be checked for that value.
django.ref.forms.widgets#django.forms.CheckboxInput
check_test A callable that takes the value of the CheckboxInput and returns True if the checkbox should be checked for that value.
django.ref.forms.widgets#django.forms.CheckboxInput.check_test
class CheckboxSelectMultiple template_name: 'django/forms/widgets/checkbox_select.html' option_template_name: 'django/forms/widgets/checkbox_option.html' Similar to SelectMultiple, but rendered as a list of checkboxes: <div> <div><input type="checkbox" name="..." ></div> ... </div> The outer <div> container receives the id attribute of the widget, if defined, or BoundField.auto_id otherwise. Changed in Django 4.0: So they are announced more concisely by screen readers, checkboxes were changed to render in <div> tags.
django.ref.forms.widgets#django.forms.CheckboxSelectMultiple
class ChoiceField(**kwargs) Default widget: Select Empty value: '' (an empty string) Normalizes to: A string. Validates that the given value exists in the list of choices. Error message keys: required, invalid_choice The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice. Takes one extra argument: choices 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.
django.ref.forms.fields#django.forms.ChoiceField
choices 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.
django.ref.forms.fields#django.forms.ChoiceField.choices
class ClearableFileInput template_name: 'django/forms/widgets/clearable_file_input.html' Renders as: <input type="file" ...> with an additional checkbox input to clear the field’s value, if the field is not required and has initial data.
django.ref.forms.widgets#django.forms.ClearableFileInput
class ComboField(**kwargs) Default widget: TextInput Empty value: '' (an empty string) Normalizes to: A string. Validates the given value against each of the fields specified as an argument to the ComboField. Error message keys: required, invalid Takes one extra required argument: fields The list of fields that should be used to validate the field’s value (in the order in which they are provided). >>> from django.forms import ComboField >>> f = ComboField(fields=[CharField(max_length=20), EmailField()]) >>> f.clean('[email protected]') '[email protected]' >>> f.clean('[email protected]') Traceback (most recent call last): ... ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
django.ref.forms.fields#django.forms.ComboField
fields The list of fields that should be used to validate the field’s value (in the order in which they are provided). >>> from django.forms import ComboField >>> f = ComboField(fields=[CharField(max_length=20), EmailField()]) >>> f.clean('[email protected]') '[email protected]' >>> f.clean('[email protected]') Traceback (most recent call last): ... ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
django.ref.forms.fields#django.forms.ComboField.fields
class DateField(**kwargs) Default widget: DateInput Empty value: None Normalizes to: A Python datetime.date object. Validates that the given value is either a datetime.date, datetime.datetime or string formatted in a particular date format. Error message keys: required, invalid Takes one optional argument: input_formats A list of formats used to attempt to convert a string to a valid datetime.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.
django.ref.forms.fields#django.forms.DateField
input_formats A list of formats used to attempt to convert a string to a valid datetime.date object.
django.ref.forms.fields#django.forms.DateField.input_formats
class DateInput input_type: 'text' template_name: 'django/forms/widgets/date.html' Renders as: <input type="text" ...> Takes same arguments as TextInput, with one more optional argument: format The format in which this field’s initial value will be displayed. If no format argument is provided, the default format is the first format found in DATE_INPUT_FORMATS and respects Format localization.
django.ref.forms.widgets#django.forms.DateInput
format The format in which this field’s initial value will be displayed.
django.ref.forms.widgets#django.forms.DateInput.format
class DateTimeField(**kwargs) Default widget: DateTimeInput Empty value: None Normalizes to: A Python datetime.datetime object. Validates that the given value is either a datetime.datetime, datetime.date or string formatted in a particular datetime format. Error message keys: required, invalid Takes one optional argument: input_formats A list of formats used to attempt to convert a string to a valid datetime.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: * '2006-10-25 14:30:59' * '2006-10-25T14:30:59' * '2006-10-25 14:30' * '2006-10-25T14:30' * '2006-10-25T14:30Z' * '2006-10-25T14:30+02:00' * '2006-10-25' 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.
django.ref.forms.fields#django.forms.DateTimeField
input_formats A list of formats used to attempt to convert a string to a valid datetime.datetime object, in addition to ISO 8601 formats.
django.ref.forms.fields#django.forms.DateTimeField.input_formats
class DateTimeInput input_type: 'text' template_name: 'django/forms/widgets/datetime.html' Renders as: <input type="text" ...> Takes same arguments as TextInput, with one more optional argument: format The format in which this field’s initial value will be displayed. If no format argument is provided, the default format is the first format found in 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.
django.ref.forms.widgets#django.forms.DateTimeInput
format The format in which this field’s initial value will be displayed.
django.ref.forms.widgets#django.forms.DateTimeInput.format
class DecimalField(**kwargs) Default widget: NumberInput when Field.localize is False, else TextInput. Empty value: None Normalizes to: A Python decimal. Validates that the given value is a decimal. Uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace is ignored. Error message keys: required, invalid, max_value, min_value, max_digits, max_decimal_places, max_whole_digits 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: max_value min_value These control the range of values permitted in the field, and should be given as decimal.Decimal values. max_digits The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value. decimal_places The maximum number of decimal places permitted.
django.ref.forms.fields#django.forms.DecimalField
decimal_places The maximum number of decimal places permitted.
django.ref.forms.fields#django.forms.DecimalField.decimal_places
max_digits The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value.
django.ref.forms.fields#django.forms.DecimalField.max_digits
max_value
django.ref.forms.fields#django.forms.DecimalField.max_value
min_value These control the range of values permitted in the field, and should be given as decimal.Decimal values.
django.ref.forms.fields#django.forms.DecimalField.min_value
class DurationField(**kwargs) Default widget: TextInput Empty value: None Normalizes to: A Python timedelta. Validates that the given value is a string which can be converted into a timedelta. The value must be between datetime.timedelta.min and datetime.timedelta.max. Error message keys: required, invalid, overflow. Accepts any format understood by parse_duration().
django.ref.forms.fields#django.forms.DurationField
class EmailField(**kwargs) Default widget: EmailInput Empty value: Whatever you’ve given as empty_value. Normalizes to: A string. Uses EmailValidator to validate that the given value is a valid email address, using a moderately complex regular expression. Error message keys: required, invalid Has three optional arguments max_length, min_length, and empty_value which work just as they do for CharField.
django.ref.forms.fields#django.forms.EmailField
class EmailInput input_type: 'email' template_name: 'django/forms/widgets/email.html' Renders as: <input type="email" ...>
django.ref.forms.widgets#django.forms.EmailInput
class ErrorList(initlist=None, error_class=None, renderer=None) 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. error_class The CSS classes to be used when rendering the error list. Any provided classes are added to the default errorlist class. renderer New in Django 4.0. Specifies the renderer to use for ErrorList. Defaults to None which means to use the default renderer specified by the FORM_RENDERER setting. template_name New in Django 4.0. 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. template_name_text New in Django 4.0. 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. template_name_ul New in Django 4.0. 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. get_context() New in Django 4.0. Return context for rendering of errors in a template. The available context is: errors : A list of the errors. error_class : A string of CSS classes. render(template_name=None, context=None, renderer=None) New in Django 4.0. The render method is called by __str__ as well as by the as_ul() method. All arguments are optional and will default to: template_name: Value returned by template_name context: Value returned by get_context() renderer: Value returned by renderer as_text() Renders the error list using the template defined by template_name_text. as_ul() 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.
django.ref.forms.api#django.forms.ErrorList
as_text() Renders the error list using the template defined by template_name_text.
django.ref.forms.api#django.forms.ErrorList.as_text
as_ul() Renders the error list using the template defined by template_name_ul.
django.ref.forms.api#django.forms.ErrorList.as_ul
error_class The CSS classes to be used when rendering the error list. Any provided classes are added to the default errorlist class.
django.ref.forms.api#django.forms.ErrorList.error_class
get_context() New in Django 4.0. Return context for rendering of errors in a template. The available context is: errors : A list of the errors. error_class : A string of CSS classes.
django.ref.forms.api#django.forms.ErrorList.get_context
render(template_name=None, context=None, renderer=None) New in Django 4.0. The render method is called by __str__ as well as by the as_ul() method. All arguments are optional and will default to: template_name: Value returned by template_name context: Value returned by get_context() renderer: Value returned by renderer
django.ref.forms.api#django.forms.ErrorList.render
renderer New in Django 4.0. Specifies the renderer to use for ErrorList. Defaults to None which means to use the default renderer specified by the FORM_RENDERER setting.
django.ref.forms.api#django.forms.ErrorList.renderer
template_name New in Django 4.0. 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.
django.ref.forms.api#django.forms.ErrorList.template_name
template_name_text New in Django 4.0. 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.
django.ref.forms.api#django.forms.ErrorList.template_name_text
template_name_ul New in Django 4.0. 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.
django.ref.forms.api#django.forms.ErrorList.template_name_ul
class Field(**kwargs)
django.ref.forms.fields#django.forms.Field
Field.clean(value)
django.ref.forms.fields#django.forms.Field.clean
Field.disabled
django.ref.forms.fields#django.forms.Field.disabled
Field.error_messages
django.ref.forms.fields#django.forms.Field.error_messages
Field.get_bound_field(form, field_name) 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.
django.ref.forms.api#django.forms.Field.get_bound_field
Field.has_changed()
django.ref.forms.fields#django.forms.Field.has_changed
Field.help_text
django.ref.forms.fields#django.forms.Field.help_text
Field.initial
django.ref.forms.fields#django.forms.Field.initial
Field.label
django.ref.forms.fields#django.forms.Field.label
Field.label_suffix
django.ref.forms.fields#django.forms.Field.label_suffix
Field.localize
django.ref.forms.fields#django.forms.Field.localize
Field.required
django.ref.forms.fields#django.forms.Field.required
Field.validators
django.ref.forms.fields#django.forms.Field.validators
Field.widget
django.ref.forms.fields#django.forms.Field.widget
class FileField(**kwargs) Default widget: ClearableFileInput Empty value: None Normalizes to: An UploadedFile object that wraps the file content and file name into a single object. Can validate that non-empty file data has been bound to the form. Error message keys: required, invalid, missing, empty, max_length 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.
django.ref.forms.fields#django.forms.FileField
class FileInput template_name: 'django/forms/widgets/file.html' Renders as: <input type="file" ...>
django.ref.forms.widgets#django.forms.FileInput
class FilePathField(**kwargs) Default widget: Select Empty value: '' (an empty string) Normalizes to: A string. Validates that the selected choice exists in the list of choices. Error message keys: required, invalid_choice The field allows choosing from files inside a certain directory. It takes five extra arguments; only path is required: path The absolute path to the directory whose contents you want listed. This directory must exist. recursive 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. match A regular expression pattern; only files with names matching this expression will be allowed as choices. allow_files 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. allow_folders 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.
django.ref.forms.fields#django.forms.FilePathField
allow_files 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.
django.ref.forms.fields#django.forms.FilePathField.allow_files
allow_folders 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.
django.ref.forms.fields#django.forms.FilePathField.allow_folders
match A regular expression pattern; only files with names matching this expression will be allowed as choices.
django.ref.forms.fields#django.forms.FilePathField.match
path The absolute path to the directory whose contents you want listed. This directory must exist.
django.ref.forms.fields#django.forms.FilePathField.path
recursive 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.
django.ref.forms.fields#django.forms.FilePathField.recursive
class FloatField(**kwargs) Default widget: NumberInput when Field.localize is False, else TextInput. Empty value: None Normalizes to: A Python float. Validates that the given value is a float. Uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace is allowed, as in Python’s float() function. Error message keys: required, invalid, max_value, min_value Takes two optional arguments for validation, max_value and min_value. These control the range of values permitted in the field.
django.ref.forms.fields#django.forms.FloatField
class Form
django.ref.forms.api#django.forms.Form
Form.add_error(field, error)
django.ref.forms.api#django.forms.Form.add_error
Form.as_p()
django.ref.forms.api#django.forms.Form.as_p
Form.as_table()
django.ref.forms.api#django.forms.Form.as_table
Form.as_ul()
django.ref.forms.api#django.forms.Form.as_ul
Form.auto_id
django.ref.forms.api#django.forms.Form.auto_id
Form.changed_data
django.ref.forms.api#django.forms.Form.changed_data