This class allows outputting the WKT representation of a geometry. See the WKBWriter.outdim, trim, and precision attributes for details about the constructor arguments.
Returns the WKT of the given geometry. Example:
See WKBWriter.outdim.
This property is used to enable or disable trimming of unnecessary decimals.
This property controls the rounding precision of coordinates; if set to None rounding is disabled.


To initialize an area object, pass in a keyword corresponding to the desired unit attribute name set with desired value. For example, the following creates an area object representing 5 square miles:
Returns the area value in units corresponding to the given unit attribute. For example:
Returns the area unit attribute name for the given full unit name. For example:


To initialize a distance object, pass in a keyword corresponding to the desired unit attribute name set with desired value. For example, the following creates a distance object representing 5 miles:
Returns the distance value in units corresponding to the given unit attribute. For example:
Returns the distance unit attribute name for the given full unit name. For example:


FileResponse is a subclass of StreamingHttpResponse optimized for binary files. It uses wsgi.file_wrapper if provided by the wsgi server, otherwise it streams the file out in small chunks.
If as_attachment=True, the Content-Disposition header is set to attachment, which asks the browser to offer the file to the user as a download. Otherwise, a Content-Disposition header with a value of inline (the browser default) will be set only if a filename is available.
If open_file doesn’t have a name or if the name of open_file isn’t appropriate, provide a custom file name using the filename parameter. Note that if you pass a file-like object like io.BytesIO, it’s your task to seek() it before passing it to FileResponse.
The Content-Length and Content-Type headers are automatically set when they can be guessed from contents of open_file.


This method is automatically called during the response initialization and set various headers (Content-Length, Content-Type, and Content-Disposition) depending on open_file.


Methods implementing a file-like interface for reading from an HttpRequest instance. This makes it possible to consume an incoming request in a streaming fashion. A common use-case would be to process a big XML payload with an iterative parser without constructing a whole XML tree in memory.
Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree:


Returns True if the request Accept header matches the mime_type argument:
Most browsers send Accept: */* by default, so this would return True for all content types. Setting an explicit Accept header in API requests can be useful for returning a different content type for those consumers only. See Content negotiation example of using accepts() to return different content to API consumers.
If a response varies depending on the content of the Accept header and you are using some form of caching like Django’s cache middleware, you should decorate the view with vary_on_headers('Accept') so that the responses are properly cached.


The raw HTTP request body as a bytestring. This is useful for processing data in different ways than conventional HTML forms: binary images, XML payload etc. For processing conventional form data, use HttpRequest.POST.
You can also read from an HttpRequest using a file-like interface with HttpRequest.read() or HttpRequest.readline(). Accessing the body attribute after reading the request with either of these I/O stream methods will produce a RawPostDataException.


Returns the absolute URI form of location. If no location is provided, the location will be set to request.get_full_path().
If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request. For example:
Note
Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has. If you need to redirect users to HTTPS, it’s best to let your web server redirect all HTTP traffic to HTTPS.


A dictionary of key/value parameters included in the CONTENT_TYPE header.


A string representing the MIME type of the request, parsed from the CONTENT_TYPE header.


A dictionary containing all cookies. Keys and values are strings.


The url template tag will use its value as the current_app argument to reverse().


A string representing the current encoding used to decode form submission data (or None, which means the DEFAULT_CHARSET setting is used). You can write to this attribute to change the encoding used when accessing the form data. Any subsequent attribute accesses (such as reading from GET or POST) will use the new encoding value. Useful if you know the form data is not in the DEFAULT_CHARSET encoding.


This will be used instead of DEFAULT_EXCEPTION_REPORTER for the current request. See Custom error reports for details.


This will be used instead of DEFAULT_EXCEPTION_REPORTER_FILTER for the current request. See Custom error reports for details.


A dictionary-like object containing all uploaded files. Each key in FILES is the name from the <input type="file" name="">. Each value in FILES is an UploadedFile.
See Managing files for more information.
FILES will only contain data if the request method was POST and the <form> that posted to the request had enctype="multipart/form-data". Otherwise, FILES will be a blank dictionary-like object.


A dictionary-like object containing all given HTTP GET parameters. See the QueryDict documentation below.


Returns the path, plus an appended query string, if applicable.
Example: "/music/bands/the_beatles/?print=true"


Like get_full_path(), but uses path_info instead of path.
Example: "/minfo/music/bands/the_beatles/?print=true"


Returns the originating host of the request using information from the HTTP_X_FORWARDED_HOST (if USE_X_FORWARDED_HOST is enabled) and HTTP_HOST headers, in that order. If they don’t provide a value, the method uses a combination of SERVER_NAME and SERVER_PORT as detailed in PEP 3333.
Example: "127.0.0.1:8000"
Raises django.core.exceptions.DisallowedHost if the host is not in ALLOWED_HOSTS or the domain name is invalid according to RFC 1034/1035.
Note
The get_host() method fails when the host is behind multiple proxies. One solution is to use middleware to rewrite the proxy headers, as in the following example:
This middleware should be positioned before any other middleware that relies on the value of get_host() – for instance, CommonMiddleware or CsrfViewMiddleware.


Returns the originating port of the request using information from the HTTP_X_FORWARDED_PORT (if USE_X_FORWARDED_PORT is enabled) and SERVER_PORT META variables, in that order.


Returns a cookie value for a signed cookie, or raises a django.core.signing.BadSignature exception if the signature is no longer valid. If you provide the default argument the exception will be suppressed and that default value will be returned instead.
The optional salt argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the max_age argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than max_age seconds.
For example:
See cryptographic signing for more information.


A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type) from the request.
The name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. You can access headers case-insensitively:
For use in, for example, Django templates, headers can also be looked up using underscores in place of hyphens:


Returns True if the request is secure; that is, if it was made with HTTPS.


A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:
With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.
Note that runserver strips all headers with underscores in the name, so you won’t see them in META. This prevents header-spoofing based on ambiguity between underscores and dashes both being normalizing to underscores in WSGI environment variables. It matches the behavior of web servers like Nginx and Apache 2.4+.
HttpRequest.headers is a simpler way to access all HTTP-prefixed headers, plus CONTENT_LENGTH and CONTENT_TYPE.


A string representing the HTTP method used in the request. This is guaranteed to be uppercase. For example:


A string representing the full path to the requested page, not including the scheme, domain, or query string.
Example: "/music/bands/the_beatles/"


Under some web server configurations, the portion of the URL after the host name is split up into a script prefix portion and a path info portion. The path_info attribute always contains the path info portion of the path, no matter what web server is being used. Using this instead of path can make your code easier to move between test and deployment servers.
For example, if the WSGIScriptAlias for your application is set to "/minfo", then path might be "/minfo/music/bands/the_beatles/" and path_info would be "/music/bands/the_beatles/".


A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.
It’s possible that a request can come in via POST with an empty POST dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t use if request.POST to check for use of the POST method; instead, use if request.method ==
"POST" (see HttpRequest.method).
POST does not include file-upload information. See FILES.


An instance of ResolverMatch representing the resolved URL. This attribute is only set after URL resolving took place, which means it’s available in all views but not in middleware which are executed before URL resolving takes place (you can use it in process_view() though).


A string representing the scheme of the request (http or https usually).


From the SessionMiddleware: A readable and writable, dictionary-like object that represents the current session.


From the CurrentSiteMiddleware: An instance of Site or RequestSite as returned by get_current_site() representing the current site.


This will be used as the root URLconf for the current request, overriding the ROOT_URLCONF setting. See How Django processes a request for details.
urlconf can be set to None to revert any changes made by previous middleware and return to using the ROOT_URLCONF.


From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in, user will be set to an instance of AnonymousUser. You can tell them apart with is_authenticated, like so:


Deletes the header with the given name. Fails silently if the header doesn’t exist. Case-insensitive.


Returns the value for the given header name. Case-insensitive.


Instantiates an HttpResponse object with the given page content, content type, and headers.
content is most commonly an iterator, bytestring, memoryview, or string. Other types will be converted to a bytestring by encoding their string representation. Iterators should return strings or bytestrings and those will be joined together to form the content of the response.
content_type is the MIME type optionally completed by a character set encoding and is used to fill the HTTP Content-Type header. If not specified, it is formed by 'text/html' and the DEFAULT_CHARSET settings, by default: "text/html; charset=utf-8".
status is the HTTP status code for the response. You can use Python’s http.HTTPStatus for meaningful aliases, such as HTTPStatus.NO_CONTENT.
reason is the HTTP response phrase. If not provided, a default phrase will be used.
charset is the charset in which the response will be encoded. If not given it will be extracted from content_type, and if that is unsuccessful, the DEFAULT_CHARSET setting will be used.
headers is a dict of HTTP headers for the response.
The headers parameter was added.


Sets the given header name to the given value. Both header and value should be strings.


A string denoting the charset in which the response will be encoded. If not given at HttpResponse instantiation time, it will be extracted from content_type and if that is unsuccessful, the DEFAULT_CHARSET setting will be used.


This method is called at the end of the request directly by the WSGI server.


A bytestring representing the content, encoded from a string if necessary.


Deletes the cookie with the given key. Fails silently if the key doesn’t exist.
Due to the way cookies work, path and domain should be the same values you used in set_cookie() – otherwise the cookie may not be deleted.


This method makes an HttpResponse instance a file-like object.


Returns the value for the given header, or an alternate if the header doesn’t exist.


Returns the value of HttpResponse.content. This method makes an HttpResponse instance a stream-like object.


Returns True or False based on a case-insensitive check for a header with the given name.


A case insensitive, dict-like object that provides an interface to all HTTP headers on the response. See Setting header fields.


Acts like dict.items() for HTTP headers on the response.


Always False. This method makes an HttpResponse instance a stream-like object.


The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases.
Unless explicitly set, reason_phrase is determined by the value of status_code.


Sets a cookie. The parameters are the same as in the Morsel cookie object in the Python standard library.
Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie.
HttpOnly is a flag included in a Set-Cookie HTTP response header. It’s part of the RFC 6265 standard for cookies and can be a useful way to mitigate the risk of a client-side script accessing the protected cookie data.
Use samesite='Strict' or samesite='Lax' to tell the browser not to send this cookie when performing a cross-origin request. SameSite isn’t supported by all browsers, so it’s not a replacement for Django’s CSRF protection, but rather a defense in depth measure.
Use samesite='None' (string) to explicitly state that this cookie is sent with all same-site and cross-site requests.
Warning
RFC 6265 states that user agents should support cookies of at least 4096 bytes. For many browsers this is also the maximum size. Django will not raise an exception if there’s an attempt to store a cookie of more than 4096 bytes, but many browsers will not set the cookie correctly.


Like set_cookie(), but cryptographic signing the cookie before setting it. Use in conjunction with HttpRequest.get_signed_cookie(). You can use the optional salt argument for added key strength, but you will need to remember to pass it to the corresponding HttpRequest.get_signed_cookie() call.


Sets a header unless it has already been set.


The HTTP status code for the response.
Unless reason_phrase is explicitly set, modifying the value of status_code outside the constructor will also modify the value of reason_phrase.


This is always False.
This attribute exists so middleware can treat streaming responses differently from regular responses.


Always True. This method makes an HttpResponse instance a stream-like object.


Writes a list of lines to the response. Line separators are not added. This method makes an HttpResponse instance a stream-like object.


Acts just like HttpResponse but uses a 400 status code.


Acts just like HttpResponse but uses a 403 status code.


Acts just like HttpResponse but uses a 410 status code.


Like HttpResponse, but uses a 405 status code. The first argument to the constructor is required: a list of permitted methods (e.g. ['GET', 'POST']).


Acts just like HttpResponse but uses a 404 status code.


The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304).


Like HttpResponseRedirect, but it returns a permanent redirect (HTTP status code 301) instead of a “found” redirect (status code 302).


The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. 'https://www.yahoo.com/search/'), an absolute path with no domain (e.g. '/search/'), or even a relative path (e.g. 'search/'). In that last case, the client browser will reconstruct the full URL itself according to the current path. See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302.
This read-only attribute represents the URL the response will redirect to (equivalent to the Location response header).


This read-only attribute represents the URL the response will redirect to (equivalent to the Location response header).


Acts just like HttpResponse but uses a 500 status code.


An HttpResponse subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences:
Its default Content-Type header is set to application/json.
The first parameter, data, should be a dict instance. If the safe parameter is set to False (see below) it can be any JSON-serializable object.
The encoder, which defaults to django.core.serializers.json.DjangoJSONEncoder, will be used to serialize the data. See JSON serialization for more details about this serializer.
The safe boolean parameter defaults to True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed). If safe is True and a non-dict object is passed as the first argument, a TypeError will be raised.
The json_dumps_params parameter is a dictionary of keyword arguments to pass to the json.dumps() call used to generate the response.


Returns True if the given key is set. This lets you do, e.g., if "foo"
in request.GET.


Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python’s standard KeyError, so you can stick to catching KeyError.)


Instantiates a QueryDict object based on query_string.
If query_string is not passed in, the resulting QueryDict will be empty (it will have no keys or values).
Most QueryDicts you encounter, and in particular those at request.POST and request.GET, will be immutable. If you are instantiating one yourself, you can make it mutable by passing mutable=True to its __init__().
Strings for setting both keys and values will be converted from encoding to str. If encoding is not set, it defaults to DEFAULT_CHARSET.


Sets the given key to [value] (a list whose single element is value). Note that this, as other dictionary functions that have side effects, can only be called on a mutable QueryDict (such as one that was created via QueryDict.copy()).


Appends an item to the internal list associated with key.


Returns a copy of the object using copy.deepcopy(). This copy will be mutable even if the original was not.


Returns a dict representation of QueryDict. For every (key, list) pair in QueryDict, dict will have (key, item), where item is one element of the list, using the same logic as QueryDict.__getitem__():


Uses the same logic as __getitem__(), with a hook for returning a default value if the key doesn’t exist.


Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and default is None. It’s guaranteed to return a list unless the default value provided isn’t a list.


Like dict.items(), except this uses the same last-value logic as __getitem__() and returns an iterator object instead of a view object. For example:


Like items(), except it includes all values, as a list, for each member of the dictionary. For example:


Returns a list of values for the given key and removes them from the dictionary. Raises KeyError if the key does not exist. For example:


Removes an arbitrary member of the dictionary (since there’s no concept of ordering), and returns a two value tuple containing the key and a list of all values for the key. Raises KeyError when called on an empty dictionary. For example:


Like dict.setdefault(), except it uses __setitem__() internally.


Sets the given key to list_ (unlike __setitem__()).


Like setdefault(), except it takes a list of values instead of a single value.


Takes either a QueryDict or a dictionary. Like dict.update(), except it appends to the current dictionary items rather than replacing them. For example:


Returns a string of the data in query string format. For example:
Use the safe parameter to pass characters which don’t require encoding. For example:


Like dict.values(), except this uses the same last-value logic as __getitem__() and returns an iterator instead of a view object. For example:


The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases.
Unless explicitly set, reason_phrase is determined by the value of status_code.


The HTTP status code for the response.
Unless reason_phrase is explicitly set, modifying the value of status_code outside the constructor will also modify the value of reason_phrase.


An iterator of the response content, bytestring encoded according to HttpResponse.charset.


See also
Django’s logging module extends Python’s builtin logging.
Logging is configured as part of the general Django django.setup() function, so it’s always available unless explicitly disabled.
By default, Django uses Python’s logging.config.dictConfig format.
The full set of default logging conditions are:
When DEBUG is True:
When DEBUG is False:
Independently of the value of DEBUG:
All loggers except django.server propagate logging to their parents, up to the root django logger. The console and mail_admins handlers are attached to the root logger to provide the behavior described above.
Python’s own defaults send records of level WARNING and higher to the console.
Django’s default logging configuration inherits Python’s defaults. It’s available as django.utils.log.DEFAULT_LOGGING and defined in django/utils/log.py:
See Configuring logging on how to complement or replace this default logging configuration.
Django provides a number of utilities to handle the particular requirements of logging in a web server environment.
Django provides several built-in loggers.
The parent logger for messages in the django named logger hierarchy. Django does not post messages using this name. Instead, it uses one of the loggers below.
Log messages related to the handling of requests. 5XX responses are raised as ERROR messages; 4XX responses are raised as WARNING messages. Requests that are logged to the django.security logger aren’t logged to django.request.
Messages to this logger have the following extra context:
Log messages related to the handling of requests received by the server invoked by the runserver command. HTTP 5XX responses are logged as ERROR messages, 4XX responses are logged as WARNING messages, and everything else is logged as INFO.
Messages to this logger have the following extra context:
Log messages related to the rendering of templates.
Messages relating to the interaction of code with the database. For example, every application-level SQL statement executed by a request is logged at the DEBUG level to this logger.
Messages to this logger have the following extra context:
For performance reasons, SQL logging is only enabled when settings.DEBUG is set to True, regardless of the logging level or handlers that are installed.
This logging does not include framework-level initialization (e.g. SET TIMEZONE) or transaction management queries (e.g. BEGIN, COMMIT, and ROLLBACK). Turn on query logging in your database if you wish to view all database queries.
The database alias was added to log messages.
The security loggers will receive messages on any occurrence of SuspiciousOperation and other security-related errors. There is a sub-logger for each subtype of security error, including all SuspiciousOperations. The level of the log event depends on where the exception is handled. Most occurrences are logged as a warning, while any SuspiciousOperation that reaches the WSGI handler will be logged as an error. For example, when an HTTP Host header is included in a request from a client that does not match ALLOWED_HOSTS, Django will return a 400 response, and an error message will be logged to the django.security.DisallowedHost logger.
These log events will reach the django logger by default, which mails error events to admins when DEBUG=False. Requests resulting in a 400 response due to a SuspiciousOperation will not be logged to the django.request logger, but only to the django.security logger.
To silence a particular type of SuspiciousOperation, you can override that specific logger following this example:
Other django.security loggers not based on SuspiciousOperation are:
Logs the SQL queries that are executed during schema changes to the database by the migrations framework. Note that it won’t log the queries executed by RunPython. Messages to this logger have params and sql in their extra context (but unlike django.db.backends, not duration). The values have the same meaning as explained in django.db.backends.
Django provides one log handler in addition to those provided by the
Python logging module.
This handler sends an email to the site ADMINS for each log message it receives.
If the log record contains a request attribute, the full details of the request will be included in the email. The email subject will include the phrase “internal IP” if the client’s IP address is in the INTERNAL_IPS setting; if not, it will include “EXTERNAL IP”.
If the log record contains stack trace information, that stack trace will be included in the email.
The include_html argument of AdminEmailHandler is used to control whether the traceback email includes an HTML attachment containing the full content of the debug web page that would have been produced if DEBUG were True. To set this value in your configuration, include it in the handler definition for django.utils.log.AdminEmailHandler, like this:
Be aware of the security implications of logging when using the AdminEmailHandler.
By setting the email_backend argument of AdminEmailHandler, the email backend that is being used by the handler can be overridden, like this:
By default, an instance of the email backend specified in EMAIL_BACKEND will be used.
The reporter_class argument of AdminEmailHandler allows providing an django.views.debug.ExceptionReporter subclass to customize the traceback text sent in the email body. You provide a string import path to the class you wish to use, like this:
Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.
Django provides some log filters in addition to those provided by the Python logging module.
This filter accepts a callback function (which should accept a single argument, the record to be logged), and calls it for each record that passes through the filter. Handling of that record will not proceed if the callback returns False.
For instance, to filter out UnreadablePostError (raised when a user cancels an upload) from the admin emails, you would create a filter function:
and then add it to your logging config:
This filter will only pass on records when settings.DEBUG is False.
This filter is used as follows in the default LOGGING configuration to ensure that the AdminEmailHandler only sends error emails to admins when DEBUG is False:
This filter is similar to RequireDebugFalse, except that records are passed only when DEBUG is True.


See also
Python programmers will often use print() in their code as a quick and convenient debugging tool. Using the logging framework is only a little more effort than that, but it’s much more elegant and flexible. As well as being useful for debugging, logging can also provide you with more - and better structured - information about the state and health of your application.
Django uses and extends Python’s builtin logging module to perform system logging. This module is discussed in detail in Python’s own documentation; this section provides a quick overview.
A Python logging configuration consists of four parts:
A logger is the entry point into the logging system. Each logger is a named bucket to which messages can be written for processing.
A logger is configured to have a log level. This log level describes the severity of the messages that the logger will handle. Python defines the following log levels:
Each message that is written to the logger is a Log Record. Each log record also has a log level indicating the severity of that specific message. A log record can also contain useful metadata that describes the event that is being logged. This can include details such as a stack trace or an error code.
When a message is given to the logger, the log level of the message is compared to the log level of the logger. If the log level of the message meets or exceeds the log level of the logger itself, the message will undergo further processing. If it doesn’t, the message will be ignored.
Once a logger has determined that a message needs to be processed, it is passed to a Handler.
The handler is the engine that determines what happens to each message in a logger. It describes a particular logging behavior, such as writing a message to the screen, to a file, or to a network socket.
Like loggers, handlers also have a log level. If the log level of a log record doesn’t meet or exceed the level of the handler, the handler will ignore the message.
A logger can have multiple handlers, and each handler can have a different log level. In this way, it is possible to provide different forms of notification depending on the importance of a message. For example, you could install one handler that forwards ERROR and CRITICAL messages to a paging service, while a second handler logs all messages (including ERROR and CRITICAL messages) to a file for later analysis.
A filter is used to provide additional control over which log records are passed from logger to handler.
By default, any log message that meets log level requirements will be handled. However, by installing a filter, you can place additional criteria on the logging process. For example, you could install a filter that only allows ERROR messages from a particular source to be emitted.
Filters can also be used to modify the logging record prior to being emitted. For example, you could write a filter that downgrades ERROR log records to WARNING records if a particular set of criteria are met.
Filters can be installed on loggers or on handlers; multiple filters can be used in a chain to perform multiple filtering actions.
Ultimately, a log record needs to be rendered as text. Formatters describe the exact format of that text. A formatter usually consists of a Python formatting string containing LogRecord attributes; however, you can also write custom formatters to implement specific formatting behavior.
The logging system handles potentially sensitive information. For example, the log record may contain information about a web request or a stack trace, while some of the data you collect in your own loggers may also have security implications. You need to be sure you know:
To help control the collection of sensitive information, you can explicitly designate certain sensitive information to be filtered out of error reports – read more about how to filter error reports.
The built-in AdminEmailHandler deserves a mention in the context of security. If its include_html option is enabled, the email message it sends will contain a full traceback, with names and values of local variables at each level of the stack, plus the values of your Django settings (in other words, the same level of detail that is exposed in a web page when DEBUG is True).
It’s generally not considered a good idea to send such potentially sensitive information over email. Consider instead using one of the many third-party services to which detailed logs can be sent to get the best of multiple worlds – the rich information of full tracebacks, clear management of who is notified and has access to the information, and so on.
Python’s logging library provides several techniques to configure logging, ranging from a programmatic interface to configuration files. By default, Django uses the dictConfig format.
In order to configure logging, you use LOGGING to define a dictionary of logging settings. These settings describe the loggers, handlers, filters and formatters that you want in your logging setup, and the log levels and other properties that you want those components to have.
By default, the LOGGING setting is merged with Django’s default logging configuration using the following scheme.
If the disable_existing_loggers key in the LOGGING dictConfig is set to True (which is the dictConfig default if the key is missing) then all loggers from the default configuration will be disabled. Disabled loggers are not the same as removed; the logger will still exist, but will silently discard anything logged to it, not even propagating entries to a parent logger. Thus you should be very careful using 'disable_existing_loggers': True; it’s probably not what you want. Instead, you can set disable_existing_loggers to False and redefine some or all of the default loggers; or you can set LOGGING_CONFIG to None and handle logging config yourself.
Logging is configured as part of the general Django setup() function. Therefore, you can be certain that loggers are always ready for use in your project code.
The full documentation for dictConfig format is the best source of information about logging configuration dictionaries. However, to give you a taste of what is possible, here are several examples.
To begin, here’s a small configuration that will allow you to output all log messages to the console:
This configures the parent root logger to send messages with the WARNING level and higher to the console handler. By adjusting the level to INFO or DEBUG you can display more messages. This may be useful during development.
Next we can add more fine-grained logging. Here’s an example of how to make the logging system print more messages from just the django named logger:
By default, this config sends messages from the django logger of level INFO or higher to the console. This is the same level as Django’s default logging config, except that the default config only displays log records when DEBUG=True. Django does not log many such INFO level messages. With this config, however, you can also set the environment variable DJANGO_LOG_LEVEL=DEBUG to see all of Django’s debug logging which is very verbose as it includes all database queries.
You don’t have to log to the console. Here’s a configuration which writes all logging from the django named logger to a local file:
If you use this example, be sure to change the 'filename' path to a location that’s writable by the user that’s running the Django application.
Finally, here’s an example of a fairly complex logging setup:
This logging configuration does the following things:
Defines two formatters:
simple, that outputs the log level name (e.g., DEBUG) and the log message.
The format string is a normal Python formatting string describing the details that are to be output on each logging line. The full list of detail that can be output can be found in Formatter Objects.
Defines two filters:
Defines two handlers:
Configures three loggers:
If you don’t want to use Python’s dictConfig format to configure your logger, you can specify your own configuration scheme.
The LOGGING_CONFIG setting defines the callable that will be used to configure Django’s loggers. By default, it points at Python’s logging.config.dictConfig() function. However, if you want to use a different configuration process, you can use any other callable that takes a single argument. The contents of LOGGING will be provided as the value of that argument when logging is configured.
If you don’t want to configure logging at all (or you want to manually configure logging using your own approach), you can set LOGGING_CONFIG to None. This will disable the configuration process for Django’s default logging.
Setting LOGGING_CONFIG to None only means that the automatic configuration process is disabled, not logging itself. If you disable the configuration process, Django will still make logging calls, falling back to whatever default logging behavior is defined.
Here’s an example that disables Django’s logging configuration and then manually configures logging:
Note that the default configuration process only calls LOGGING_CONFIG once settings are fully-loaded. In contrast, manually configuring the logging in your settings file will load your logging config immediately. As such, your logging config must appear after any settings on which it depends.


A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application.
The way Manager classes work is documented in Making queries; this document specifically touches on model options that customize Manager behavior.
By default, Django adds a Manager with the name objects to every Django model class. However, if you want to use objects as a field name, or if you want to use a name other than objects for the Manager, you can rename it on a per-model basis. To rename the Manager for a given class, define a class attribute of type models.Manager() on that model. For example:
Using this example model, Person.objects will generate an AttributeError exception, but Person.people.all() will provide a list of all Person objects.
You can use a custom Manager in a particular model by extending the base Manager class and instantiating your custom Manager in your model.
There are two reasons you might want to customize a Manager: to add extra Manager methods, and/or to modify the initial QuerySet the Manager returns.
Adding extra Manager methods is the preferred way to add “table-level” functionality to your models. (For “row-level” functionality – i.e., functions that act on a single instance of a model object – use Model methods, not custom Manager methods.)
For example, this custom Manager adds a method with_counts():
With this example, you’d use OpinionPoll.objects.with_counts() to get a QuerySet of OpinionPoll objects with the extra num_responses attribute attached.
A custom Manager method can return anything you want. It doesn’t have to return a QuerySet.
Another thing to note is that Manager methods can access self.model to get the model class to which they’re attached.
A Manager’s base QuerySet returns all objects in the system. For example, using this model:
…the statement Book.objects.all() will return all books in the database.
You can override a Manager’s base QuerySet by overriding the Manager.get_queryset() method. get_queryset() should return a QuerySet with the properties you require.
For example, the following model has two Managers – one that returns all objects, and one that returns only the books by Roald Dahl:
With this sample model, Book.objects.all() will return all books in the database, but Book.dahl_objects.all() will only return the ones written by Roald Dahl.
Because get_queryset() returns a QuerySet object, you can use filter(), exclude() and all the other QuerySet methods on it. So these statements are all legal:
This example also pointed out another interesting technique: using multiple managers on the same model. You can attach as many Manager() instances to a model as you’d like. This is a non-repetitive way to define common “filters” for your models.
For example:
This example allows you to request Person.authors.all(), Person.editors.all(), and Person.people.all(), yielding predictable results.
If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they’re defined in the model) has a special status. Django interprets the first Manager defined in a class as the “default” Manager, and several parts of Django (including dumpdata) will use that Manager exclusively for that model. As a result, it’s a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_queryset() results in an inability to retrieve objects you’d like to work with.
You can specify a custom default manager using Meta.default_manager_name.
If you’re writing some code that must handle an unknown model, for example, in a third-party app that implements a generic view, use this manager (or _base_manager) rather than assuming the model has an objects manager.
By default, Django uses an instance of the Model._base_manager manager class when accessing related objects (i.e. choice.question), not the _default_manager on the related object. This is because Django needs to be able to retrieve the related object, even if it would otherwise be filtered out (and hence be inaccessible) by the default manager.
If the normal base manager class (django.db.models.Manager) isn’t appropriate for your circumstances, you can tell Django which class to use by setting Meta.base_manager_name.
Base managers aren’t used when querying on related models, or when accessing a one-to-many or many-to-many relationship. For example, if the Question model from the tutorial had a deleted field and a base manager that filters out instances with deleted=True, a queryset like Choice.objects.filter(question__name__startswith='What') would include choices related to deleted questions.
This manager is used to access objects that are related to from some other model. In those situations, Django has to be able to see all the objects for the model it is fetching, so that anything which is referred to can be retrieved.
Therefore, you should not override get_queryset() to filter out any rows. If you do so, Django will return incomplete results.
While most methods from the standard QuerySet are accessible directly from the Manager, this is only the case for the extra methods defined on a custom QuerySet if you also implement them on the Manager:
This example allows you to call both authors() and editors() directly from the manager Person.people.
In lieu of the above approach which requires duplicating methods on both the QuerySet and the Manager, QuerySet.as_manager() can be used to create an instance of Manager with a copy of a custom QuerySet’s methods:
The Manager instance created by QuerySet.as_manager() will be virtually identical to the PersonManager from the previous example.
Not every QuerySet method makes sense at the Manager level; for instance we intentionally prevent the QuerySet.delete() method from being copied onto the Manager class.
Methods are copied according to the following rules:
For example:
For advanced usage you might want both a custom Manager and a custom QuerySet. You can do that by calling Manager.from_queryset() which returns a subclass of your base Manager with a copy of the custom QuerySet methods:
You may also store the generated class into a variable:
Here’s how Django handles custom managers and model inheritance:
These rules provide the necessary flexibility if you want to install a collection of custom managers on a group of models, via an abstract base class, but still customize the default manager. For example, suppose you have this base class:
If you use this directly in a subclass, objects will be the default manager if you declare no managers in the base class:
If you want to inherit from AbstractBase, but provide a different default manager, you can provide the default manager on the child class:
Here, default_manager is the default. The objects manager is still available, since it’s inherited, but isn’t used as the default.
Finally for this example, suppose you want to add extra managers to the child class, but still use the default from AbstractBase. You can’t add the new manager directly in the child class, as that would override the default and you would have to also explicitly include all the managers from the abstract base class. The solution is to put the extra managers in another base class and introduce it into the inheritance hierarchy after the defaults:
Note that while you can define a custom manager on the abstract model, you can’t invoke any methods using the abstract model. That is:
is legal, but:
will raise an exception. This is because managers are intended to encapsulate logic for managing collections of objects. Since you can’t have a collection of abstract objects, it doesn’t make sense to be managing them. If you have functionality that applies to the abstract model, you should put that functionality in a staticmethod or classmethod on the abstract model.
Whatever features you add to your custom Manager, it must be possible to make a shallow copy of a Manager instance; i.e., the following code must work:
Django makes shallow copies of manager objects during certain queries; if your Manager cannot be copied, those queries will fail.
This won’t be an issue for most custom managers. If you are just adding simple methods to your Manager, it is unlikely that you will inadvertently make instances of your Manager uncopyable. However, if you’re overriding __getattr__ or some other private method of your Manager object that controls object state, you should ensure that you don’t affect the ability of your Manager to be copied.


When you loop over the list of messages in a template, what you get are instances of the Message class. They have only a few attributes:


This class stores the message data in a cookie (signed with a secret hash to prevent manipulation) to persist notifications across requests. Old messages are dropped if the cookie data size would exceed 2048 bytes.
Messages format was changed to the RFC 6265 compliant format.


This class first uses CookieStorage, and falls back to using SessionStorage for the messages that could not fit in a single cookie. It also requires Django’s contrib.sessions application.
This behavior avoids writing to the session whenever possible. It should provide the best performance in the general case.


This class stores all messages inside of the request’s session. Therefore it requires Django’s contrib.sessions application.


Adds a success message attribute to FormView based classes
cleaned_data is the cleaned data from the form which is used for string formatting


cleaned_data is the cleaned data from the form which is used for string formatting


This document explains all middleware components that come with Django. For information on how to use them and how to write your own middleware, see the middleware usage guide.
Enable the site-wide cache. If these are enabled, each Django-powered page will be cached for as long as the CACHE_MIDDLEWARE_SECONDS setting defines. See the cache documentation.
Adds a few conveniences for perfectionists:
Performs URL rewriting based on the APPEND_SLASH and PREPEND_WWW settings.
If APPEND_SLASH is True and the initial URL doesn’t end with a slash, and it is not found in the URLconf, then a new URL is formed by appending a slash at the end. If this new URL is found in the URLconf, then Django redirects the request to this new URL. Otherwise, the initial URL is processed as usual.
For example, foo.com/bar will be redirected to foo.com/bar/ if you don’t have a valid URL pattern for foo.com/bar but do have a valid pattern for foo.com/bar/.
If PREPEND_WWW is True, URLs that lack a leading “www.” will be redirected to the same URL with a leading “www.”
Both of these options are meant to normalize URLs. The philosophy is that each URL should exist in one, and only one, place. Technically a URL foo.com/bar is distinct from foo.com/bar/ – a search-engine indexer would treat them as separate URLs – so it’s best practice to normalize URLs.
If necessary, individual views may be excluded from the APPEND_SLASH behavior using the no_append_slash() decorator:
Support for the no_append_slash() decorator was added.
Defaults to HttpResponsePermanentRedirect. Subclass CommonMiddleware and override the attribute to customize the redirects issued by the middleware.
Warning
Security researchers recently revealed that when compression techniques (including GZipMiddleware) are used on a website, the site may become exposed to a number of possible attacks. Before using GZipMiddleware on your site, you should consider very carefully whether you are subject to these attacks. If you’re in any doubt about whether you’re affected, you should avoid using GZipMiddleware. For more details, see the the BREACH paper (PDF) and breachattack.com.
The django.middleware.gzip.GZipMiddleware compresses content for browsers that understand GZip compression (all modern browsers).
This middleware should be placed before any other middleware that need to read or write the response body so that compression happens afterward.
It will NOT compress content if any of the following are true:
If the response has an ETag header, the ETag is made weak to comply with RFC 7232#section-2.1.
You can apply GZip compression to individual views using the gzip_page() decorator.
Handles conditional GET operations. If the response doesn’t have an ETag header, the middleware adds one if needed. If the response has an ETag or Last-Modified header, and the request has If-None-Match or If-Modified-Since, the response is replaced by an HttpResponseNotModified.
Enables language selection based on data from the request. It customizes content for each user. See the internationalization documentation.
Defaults to HttpResponseRedirect. Subclass LocaleMiddleware and override the attribute to customize the redirects issued by the middleware.
Enables cookie- and session-based message support. See the messages documentation.
Warning
If your deployment situation allows, it’s usually a good idea to have your front-end web server perform the functionality provided by the SecurityMiddleware. That way, if there are requests that aren’t served by Django (such as static media or user-uploaded files), they will have the same protections as requests to your Django application.
The django.middleware.security.SecurityMiddleware provides several security enhancements to the request/response cycle. Each one can be independently enabled or disabled with a setting.
For sites that should only be accessed over HTTPS, you can instruct modern browsers to refuse to connect to your domain name via an insecure connection (for a given period of time) by setting the “Strict-Transport-Security” header. This reduces your exposure to some SSL-stripping man-in-the-middle (MITM) attacks.
SecurityMiddleware will set this header for you on all HTTPS responses if you set the SECURE_HSTS_SECONDS setting to a non-zero integer value.
When enabling HSTS, it’s a good idea to first use a small value for testing, for example, SECURE_HSTS_SECONDS = 3600 for one hour. Each time a web browser sees the HSTS header from your site, it will refuse to communicate non-securely (using HTTP) with your domain for the given period of time. Once you confirm that all assets are served securely on your site (i.e. HSTS didn’t break anything), it’s a good idea to increase this value so that infrequent visitors will be protected (31536000 seconds, i.e. 1 year, is common).
Additionally, if you set the SECURE_HSTS_INCLUDE_SUBDOMAINS setting to True, SecurityMiddleware will add the includeSubDomains directive to the Strict-Transport-Security header. This is recommended (assuming all subdomains are served exclusively using HTTPS), otherwise your site may still be vulnerable via an insecure connection to a subdomain.
If you wish to submit your site to the browser preload list, set the SECURE_HSTS_PRELOAD setting to True. That appends the preload directive to the Strict-Transport-Security header.
Warning
The HSTS policy applies to your entire domain, not just the URL of the response that you set the header on. Therefore, you should only use it if your entire domain is served via HTTPS only.
Browsers properly respecting the HSTS header will refuse to allow users to bypass warnings and connect to a site with an expired, self-signed, or otherwise invalid SSL certificate. If you use HSTS, make sure your certificates are in good shape and stay that way!
Note
If you are deployed behind a load-balancer or reverse-proxy server, and the Strict-Transport-Security header is not being added to your responses, it may be because Django doesn’t realize that it’s on a secure connection; you may need to set the SECURE_PROXY_SSL_HEADER setting.
Browsers use the Referer header as a way to send information to a site about how users got there. When a user clicks a link, the browser will send the full URL of the linking page as the referrer. While this can be useful for some purposes – like figuring out who’s linking to your site – it also can cause privacy concerns by informing one site that a user was visiting another site.
Some browsers have the ability to accept hints about whether they should send the HTTP Referer header when a user clicks a link; this hint is provided via the Referrer-Policy header. This header can suggest any of three behaviors to browsers:
There are two types of conditions this header can tell a browser to watch out for:
Warning
When your site is served via HTTPS, Django’s CSRF protection system requires the Referer header to be present, so completely disabling the Referer header will interfere with CSRF protection. To gain most of the benefits of disabling Referer headers while also keeping CSRF protection, consider enabling only same-origin referrers.
SecurityMiddleware can set the Referrer-Policy header for you, based on the SECURE_REFERRER_POLICY setting (note spelling: browsers send a Referer header when a user clicks a link, but the header instructing a browser whether to do so is spelled Referrer-Policy). The valid values for this setting are:
Unknown Policy Values
Where a policy value is unknown by a user agent, it is possible to specify multiple policy values to provide a fallback. The last specified value that is understood takes precedence. To support this, an iterable or comma-separated string can be used with SECURE_REFERRER_POLICY.
Some browsers have the ability to isolate top-level windows from other documents by putting them in a separate browsing context group based on the value of the Cross-Origin Opener Policy (COOP) header. If a document that is isolated in this way opens a cross-origin popup window, the popup’s window.opener property will be null. Isolating windows using COOP is a defense-in-depth protection against cross-origin attacks, especially those like Spectre which allowed exfiltration of data loaded into a shared browsing context.
SecurityMiddleware can set the Cross-Origin-Opener-Policy header for you, based on the SECURE_CROSS_ORIGIN_OPENER_POLICY setting. The valid values for this setting are:
Some browsers will try to guess the content types of the assets that they fetch, overriding the Content-Type header. While this can help display sites with improperly configured servers, it can also pose a security risk.
If your site serves user-uploaded files, a malicious user could upload a specially-crafted file that would be interpreted as HTML or JavaScript by the browser when you expected it to be something harmless.
To prevent the browser from guessing the content type and force it to always use the type provided in the Content-Type header, you can pass the X-Content-Type-Options: nosniff header. SecurityMiddleware will do this for all responses if the SECURE_CONTENT_TYPE_NOSNIFF setting is True.
Note that in most deployment situations where Django isn’t involved in serving user-uploaded files, this setting won’t help you. For example, if your MEDIA_URL is served directly by your front-end web server (nginx, Apache, etc.) then you’d want to set this header there. On the other hand, if you are using Django to do something like require authorization in order to download files and you cannot set the header using your web server, this setting will be useful.
If your site offers both HTTP and HTTPS connections, most users will end up with an unsecured connection by default. For best security, you should redirect all HTTP connections to HTTPS.
If you set the SECURE_SSL_REDIRECT setting to True, SecurityMiddleware will permanently (HTTP 301) redirect all HTTP connections to HTTPS.
Note
For performance reasons, it’s preferable to do these redirects outside of Django, in a front-end load balancer or reverse-proxy server such as nginx. SECURE_SSL_REDIRECT is intended for the deployment situations where this isn’t an option.
If the SECURE_SSL_HOST setting has a value, all redirects will be sent to that host instead of the originally-requested host.
If there are a few pages on your site that should be available over HTTP, and not redirected to HTTPS, you can list regular expressions to match those URLs in the SECURE_REDIRECT_EXEMPT setting.
Note
If you are deployed behind a load-balancer or reverse-proxy server and Django can’t seem to tell when a request actually is already secure, you may need to set the SECURE_PROXY_SSL_HEADER setting.
Enables session support. See the session documentation.
Adds the site attribute representing the current site to every incoming HttpRequest object. See the sites documentation.
Adds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object. See Authentication in web requests.
Middleware for utilizing web server provided authentication. See How to authenticate using REMOTE_USER for usage details.
Middleware for utilizing web server provided authentication when enabled only on the login page. See Using REMOTE_USER on login pages only for usage details.
Adds protection against Cross Site Request Forgeries by adding hidden form fields to POST forms and checking requests for the correct value. See the Cross Site Request Forgery protection documentation.
Simple clickjacking protection via the X-Frame-Options header.
Here are some hints about the ordering of various Django middleware classes:
SecurityMiddleware
It should go near the top of the list if you’re going to turn on the SSL redirect as that avoids running through a bunch of other unnecessary middleware.
UpdateCacheMiddleware
Before those that modify the Vary header (SessionMiddleware, GZipMiddleware, LocaleMiddleware).
GZipMiddleware
Before any middleware that may change or use the response body.
After UpdateCacheMiddleware: Modifies Vary header.
SessionMiddleware
Before any middleware that may raise an exception to trigger an error view (such as PermissionDenied) if you’re using CSRF_USE_SESSIONS.
After UpdateCacheMiddleware: Modifies Vary header.
ConditionalGetMiddleware
Before any middleware that may change the response (it sets the ETag header).
After GZipMiddleware so it won’t calculate an ETag header on gzipped contents.
LocaleMiddleware
One of the topmost, after SessionMiddleware (uses session data) and UpdateCacheMiddleware (modifies Vary header).
CommonMiddleware
Before any middleware that may change the response (it sets the Content-Length header). A middleware that appears before CommonMiddleware and changes the response must reset Content-Length.
Close to the top: it redirects when APPEND_SLASH or PREPEND_WWW are set to True.
After SessionMiddleware if you’re using CSRF_USE_SESSIONS.
CsrfViewMiddleware
Before any view middleware that assumes that CSRF attacks have been dealt with.
Before RemoteUserMiddleware, or any other authentication middleware that may perform a login, and hence rotate the CSRF token, before calling down the middleware chain.
After SessionMiddleware if you’re using CSRF_USE_SESSIONS.
AuthenticationMiddleware
After SessionMiddleware: uses session storage.
MessageMiddleware
After SessionMiddleware: can use session-based storage.
FetchFromCacheMiddleware
After any middleware that modifies the Vary header: that header is used to pick a value for the cache hash-key.
FlatpageFallbackMiddleware
Should be near the bottom as it’s a last-resort type of middleware.
RedirectFallbackMiddleware
Should be near the bottom as it’s a last-resort type of middleware.


Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output.
Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, AuthenticationMiddleware, that associates users with requests using sessions.
This document explains how middleware works, how you activate middleware, and how to write your own middleware. Django ships with some built-in middleware you can use right out of the box. They’re documented in the built-in middleware reference.
A middleware factory is a callable that takes a get_response callable and returns a middleware. A middleware is a callable that takes a request and returns a response, just like a view.
A middleware can be written as a function that looks like this:
Or it can be written as a class whose instances are callable, like this:
The get_response callable provided by Django might be the actual view (if this is the last listed middleware) or it might be the next middleware in the chain. The current middleware doesn’t need to know or care what exactly it is, just that it represents whatever comes next.
The above is a slight simplification – the get_response callable for the last middleware in the chain won’t be the actual view but rather a wrapper method from the handler which takes care of applying view middleware, calling the view with appropriate URL arguments, and applying template-response and exception middleware.
Middleware can either support only synchronous Python (the default), only asynchronous Python, or both. See Asynchronous support for details of how to advertise what you support, and know what kind of request you are getting.
Middleware can live anywhere on your Python path.
Middleware factories must accept a get_response argument. You can also initialize some global state for the middleware. Keep in mind a couple of caveats:
It’s sometimes useful to determine at startup time whether a piece of middleware should be used. In these cases, your middleware’s __init__() method may raise MiddlewareNotUsed. Django will then remove that middleware from the middleware process and log a debug message to the django.request logger when DEBUG is True.
To activate a middleware component, add it to the MIDDLEWARE list in your Django settings.
In MIDDLEWARE, each middleware component is represented by a string: the full Python path to the middleware factory’s class or function name. For example, here’s the default value created by django-admin
startproject:
A Django installation doesn’t require any middleware — MIDDLEWARE can be empty, if you’d like — but it’s strongly suggested that you at least use CommonMiddleware.
The order in MIDDLEWARE matters because a middleware can depend on other middleware. For instance, AuthenticationMiddleware stores the authenticated user in the session; therefore, it must run after SessionMiddleware. See Middleware ordering for some common hints about ordering of Django middleware classes.
During the request phase, before calling the view, Django applies middleware in the order it’s defined in MIDDLEWARE, top-down.
You can think of it like an onion: each middleware class is a “layer” that wraps the view, which is in the core of the onion. If the request passes through all the layers of the onion (each one calls get_response to pass the request in to the next layer), all the way to the view at the core, the response will then pass through every layer (in reverse order) on the way back out.
If one of the layers decides to short-circuit and return a response without ever calling its get_response, none of the layers of the onion inside that layer (including the view) will see the request or the response. The response will only return through the same layers that the request passed in through.
Besides the basic request/response middleware pattern described earlier, you can add three other special methods to class-based middleware:
request is an HttpRequest object. view_func is the Python function that Django is about to use. (It’s the actual function object, not the name of the function as a string.) view_args is a list of positional arguments that will be passed to the view, and view_kwargs is a dictionary of keyword arguments that will be passed to the view. Neither view_args nor view_kwargs include the first view argument (request).
process_view() is called just before Django calls the view.
It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won’t bother calling the appropriate view; it’ll apply response middleware to that HttpResponse and return the result.
Note
Accessing request.POST inside middleware before the view runs or in process_view() will prevent any view running after the middleware from being able to modify the upload handlers for the request, and should normally be avoided.
The CsrfViewMiddleware class can be considered an exception, as it provides the csrf_exempt() and csrf_protect() decorators which allow views to explicitly control at what point the CSRF validation should occur.
request is an HttpRequest object. exception is an Exception object raised by the view function.
Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the template response and response middleware will be applied and the resulting response returned to the browser. Otherwise, default exception handling kicks in.
Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the process_exception methods of the middleware classes above that middleware won’t be called at all.
request is an HttpRequest object. response is the TemplateResponse object (or equivalent) returned by a Django view or by a middleware.
process_template_response() is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent.
It must return a response object that implements a render method. It could alter the given response by changing response.template_name and response.context_data, or it could create and return a brand-new TemplateResponse or equivalent.
You don’t need to explicitly render responses – responses will be automatically rendered once all template response middleware has been called.
Middleware are run in reverse order during the response phase, which includes process_template_response().
Unlike HttpResponse, StreamingHttpResponse does not have a content attribute. As a result, middleware can no longer assume that all responses will have a content attribute. If they need access to the content, they must test for streaming responses and adjust their behavior accordingly:
Note
streaming_content should be assumed to be too large to hold in memory. Response middleware may wrap it in a new generator, but must not consume it. Wrapping is typically implemented as follows:
Django automatically converts exceptions raised by the view or by middleware into an appropriate HTTP response with an error status code. Certain exceptions are converted to 4xx status codes, while an unknown exception is converted to a 500 status code.
This conversion takes place before and after each middleware (you can think of it as the thin film in between each layer of the onion), so that every middleware can always rely on getting some kind of HTTP response back from calling its get_response callable. Middleware don’t need to worry about wrapping their call to get_response in a try/except and handling an exception that might have been raised by a later middleware or the view. Even if the very next middleware in the chain raises an Http404 exception, for example, your middleware won’t see that exception; instead it will get an HttpResponse object with a status_code of 404.
You can set DEBUG_PROPAGATE_EXCEPTIONS to True to skip this conversion and propagate exceptions upward.
Middleware can support any combination of synchronous and asynchronous requests. Django will adapt requests to fit the middleware’s requirements if it cannot support both, but at a performance penalty.
By default, Django assumes that your middleware is capable of handling only synchronous requests. To change these assumptions, set the following attributes on your middleware factory function or class:
If your middleware has both sync_capable = True and async_capable = True, then Django will pass it the request without converting it. In this case, you can work out if your middleware will receive async requests by checking if the get_response object you are passed is a coroutine function, using asyncio.iscoroutinefunction().
The django.utils.decorators module contains sync_only_middleware(), async_only_middleware(), and sync_and_async_middleware() decorators that allow you to apply these flags to middleware factory functions.
The returned callable must match the sync or async nature of the get_response method. If you have an asynchronous get_response, you must return a coroutine function (async def).
process_view, process_template_response and process_exception methods, if they are provided, should also be adapted to match the sync/async mode. However, Django will individually adapt them as required if you do not, at an additional performance penalty.
Here’s an example of how to create a middleware function that supports both:
Note
If you declare a hybrid middleware that supports both synchronous and asynchronous calls, the kind of call you get may not match the underlying view. Django will optimize the middleware call stack to have as few sync/async transitions as possible.
Thus, even if you are wrapping an async view, you may be called in sync mode if there is other, synchronous middleware between you and the view.
Django provides django.utils.deprecation.MiddlewareMixin to ease creating middleware classes that are compatible with both MIDDLEWARE and the old MIDDLEWARE_CLASSES, and support synchronous and asynchronous requests. All middleware classes included with Django are compatible with both settings.
The mixin provides an __init__() method that requires a get_response argument and stores it in self.get_response.
The __call__() method:
If used with MIDDLEWARE_CLASSES, the __call__() method will never be used; Django calls process_request() and process_response() directly.
In most cases, inheriting from this mixin will be sufficient to make an old-style middleware compatible with the new system with sufficient backwards-compatibility. The new short-circuiting semantics will be harmless or even beneficial to the existing middleware. In a few cases, a middleware class may need some changes to adjust to the new semantics.
These are the behavioral differences between using MIDDLEWARE and MIDDLEWARE_CLASSES:


Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into.
There are several commands which you will use to interact with migrations and Django’s handling of database schema:
You should think of migrations as a version control system for your database schema. makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database.
The migration files for each app live in a “migrations” directory inside of that app, and are designed to be committed to, and distributed as part of, its codebase. You should be making them once on your development machine and then running the same migrations on your colleagues’ machines, your staging machines, and eventually your production machines.
Note
It is possible to override the name of the package which contains the migrations on a per-app basis by modifying the MIGRATION_MODULES setting.
Migrations will run the same way on the same dataset and produce consistent results, meaning that what you see in development and staging is, under the same circumstances, exactly what will happen in production.
Django will make migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations later on (for example, if you’ve set custom validators).
Migrations are supported on all backends that Django ships with, as well as any third-party backends if they have programmed in support for schema alteration (done via the SchemaEditor class).
However, some databases are more capable than others when it comes to schema migrations; some of the caveats are covered below.
PostgreSQL is the most capable of all the databases here in terms of schema support.
The only caveat is that prior to PostgreSQL 11, adding columns with default values causes a full rewrite of the table, for a time proportional to its size. For this reason, it’s recommended you always create new columns with null=True, as this way they will be added immediately.
MySQL lacks support for transactions around schema alteration operations, meaning that if a migration fails to apply you will have to manually unpick the changes in order to try again (it’s impossible to roll back to an earlier point).
In addition, MySQL will fully rewrite tables for almost every schema operation and generally takes a time proportional to the number of rows in the table to add or remove columns. On slower hardware this can be worse than a minute per million rows - adding a few columns to a table with just a few million rows could lock your site up for over ten minutes.
Finally, MySQL has relatively small limits on name lengths for columns, tables and indexes, as well as a limit on the combined size of all columns an index covers. This means that indexes that are possible on other backends will fail to be created under MySQL.
SQLite has very little built-in schema alteration support, and so Django attempts to emulate it by:
This process generally works well, but it can be slow and occasionally buggy. It is not recommended that you run and migrate SQLite in a production environment unless you are very aware of the risks and its limitations; the support Django ships with is designed to allow developers to use SQLite on their local machines to develop less complex Django projects without the need for a full database.
Django can create migrations for you. Make changes to your models - say, add a field and remove a model - and then run makemigrations:
Your models will be scanned and compared to the versions currently contained in your migration files, and then a new set of migrations will be written out. Make sure to read the output to see what makemigrations thinks you have changed - it’s not perfect, and for complex changes it might not be detecting what you expect.
Once you have your new migration files, you should apply them to your database to make sure they work as expected:
Once the migration is applied, commit the migration and the models change to your version control system as a single commit - that way, when other developers (or your production servers) check out the code, they’ll get both the changes to your models and the accompanying migration at the same time.
If you want to give the migration(s) a meaningful name instead of a generated one, you can use the makemigrations --name option:
Because migrations are stored in version control, you’ll occasionally come across situations where you and another developer have both committed a migration to the same app at the same time, resulting in two migrations with the same number.
Don’t worry - the numbers are just there for developers’ reference, Django just cares that each migration has a different name. Migrations specify which other migrations they depend on - including earlier migrations in the same app - in the file, so it’s possible to detect when there’s two new migrations for the same app that aren’t ordered.
When this happens, Django will prompt you and give you some options. If it thinks it’s safe enough, it will offer to automatically linearize the two migrations for you. If not, you’ll have to go in and modify the migrations yourself - don’t worry, this isn’t difficult, and is explained more in Migration files below.
On databases that support DDL transactions (SQLite and PostgreSQL), all migration operations will run inside a single transaction by default. In contrast, if a database doesn’t support DDL transactions (e.g. MySQL, Oracle) then all operations will run without a transaction.
You can prevent a migration from running in a transaction by setting the atomic attribute to False. For example:
It’s also possible to execute parts of the migration inside a transaction using atomic() or by passing atomic=True to RunPython. See Non-atomic migrations for more details.
While migrations are per-app, the tables and relationships implied by your models are too complex to be created for one app at a time. When you make a migration that requires something else to run - for example, you add a ForeignKey in your books app to your authors app - the resulting migration will contain a dependency on a migration in authors.
This means that when you run the migrations, the authors migration runs first and creates the table the ForeignKey references, and then the migration that makes the ForeignKey column runs afterward and creates the constraint. If this didn’t happen, the migration would try to create the ForeignKey column without the table it’s referencing existing and your database would throw an error.
This dependency behavior affects most migration operations where you restrict to a single app. Restricting to a single app (either in makemigrations or migrate) is a best-efforts promise, and not a guarantee; any other apps that need to be used to get dependencies correct will be.
Apps without migrations must not have relations (ForeignKey, ManyToManyField, etc.) to apps with migrations. Sometimes it may work, but it’s not supported.
Migrations are stored as an on-disk format, referred to here as “migration files”. These files are actually normal Python files with an agreed-upon object layout, written in a declarative style.
A basic migration file looks like this:
What Django looks for when it loads a migration file (as a Python module) is a subclass of django.db.migrations.Migration called Migration. It then inspects this object for four attributes, only two of which are used most of the time:
The operations are the key; they are a set of declarative instructions which tell Django what schema changes need to be made. Django scans them and builds an in-memory representation of all of the schema changes to all apps, and uses this to generate the SQL which makes the schema changes.
That in-memory structure is also used to work out what the differences are between your models and the current state of your migrations; Django runs through all the changes, in order, on an in-memory set of models to come up with the state of your models last time you ran makemigrations. It then uses these models to compare against the ones in your models.py files to work out what you have changed.
You should rarely, if ever, need to edit migration files by hand, but it’s entirely possible to write them manually if you need to. Some of the more complex operations are not autodetectable and are only available via a hand-written migration, so don’t be scared about editing them if you have to.
You can’t modify the number of positional arguments in an already migrated custom field without raising a TypeError. The old migration will call the modified __init__ method with the old signature. So if you need a new argument, please create a keyword argument and add something like assert 'argument_name' in kwargs in the constructor.
You can optionally serialize managers into migrations and have them available in RunPython operations. This is done by defining a use_in_migrations attribute on the manager class:
If you are using the from_queryset() function to dynamically generate a manager class, you need to inherit from the generated class to make it importable:
Please refer to the notes about Historical models in migrations to see the implications that come along.
The “initial migrations” for an app are the migrations that create the first version of that app’s tables. Usually an app will have one initial migration, but in some cases of complex model interdependencies it may have two or more.
Initial migrations are marked with an initial = True class attribute on the migration class. If an initial class attribute isn’t found, a migration will be considered “initial” if it is the first migration in the app (i.e. if it has no dependencies on any other migration in the same app).
When the migrate --fake-initial option is used, these initial migrations are treated specially. For an initial migration that creates one or more tables (CreateModel operation), Django checks that all of those tables already exist in the database and fake-applies the migration if so. Similarly, for an initial migration that adds one or more fields (AddField operation), Django checks that all of the respective columns already exist in the database and fake-applies the migration if so. Without --fake-initial, initial migrations are treated no differently from any other migration.
As previously discussed, you may need to linearize migrations manually when two development branches are joined. While editing migration dependencies, you can inadvertently create an inconsistent history state where a migration has been applied but some of its dependencies haven’t. This is a strong indication that the dependencies are incorrect, so Django will refuse to run migrations or make new migrations until it’s fixed. When using multiple databases, you can use the allow_migrate() method of database routers to control which databases makemigrations checks for consistent history.
New apps come preconfigured to accept migrations, and so you can add migrations by running makemigrations once you’ve made some changes.
If your app already has models and database tables, and doesn’t have migrations yet (for example, you created it against a previous Django version), you’ll need to convert it to use migrations by running:
This will make a new initial migration for your app. Now, run python
manage.py migrate --fake-initial, and Django will detect that you have an initial migration and that the tables it wants to create already exist, and will mark the migration as already applied. (Without the migrate
--fake-initial flag, the command would error out because the tables it wants to create already exist.)
Note that this only works given two things:
Migrations can be reversed with migrate by passing the number of the previous migration. For example, to reverse migration books.0003:
If you want to reverse all migrations applied for an app, use the name zero:
A migration is irreversible if it contains any irreversible operations. Attempting to reverse such migrations will raise IrreversibleError:
When you run migrations, Django is working from historical versions of your models stored in the migration files. If you write Python code using the RunPython operation, or if you have allow_migrate methods on your database routers, you need to use these historical model versions rather than importing them directly.
Warning
If you import models directly rather than using the historical models, your migrations may work initially but will fail in the future when you try to re-run old migrations (commonly, when you set up a new installation and run through all the migrations to set up the database).
This means that historical model problems may not be immediately obvious. If you run into this kind of failure, it’s OK to edit the migration to use the historical models rather than direct imports and commit those changes.
Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True) and Meta options (also versioned, so they may be different from your current ones).
Warning
This means that you will NOT have custom save() methods called on objects when you access them in migrations, and you will NOT have any custom constructors or instance methods. Plan appropriately!
References to functions in field options such as upload_to and limit_choices_to and model manager declarations with managers having use_in_migrations = True are serialized in migrations, so the functions and classes will need to be kept around for as long as there is a migration referencing them. Any custom model fields will also need to be kept, since these are imported directly by migrations.
In addition, the concrete base classes of the model are stored as pointers, so you must always keep base classes around for as long as there is a migration that contains a reference to them. On the plus side, methods and managers from these base classes inherit normally, so if you absolutely need access to these you can opt to move them into a superclass.
To remove old references, you can squash migrations or, if there aren’t many references, copy them into the migration files.
Similar to the “references to historical functions” considerations described in the previous section, removing custom model fields from your project or third-party app will cause a problem if they are referenced in old migrations.
To help with this situation, Django provides some model field attributes to assist with model field deprecation using the system checks framework.
Add the system_check_deprecated_details attribute to your model field similar to the following:
After a deprecation period of your choosing (two or three feature releases for fields in Django itself), change the system_check_deprecated_details attribute to system_check_removed_details and update the dictionary similar to:
You should keep the field’s methods that are required for it to operate in database migrations such as __init__(), deconstruct(), and get_internal_type(). Keep this stub field for as long as any migrations which reference the field exist. For example, after squashing migrations and removing the old ones, you should be able to remove the field completely.
As well as changing the database schema, you can also use migrations to change the data in the database itself, in conjunction with the schema if you want.
Migrations that alter data are usually called “data migrations”; they’re best written as separate migrations, sitting alongside your schema migrations.
Django can’t automatically generate data migrations for you, as it does with schema migrations, but it’s not very hard to write them. Migration files in Django are made up of Operations, and the main operation you use for data migrations is RunPython.
To start, make an empty migration file you can work from (Django will put the file in the right place, suggest a name, and add dependencies for you):
Then, open up the file; it should look something like this:
Now, all you need to do is create a new function and have RunPython use it. RunPython expects a callable as its argument which takes two arguments - the first is an app registry that has the historical versions of all your models loaded into it to match where in your history the migration sits, and the second is a SchemaEditor, which you can use to manually effect database schema changes (but beware, doing this can confuse the migration autodetector!)
Let’s write a migration that populates our new name field with the combined values of first_name and last_name (we’ve come to our senses and realized that not everyone has first and last names). All we need to do is use the historical model and iterate over the rows:
Once that’s done, we can run python manage.py migrate as normal and the data migration will run in place alongside other migrations.
You can pass a second callable to RunPython to run whatever logic you want executed when migrating backwards. If this callable is omitted, migrating backwards will raise an exception.
When writing a RunPython function that uses models from apps other than the one in which the migration is located, the migration’s dependencies attribute should include the latest migration of each app that is involved, otherwise you may get an error similar to: LookupError: No installed app
with label 'myappname' when you try to retrieve the model in the RunPython function using apps.get_model().
In the following example, we have a migration in app1 which needs to use models in app2. We aren’t concerned with the details of move_m1 other than the fact it will need to access models from both apps. Therefore we’ve added a dependency that specifies the last migration of app2:
If you’re interested in the more advanced migration operations, or want to be able to write your own, see the migration operations reference and the “how-to” on writing migrations.
You are encouraged to make migrations freely and not worry about how many you have; the migration code is optimized to deal with hundreds at a time without much slowdown. However, eventually you will want to move back from having several hundred migrations to just a few, and that’s where squashing comes in.
Squashing is the act of reducing an existing set of many migrations down to one (or sometimes a few) migrations which still represent the same changes.
Django does this by taking all of your existing migrations, extracting their Operations and putting them all in sequence, and then running an optimizer over them to try and reduce the length of the list - for example, it knows that CreateModel and DeleteModel cancel each other out, and it knows that AddField can be rolled into CreateModel.
Once the operation sequence has been reduced as much as possible - the amount possible depends on how closely intertwined your models are and if you have any RunSQL or RunPython operations (which can’t be optimized through unless they are marked as elidable) - Django will then write it back out into a new set of migration files.
These files are marked to say they replace the previously-squashed migrations, so they can coexist with the old migration files, and Django will intelligently switch between them depending where you are in the history. If you’re still part-way through the set of migrations that you squashed, it will keep using them until it hits the end and then switch to the squashed history, while new installs will use the new squashed migration and skip all the old ones.
This enables you to squash and not mess up systems currently in production that aren’t fully up-to-date yet. The recommended process is to squash, keeping the old files, commit and release, wait until all systems are upgraded with the new release (or if you’re a third-party project, ensure your users upgrade releases in order without skipping any), and then remove the old files, commit and do a second release.
The command that backs all this is squashmigrations - pass it the app label and migration name you want to squash up to, and it’ll get to work:
Use the squashmigrations --squashed-name option if you want to set the name of the squashed migration rather than use an autogenerated one.
Note that model interdependencies in Django can get very complex, and squashing may result in migrations that do not run; either mis-optimized (in which case you can try again with --no-optimize, though you should also report an issue), or with a CircularDependencyError, in which case you can manually resolve it.
To manually resolve a CircularDependencyError, break out one of the ForeignKeys in the circular dependency loop into a separate migration, and move the dependency on the other app with it. If you’re unsure, see how makemigrations deals with the problem when asked to create brand new migrations from your models. In a future release of Django, squashmigrations will be updated to attempt to resolve these errors itself.
Once you’ve squashed your migration, you should then commit it alongside the migrations it replaces and distribute this change to all running instances of your application, making sure that they run migrate to store the change in their database.
You must then transition the squashed migration to a normal migration by:
Note
Once you’ve squashed a migration, you should not then re-squash that squashed migration until you have fully transitioned it to a normal migration.
Migrations are Python files containing the old definitions of your models - thus, to write them, Django must take the current state of your models and serialize them out into a file.
While Django can serialize most things, there are some things that we just can’t serialize out into a valid Python representation - there’s no Python standard for how a value can be turned back into code (repr() only works for basic values, and doesn’t specify import paths).
Django can serialize the following:
Serialization support for pure and concrete path objects from pathlib, and os.PathLike instances was added.
Django cannot serialize:
You can serialize other types by writing a custom serializer. For example, if Django didn’t serialize Decimal by default, you could do this:
The first argument of MigrationWriter.register_serializer() is a type or iterable of types that should use the serializer.
The serialize() method of your serializer must return a string of how the value should appear in migrations and a set of any imports that are needed in the migration.
You can let Django serialize your own custom class instances by giving the class a deconstruct() method. It takes no arguments, and should return a tuple of three things (path, args, kwargs):
Note
This return value is different from the deconstruct() method for custom fields which returns a tuple of four items.
Django will write out the value as an instantiation of your class with the given arguments, similar to the way it writes out references to Django fields.
To prevent a new migration from being created each time makemigrations is run, you should also add a __eq__() method to the decorated class. This function will be called by Django’s migration framework to detect changes between states.
As long as all of the arguments to your class’ constructor are themselves serializable, you can use the @deconstructible class decorator from django.utils.deconstruct to add the deconstruct() method:
The decorator adds logic to capture and preserve the arguments on their way into your constructor, and then returns those arguments exactly when deconstruct() is called.
If you are the maintainer of a third-party app with models, you may need to ship migrations that support multiple Django versions. In this case, you should always run makemigrations with the lowest Django version you wish to support.
The migrations system will maintain backwards-compatibility according to the same policy as the rest of Django, so migration files generated on Django X.Y should run unchanged on Django X.Y+1. The migrations system does not promise forwards-compatibility, however. New features may be added, and migration files generated with newer versions of Django may not work on older versions.
See also


Model API reference. For introductory material, see Models.