doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
pgettext(context, message) Translates message given the context and returns it as a string. For more information, see Contextual markers.
django.ref.utils#django.utils.translation.pgettext
pgettext_lazy(context, message) Same as the non-lazy versions above, but using lazy execution. See lazy translations documentation.
django.ref.utils#django.utils.translation.pgettext_lazy
templatize(src) Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
django.ref.utils#django.utils.translation.templatize
to_locale(language) Turns a language name (en-us) into a locale name (en_US).
django.ref.utils#django.utils.translation.to_locale
Validators These validators are available from the django.contrib.postgres.validators module. KeysValidator class KeysValidator(keys, strict=False, messages=None) Validates that the given keys are contained in the value. If strict is True, then it also checks that there are no other keys present. The messages passed should be a dict containing the keys missing_keys and/or extra_keys. Note Note that this checks only for the existence of a given key, not that the value of a key is non-empty. Range validators RangeMaxValueValidator class RangeMaxValueValidator(limit_value, message=None) Validates that the upper bound of the range is not greater than limit_value. RangeMinValueValidator class RangeMinValueValidator(limit_value, message=None) Validates that the lower bound of the range is not less than the limit_value.
django.ref.contrib.postgres.validators
Validators Writing validators A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet some criteria. Validators can be useful for re-using validation logic between different types of fields. For example, here’s a validator that only allows even numbers: from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, ) You can add this to a model field via the field’s validators argument: from django.db import models class MyModel(models.Model): even_field = models.IntegerField(validators=[validate_even]) Because values are converted to Python before validators are run, you can even use the same validator with forms: from django import forms class MyForm(forms.Form): even_field = forms.IntegerField(validators=[validate_even]) You can also use a class with a __call__() method for more complex or configurable validators. RegexValidator, for example, uses this technique. If a class-based validator is used in the validators model field option, you should make sure it is serializable by the migration framework by adding deconstruct() and __eq__() methods. How validators are run See the form validation for more information on how validators are run in forms, and Validating objects for how they’re run in models. Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form. See the ModelForm documentation for information on how model validation interacts with forms. Built-in validators The django.core.validators module contains a collection of callable validators for use with model and form fields. They’re used internally but are available for use with your own fields, too. They can be used in addition to, or in lieu of custom field.clean() methods. RegexValidator class RegexValidator(regex=None, message=None, code=None, inverse_match=None, flags=0) Parameters: regex – If not None, overrides regex. Can be a regular expression string or a pre-compiled regular expression. message – If not None, overrides message. code – If not None, overrides code. inverse_match – If not None, overrides inverse_match. flags – If not None, overrides flags. In that case, regex must be a regular expression string, or TypeError is raised. A RegexValidator searches the provided value for a given regular expression with re.search(). By default, raises a ValidationError with message and code if a match is not found. Its behavior can be inverted by setting inverse_match to True, in which case the ValidationError is raised when a match is found. regex The regular expression pattern to search for within the provided value, using re.search(). This may be a string or a pre-compiled regular expression created with re.compile(). Defaults to the empty string, which will be found in every possible value. message The error message used by ValidationError if validation fails. Defaults to "Enter a valid value". code The error code used by ValidationError if validation fails. Defaults to "invalid". inverse_match The match mode for regex. Defaults to False. flags The regex flags used when compiling the regular expression string regex. If regex is a pre-compiled regular expression, and flags is overridden, TypeError is raised. Defaults to 0. EmailValidator class EmailValidator(message=None, code=None, allowlist=None) Parameters: message – If not None, overrides message. code – If not None, overrides code. allowlist – If not None, overrides allowlist. message The error message used by ValidationError if validation fails. Defaults to "Enter a valid email address". code The error code used by ValidationError if validation fails. Defaults to "invalid". allowlist Allowlist of email domains. By default, a regular expression (the domain_regex attribute) is used to validate whatever appears after the @ sign. However, if that string appears in the allowlist, this validation is bypassed. If not provided, the default allowlist is ['localhost']. Other domains that don’t contain a dot won’t pass validation, so you’d need to add them to the allowlist as necessary. Deprecated since version 3.2: The whitelist parameter is deprecated. Use allowlist instead. The undocumented domain_whitelist attribute is deprecated. Use domain_allowlist instead. URLValidator class URLValidator(schemes=None, regex=None, message=None, code=None) A RegexValidator subclass that ensures a value looks like a URL, and raises an error code of 'invalid' if it doesn’t. Loopback addresses and reserved IP spaces are considered valid. Literal IPv6 addresses (RFC 3986#section-3.2.2) and Unicode domains are both supported. In addition to the optional arguments of its parent RegexValidator class, URLValidator accepts an extra optional attribute: schemes URL/URI scheme list to validate against. If not provided, the default list is ['http', 'https', 'ftp', 'ftps']. As a reference, the IANA website provides a full list of valid URI schemes. validate_email validate_email An EmailValidator instance without any customizations. validate_slug validate_slug A RegexValidator instance that ensures a value consists of only letters, numbers, underscores or hyphens. validate_unicode_slug validate_unicode_slug A RegexValidator instance that ensures a value consists of only Unicode letters, numbers, underscores, or hyphens. validate_ipv4_address validate_ipv4_address A RegexValidator instance that ensures a value looks like an IPv4 address. validate_ipv6_address validate_ipv6_address Uses django.utils.ipv6 to check the validity of an IPv6 address. validate_ipv46_address validate_ipv46_address Uses both validate_ipv4_address and validate_ipv6_address to ensure a value is either a valid IPv4 or IPv6 address. validate_comma_separated_integer_list validate_comma_separated_integer_list A RegexValidator instance that ensures a value is a comma-separated list of integers. int_list_validator int_list_validator(sep=', ', message=None, code='invalid', allow_negative=False) Returns a RegexValidator instance that ensures a string consists of integers separated by sep. It allows negative integers when allow_negative is True. MaxValueValidator class MaxValueValidator(limit_value, message=None) Raises a ValidationError with a code of 'max_value' if value is greater than limit_value, which may be a callable. MinValueValidator class MinValueValidator(limit_value, message=None) Raises a ValidationError with a code of 'min_value' if value is less than limit_value, which may be a callable. MaxLengthValidator class MaxLengthValidator(limit_value, message=None) Raises a ValidationError with a code of 'max_length' if the length of value is greater than limit_value, which may be a callable. MinLengthValidator class MinLengthValidator(limit_value, message=None) Raises a ValidationError with a code of 'min_length' if the length of value is less than limit_value, which may be a callable. DecimalValidator class DecimalValidator(max_digits, decimal_places) Raises ValidationError with the following codes: 'max_digits' if the number of digits is larger than max_digits. 'max_decimal_places' if the number of decimals is larger than decimal_places. 'max_whole_digits' if the number of whole digits is larger than the difference between max_digits and decimal_places. FileExtensionValidator class FileExtensionValidator(allowed_extensions, message, code) Raises a ValidationError with a code of 'invalid_extension' if the extension of value.name (value is a File) isn’t found in allowed_extensions. The extension is compared case-insensitively with allowed_extensions. Warning Don’t rely on validation of the file extension to determine a file’s type. Files can be renamed to have any extension no matter what data they contain. validate_image_file_extension validate_image_file_extension Uses Pillow to ensure that value.name (value is a File) has a valid image extension. ProhibitNullCharactersValidator class ProhibitNullCharactersValidator(message=None, code=None) Raises a ValidationError if str(value) contains one or more nulls characters ('\x00'). Parameters: message – If not None, overrides message. code – If not None, overrides code. message The error message used by ValidationError if validation fails. Defaults to "Null characters are not allowed.". code The error code used by ValidationError if validation fails. Defaults to "null_characters_not_allowed".
django.ref.validators
class ExceptionReporter html_template_path New in Django 3.2. Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the HTML representation of the exception. Defaults to the Django provided template. text_template_path New in Django 3.2. Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the plain-text representation of the exception. Defaults to the Django provided template. get_traceback_data() Return a dictionary containing traceback information. This is the main extension point for customizing exception reports, for example: from django.views.debug import ExceptionReporter class CustomExceptionReporter(ExceptionReporter): def get_traceback_data(self): data = super().get_traceback_data() # ... remove/add something here ... return data get_traceback_html() Return HTML version of exception report. Used for HTML version of debug 500 HTTP error page. get_traceback_text() Return plain text version of exception report. Used for plain text version of debug 500 HTTP error page and email reports.
django.howto.error-reporting#django.views.debug.ExceptionReporter
get_traceback_data() Return a dictionary containing traceback information. This is the main extension point for customizing exception reports, for example: from django.views.debug import ExceptionReporter class CustomExceptionReporter(ExceptionReporter): def get_traceback_data(self): data = super().get_traceback_data() # ... remove/add something here ... return data
django.howto.error-reporting#django.views.debug.ExceptionReporter.get_traceback_data
get_traceback_html() Return HTML version of exception report. Used for HTML version of debug 500 HTTP error page.
django.howto.error-reporting#django.views.debug.ExceptionReporter.get_traceback_html
get_traceback_text() Return plain text version of exception report. Used for plain text version of debug 500 HTTP error page and email reports.
django.howto.error-reporting#django.views.debug.ExceptionReporter.get_traceback_text
html_template_path New in Django 3.2. Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the HTML representation of the exception. Defaults to the Django provided template.
django.howto.error-reporting#django.views.debug.ExceptionReporter.html_template_path
text_template_path New in Django 3.2. Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the plain-text representation of the exception. Defaults to the Django provided template.
django.howto.error-reporting#django.views.debug.ExceptionReporter.text_template_path
class SafeExceptionReporterFilter cleansed_substitute The string value to replace sensitive value with. By default it replaces the values of sensitive variables with stars (**********). hidden_settings A compiled regular expression object used to match settings and request.META values considered as sensitive. By default equivalent to: import re re.compile(r'API|TOKEN|KEY|SECRET|PASS|SIGNATURE', flags=re.IGNORECASE) is_active(request) Returns True to activate the filtering in get_post_parameters() and get_traceback_frame_variables(). By default the filter is active if DEBUG is False. Note that sensitive request.META values are always filtered along with sensitive setting values, as described in the DEBUG documentation. get_post_parameters(request) Returns the filtered dictionary of POST parameters. Sensitive values are replaced with cleansed_substitute. get_traceback_frame_variables(request, tb_frame) Returns the filtered dictionary of local variables for the given traceback frame. Sensitive values are replaced with cleansed_substitute.
django.howto.error-reporting#django.views.debug.SafeExceptionReporterFilter
cleansed_substitute The string value to replace sensitive value with. By default it replaces the values of sensitive variables with stars (**********).
django.howto.error-reporting#django.views.debug.SafeExceptionReporterFilter.cleansed_substitute
get_post_parameters(request) Returns the filtered dictionary of POST parameters. Sensitive values are replaced with cleansed_substitute.
django.howto.error-reporting#django.views.debug.SafeExceptionReporterFilter.get_post_parameters
get_traceback_frame_variables(request, tb_frame) Returns the filtered dictionary of local variables for the given traceback frame. Sensitive values are replaced with cleansed_substitute.
django.howto.error-reporting#django.views.debug.SafeExceptionReporterFilter.get_traceback_frame_variables
hidden_settings A compiled regular expression object used to match settings and request.META values considered as sensitive. By default equivalent to: import re re.compile(r'API|TOKEN|KEY|SECRET|PASS|SIGNATURE', flags=re.IGNORECASE)
django.howto.error-reporting#django.views.debug.SafeExceptionReporterFilter.hidden_settings
is_active(request) Returns True to activate the filtering in get_post_parameters() and get_traceback_frame_variables(). By default the filter is active if DEBUG is False. Note that sensitive request.META values are always filtered along with sensitive setting values, as described in the DEBUG documentation.
django.howto.error-reporting#django.views.debug.SafeExceptionReporterFilter.is_active
cache_control(**kwargs) This decorator patches the response’s Cache-Control header by adding all of the keyword arguments to it. See patch_cache_control() for the details of the transformation.
django.topics.http.decorators#django.views.decorators.cache.cache_control
django.views.decorators.cache.cache_page()
django.topics.cache#django.views.decorators.cache.cache_page
never_cache(view_func) This decorator adds a Cache-Control: max-age=0, no-cache, no-store, must-revalidate, private header to a response to indicate that a page should never be cached.
django.topics.http.decorators#django.views.decorators.cache.never_cache
no_append_slash() This decorator allows individual views to be excluded from APPEND_SLASH URL normalization.
django.topics.http.decorators#django.views.decorators.common.no_append_slash
csrf_exempt(view) This decorator marks a view as being exempt from the protection ensured by the middleware. Example: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_view(request): return HttpResponse('Hello world')
django.ref.csrf#django.views.decorators.csrf.csrf_exempt
csrf_protect(view) Decorator that provides the protection of CsrfViewMiddleware to a view. Usage: from django.shortcuts import render from django.views.decorators.csrf import csrf_protect @csrf_protect def my_view(request): c = {} # ... return render(request, "a_template.html", c) If you are using class-based views, you can refer to Decorating class-based views.
django.ref.csrf#django.views.decorators.csrf.csrf_protect
ensure_csrf_cookie(view) This decorator forces a view to send the CSRF cookie.
django.ref.csrf#django.views.decorators.csrf.ensure_csrf_cookie
requires_csrf_token(view) Normally the csrf_token template tag will not work if CsrfViewMiddleware.process_view or an equivalent like csrf_protect has not run. The view decorator requires_csrf_token can be used to ensure the template tag does work. This decorator works similarly to csrf_protect, but never rejects an incoming request. Example: from django.shortcuts import render from django.views.decorators.csrf import requires_csrf_token @requires_csrf_token def my_view(request): c = {} # ... return render(request, "a_template.html", c)
django.ref.csrf#django.views.decorators.csrf.requires_csrf_token
sensitive_post_parameters(*parameters) If one of your views receives an HttpRequest object with POST parameters susceptible to contain sensitive information, you may prevent the values of those parameters from being included in the error reports using the sensitive_post_parameters decorator: from django.views.decorators.debug import sensitive_post_parameters @sensitive_post_parameters('pass_word', 'credit_card_number') def record_user_profile(request): UserProfile.create( user=request.user, password=request.POST['pass_word'], credit_card=request.POST['credit_card_number'], name=request.POST['name'], ) ... In the above example, the values for the pass_word and credit_card_number POST parameters will be hidden and replaced with stars (**********) in the request’s representation inside the error reports, whereas the value of the name parameter will be disclosed. To systematically hide all POST parameters of a request in error reports, do not provide any argument to the sensitive_post_parameters decorator: @sensitive_post_parameters() def my_view(request): ... All POST parameters are systematically filtered out of error reports for certain django.contrib.auth.views views (login, password_reset_confirm, password_change, and add_view and user_change_password in the auth admin) to prevent the leaking of sensitive information such as user passwords.
django.howto.error-reporting#django.views.decorators.debug.sensitive_post_parameters
sensitive_variables(*variables) If a function (either a view or any regular callback) in your code uses local variables susceptible to contain sensitive information, you may prevent the values of those variables from being included in error reports using the sensitive_variables decorator: from django.views.decorators.debug import sensitive_variables @sensitive_variables('user', 'pw', 'cc') def process_info(user): pw = user.pass_word cc = user.credit_card_number name = user.name ... In the above example, the values for the user, pw and cc variables will be hidden and replaced with stars (**********) in the error reports, whereas the value of the name variable will be disclosed. To systematically hide all local variables of a function from error logs, do not provide any argument to the sensitive_variables decorator: @sensitive_variables() def my_function(): ... When using multiple decorators If the variable you want to hide is also a function argument (e.g. ‘user’ in the following example), and if the decorated function has multiple decorators, then make sure to place @sensitive_variables at the top of the decorator chain. This way it will also hide the function argument as it gets passed through the other decorators: @sensitive_variables('user', 'pw', 'cc') @some_decorator @another_decorator def process_info(user): ...
django.howto.error-reporting#django.views.decorators.debug.sensitive_variables
gzip_page() This decorator compresses content if the browser allows gzip compression. It sets the Vary header accordingly, so that caches will base their storage on the Accept-Encoding header.
django.topics.http.decorators#django.views.decorators.gzip.gzip_page
condition(etag_func=None, last_modified_func=None)
django.topics.http.decorators#django.views.decorators.http.condition
etag(etag_func)
django.topics.http.decorators#django.views.decorators.http.etag
last_modified(last_modified_func) These decorators can be used to generate ETag and Last-Modified headers; see conditional view processing.
django.topics.http.decorators#django.views.decorators.http.last_modified
require_GET() Decorator to require that a view only accepts the GET method.
django.topics.http.decorators#django.views.decorators.http.require_GET
require_http_methods(request_method_list) Decorator to require that a view only accepts particular request methods. Usage: from django.views.decorators.http import require_http_methods @require_http_methods(["GET", "POST"]) def my_view(request): # I can assume now that only GET or POST requests make it this far # ... pass Note that request methods should be in uppercase.
django.topics.http.decorators#django.views.decorators.http.require_http_methods
require_POST() Decorator to require that a view only accepts the POST method.
django.topics.http.decorators#django.views.decorators.http.require_POST
require_safe() Decorator to require that a view only accepts the GET and HEAD methods. These methods are commonly considered “safe” because they should not have the significance of taking an action other than retrieving the requested resource. Note Web servers should automatically strip the content of responses to HEAD requests while leaving the headers unchanged, so you may handle HEAD requests exactly like GET requests in your views. Since some software, such as link checkers, rely on HEAD requests, you might prefer using require_safe instead of require_GET.
django.topics.http.decorators#django.views.decorators.http.require_safe
vary_on_cookie(func)
django.topics.http.decorators#django.views.decorators.vary.vary_on_cookie
vary_on_headers(*headers) The Vary header defines which request headers a cache mechanism should take into account when building its cache key. See using vary headers.
django.topics.http.decorators#django.views.decorators.vary.vary_on_headers
defaults.bad_request(request, exception, template_name='400.html')
django.ref.views#django.views.defaults.bad_request
defaults.page_not_found(request, exception, template_name='404.html')
django.ref.views#django.views.defaults.page_not_found
defaults.permission_denied(request, exception, template_name='403.html')
django.ref.views#django.views.defaults.permission_denied
defaults.server_error(request, template_name='500.html')
django.ref.views#django.views.defaults.server_error
class django.views.generic.base.ContextMixin Attributes extra_context A dictionary to include in the context. This is a convenient way of specifying some context in as_view(). Example usage: from django.views.generic import TemplateView TemplateView.as_view(extra_context={'title': 'Custom Title'}) Methods get_context_data(**kwargs) Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. Example usage: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['number'] = random.randrange(1, 100) return context The template context of all class-based generic views include a view variable that points to the View instance. Use alters_data where appropriate Note that having the view instance in the template context may expose potentially hazardous methods to template authors. To prevent methods like this from being called in the template, set alters_data=True on those methods. For more information, read the documentation on rendering a template context.
django.ref.class-based-views.mixins-simple#django.views.generic.base.ContextMixin
extra_context A dictionary to include in the context. This is a convenient way of specifying some context in as_view(). Example usage: from django.views.generic import TemplateView TemplateView.as_view(extra_context={'title': 'Custom Title'})
django.ref.class-based-views.mixins-simple#django.views.generic.base.ContextMixin.extra_context
get_context_data(**kwargs) Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. Example usage: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['number'] = random.randrange(1, 100) return context The template context of all class-based generic views include a view variable that points to the View instance. Use alters_data where appropriate Note that having the view instance in the template context may expose potentially hazardous methods to template authors. To prevent methods like this from being called in the template, set alters_data=True on those methods. For more information, read the documentation on rendering a template context.
django.ref.class-based-views.mixins-simple#django.views.generic.base.ContextMixin.get_context_data
class django.views.generic.base.RedirectView Redirects to a given URL. The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output. If the given URL is None, Django will return an HttpResponseGone (410). Ancestors (MRO) This view inherits methods and attributes from the following view: django.views.generic.base.View Method Flowchart setup() dispatch() http_method_not_allowed() get_redirect_url() Example views.py: from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from articles.models import Article class ArticleCounterRedirectView(RedirectView): permanent = False query_string = True pattern_name = 'article-detail' def get_redirect_url(self, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs['pk']) article.update_counter() return super().get_redirect_url(*args, **kwargs) Example urls.py: from django.urls import path from django.views.generic.base import RedirectView from article.views import ArticleCounterRedirectView, ArticleDetailView urlpatterns = [ path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'), path('details/<int:pk>/', ArticleDetailView.as_view(), name='article-detail'), path('go-to-django/', RedirectView.as_view(url='https://www.djangoproject.com/'), name='go-to-django'), ] Attributes url The URL to redirect to, as a string. Or None to raise a 410 (Gone) HTTP error. pattern_name The name of the URL pattern to redirect to. Reversing will be done using the same args and kwargs as are passed in for this view. permanent Whether the redirect should be permanent. The only difference here is the HTTP status code returned. If True, then the redirect will use status code 301. If False, then the redirect will use status code 302. By default, permanent is False. query_string Whether to pass along the GET query string to the new location. If True, then the query string is appended to the URL. If False, then the query string is discarded. By default, query_string is False. Methods get_redirect_url(*args, **kwargs) Constructs the target URL for redirection. The args and kwargs arguments are positional and/or keyword arguments captured from the URL pattern, respectively. The default implementation uses url as a starting string and performs expansion of % named parameters in that string using the named groups captured in the URL. If url is not set, get_redirect_url() tries to reverse the pattern_name using what was captured in the URL (both named and unnamed groups are used). If requested by query_string, it will also append the query string to the generated URL. Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.
django.ref.class-based-views.base#django.views.generic.base.RedirectView
get_redirect_url(*args, **kwargs) Constructs the target URL for redirection. The args and kwargs arguments are positional and/or keyword arguments captured from the URL pattern, respectively. The default implementation uses url as a starting string and performs expansion of % named parameters in that string using the named groups captured in the URL. If url is not set, get_redirect_url() tries to reverse the pattern_name using what was captured in the URL (both named and unnamed groups are used). If requested by query_string, it will also append the query string to the generated URL. Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.
django.ref.class-based-views.base#django.views.generic.base.RedirectView.get_redirect_url
pattern_name The name of the URL pattern to redirect to. Reversing will be done using the same args and kwargs as are passed in for this view.
django.ref.class-based-views.base#django.views.generic.base.RedirectView.pattern_name
permanent Whether the redirect should be permanent. The only difference here is the HTTP status code returned. If True, then the redirect will use status code 301. If False, then the redirect will use status code 302. By default, permanent is False.
django.ref.class-based-views.base#django.views.generic.base.RedirectView.permanent
query_string Whether to pass along the GET query string to the new location. If True, then the query string is appended to the URL. If False, then the query string is discarded. By default, query_string is False.
django.ref.class-based-views.base#django.views.generic.base.RedirectView.query_string
url The URL to redirect to, as a string. Or None to raise a 410 (Gone) HTTP error.
django.ref.class-based-views.base#django.views.generic.base.RedirectView.url
class django.views.generic.base.TemplateResponseMixin Provides a mechanism to construct a TemplateResponse, given suitable context. The template to use is configurable and can be further customized by subclasses. Attributes template_name The full name of a template to use as defined by a string. Not defining a template_name will raise a django.core.exceptions.ImproperlyConfigured exception. template_engine The NAME of a template engine to use for loading the template. template_engine is passed as the using keyword argument to response_class. Default is None, which tells Django to search for the template in all configured engines. response_class The response class to be returned by render_to_response method. Default is TemplateResponse. The template and context of TemplateResponse instances can be altered later (e.g. in template response middleware). If you need custom template loading or custom context object instantiation, create a TemplateResponse subclass and assign it to response_class. content_type The content type to use for the response. content_type is passed as a keyword argument to response_class. Default is None – meaning that Django uses 'text/html'. Methods render_to_response(context, **response_kwargs) Returns a self.response_class instance. If any keyword arguments are provided, they will be passed to the constructor of the response class. Calls get_template_names() to obtain the list of template names that will be searched looking for an existent template. get_template_names() Returns a list of template names to search for when rendering the template. The first template that is found will be used. The default implementation will return a list containing template_name (if it is specified).
django.ref.class-based-views.mixins-simple#django.views.generic.base.TemplateResponseMixin
content_type The content type to use for the response. content_type is passed as a keyword argument to response_class. Default is None – meaning that Django uses 'text/html'.
django.ref.class-based-views.mixins-simple#django.views.generic.base.TemplateResponseMixin.content_type
get_template_names() Returns a list of template names to search for when rendering the template. The first template that is found will be used. The default implementation will return a list containing template_name (if it is specified).
django.ref.class-based-views.mixins-simple#django.views.generic.base.TemplateResponseMixin.get_template_names
render_to_response(context, **response_kwargs) Returns a self.response_class instance. If any keyword arguments are provided, they will be passed to the constructor of the response class. Calls get_template_names() to obtain the list of template names that will be searched looking for an existent template.
django.ref.class-based-views.mixins-simple#django.views.generic.base.TemplateResponseMixin.render_to_response
response_class The response class to be returned by render_to_response method. Default is TemplateResponse. The template and context of TemplateResponse instances can be altered later (e.g. in template response middleware). If you need custom template loading or custom context object instantiation, create a TemplateResponse subclass and assign it to response_class.
django.ref.class-based-views.mixins-simple#django.views.generic.base.TemplateResponseMixin.response_class
template_engine The NAME of a template engine to use for loading the template. template_engine is passed as the using keyword argument to response_class. Default is None, which tells Django to search for the template in all configured engines.
django.ref.class-based-views.mixins-simple#django.views.generic.base.TemplateResponseMixin.template_engine
template_name The full name of a template to use as defined by a string. Not defining a template_name will raise a django.core.exceptions.ImproperlyConfigured exception.
django.ref.class-based-views.mixins-simple#django.views.generic.base.TemplateResponseMixin.template_name
class django.views.generic.base.TemplateView Renders a given template, with the context containing parameters captured in the URL. Ancestors (MRO) This view inherits methods and attributes from the following views: django.views.generic.base.TemplateResponseMixin django.views.generic.base.ContextMixin django.views.generic.base.View Method Flowchart setup() dispatch() http_method_not_allowed() get_context_data() Example views.py: from django.views.generic.base import TemplateView from articles.models import Article class HomePageView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['latest_articles'] = Article.objects.all()[:5] return context Example urls.py: from django.urls import path from myapp.views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] Context Populated (through ContextMixin) with the keyword arguments captured from the URL pattern that served the view. You can also add context using the extra_context keyword argument for as_view().
django.ref.class-based-views.base#django.views.generic.base.TemplateView
class django.views.generic.base.View The master class-based base view. All other class-based views inherit from this base class. It isn’t strictly a generic view and thus can also be imported from django.views. Method Flowchart setup() dispatch() http_method_not_allowed() options() Example views.py: from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request, *args, **kwargs): return HttpResponse('Hello, World!') Example urls.py: from django.urls import path from myapp.views import MyView urlpatterns = [ path('mine/', MyView.as_view(), name='my-view'), ] Attributes http_method_names The list of HTTP method names that this view will accept. Default: ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] Methods classmethod as_view(**initkwargs) Returns a callable view that takes a request and returns a response: response = MyView.as_view()(request) The returned view has view_class and view_initkwargs attributes. When the view is called during the request/response cycle, the setup() method assigns the HttpRequest to the view’s request attribute, and any positional and/or keyword arguments captured from the URL pattern to the args and kwargs attributes, respectively. Then dispatch() is called. setup(request, *args, **kwargs) Performs key view initialization prior to dispatch(). If overriding this method, you must call super(). dispatch(request, *args, **kwargs) The view part of the view – the method that accepts a request argument plus arguments, and returns an HTTP response. The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on. By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example. http_method_not_allowed(request, *args, **kwargs) If the view was called with an HTTP method it doesn’t support, this method is called instead. The default implementation returns HttpResponseNotAllowed with a list of allowed methods in plain text. options(request, *args, **kwargs) Handles responding to requests for the OPTIONS HTTP verb. Returns a response with the Allow header containing a list of the view’s allowed HTTP method names.
django.ref.class-based-views.base#django.views.generic.base.View
dispatch(request, *args, **kwargs) The view part of the view – the method that accepts a request argument plus arguments, and returns an HTTP response. The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on. By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example.
django.ref.class-based-views.base#django.views.generic.base.View.dispatch
http_method_names The list of HTTP method names that this view will accept. Default: ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
django.ref.class-based-views.base#django.views.generic.base.View.http_method_names
http_method_not_allowed(request, *args, **kwargs) If the view was called with an HTTP method it doesn’t support, this method is called instead. The default implementation returns HttpResponseNotAllowed with a list of allowed methods in plain text.
django.ref.class-based-views.base#django.views.generic.base.View.http_method_not_allowed
options(request, *args, **kwargs) Handles responding to requests for the OPTIONS HTTP verb. Returns a response with the Allow header containing a list of the view’s allowed HTTP method names.
django.ref.class-based-views.base#django.views.generic.base.View.options
setup(request, *args, **kwargs) Performs key view initialization prior to dispatch(). If overriding this method, you must call super().
django.ref.class-based-views.base#django.views.generic.base.View.setup
class ArchiveIndexView A top-level index page showing the “latest” objects, by date. Objects with a date in the future are not included unless you set allow_future to True. Ancestors (MRO) django.views.generic.list.MultipleObjectTemplateResponseMixin django.views.generic.base.TemplateResponseMixin django.views.generic.dates.BaseArchiveIndexView django.views.generic.dates.BaseDateListView django.views.generic.list.MultipleObjectMixin django.views.generic.dates.DateMixin django.views.generic.base.View Context In addition to the context provided by django.views.generic.list.MultipleObjectMixin (via django.views.generic.dates.BaseDateListView), the template’s context will be: date_list: A QuerySet object containing all years that have objects available according to queryset, represented as datetime.datetime objects, in descending order. Notes Uses a default context_object_name of latest. Uses a default template_name_suffix of _archive. Defaults to providing date_list by year, but this can be altered to month or day using the attribute date_list_period. This also applies to all subclass views. Example myapp/urls.py: from django.urls import path from django.views.generic.dates import ArchiveIndexView from myapp.models import Article urlpatterns = [ path('archive/', ArchiveIndexView.as_view(model=Article, date_field="pub_date"), name="article_archive"), ] Example myapp/article_archive.html: <ul> {% for article in latest %} <li>{{ article.pub_date }}: {{ article.title }}</li> {% endfor %} </ul> This will output all articles.
django.ref.class-based-views.generic-date-based#django.views.generic.dates.ArchiveIndexView
class BaseArchiveIndexView
django.ref.class-based-views.generic-date-based#django.views.generic.dates.BaseArchiveIndexView
class BaseDateDetailView
django.ref.class-based-views.generic-date-based#django.views.generic.dates.BaseDateDetailView
class BaseDateListView A base class that provides common behavior for all date-based views. There won’t normally be a reason to instantiate BaseDateListView; instantiate one of the subclasses instead. While this view (and its subclasses) are executing, self.object_list will contain the list of objects that the view is operating upon, and self.date_list will contain the list of dates for which data is available. Mixins DateMixin MultipleObjectMixin Methods and Attributes allow_empty A boolean specifying whether to display the page if no objects are available. If this is True and no objects are available, the view will display an empty page instead of raising a 404. This is identical to django.views.generic.list.MultipleObjectMixin.allow_empty, except for the default value, which is False. date_list_period Optional A string defining the aggregation period for date_list. It must be one of 'year' (default), 'month', or 'day'. get_dated_items() Returns a 3-tuple containing (date_list, object_list, extra_context). date_list is the list of dates for which data is available. object_list is the list of objects. extra_context is a dictionary of context data that will be added to any context data provided by the MultipleObjectMixin. get_dated_queryset(**lookup) Returns a queryset, filtered using the query arguments defined by lookup. Enforces any restrictions on the queryset, such as allow_empty and allow_future. get_date_list_period() Returns the aggregation period for date_list. Returns date_list_period by default. get_date_list(queryset, date_type=None, ordering='ASC') Returns the list of dates of type date_type for which queryset contains entries. For example, get_date_list(qs, 'year') will return the list of years for which qs has entries. If date_type isn’t provided, the result of get_date_list_period() is used. date_type and ordering are passed to QuerySet.dates().
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.BaseDateListView
allow_empty A boolean specifying whether to display the page if no objects are available. If this is True and no objects are available, the view will display an empty page instead of raising a 404. This is identical to django.views.generic.list.MultipleObjectMixin.allow_empty, except for the default value, which is False.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.BaseDateListView.allow_empty
date_list_period Optional A string defining the aggregation period for date_list. It must be one of 'year' (default), 'month', or 'day'.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.BaseDateListView.date_list_period
get_date_list(queryset, date_type=None, ordering='ASC') Returns the list of dates of type date_type for which queryset contains entries. For example, get_date_list(qs, 'year') will return the list of years for which qs has entries. If date_type isn’t provided, the result of get_date_list_period() is used. date_type and ordering are passed to QuerySet.dates().
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.BaseDateListView.get_date_list
get_date_list_period() Returns the aggregation period for date_list. Returns date_list_period by default.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.BaseDateListView.get_date_list_period
get_dated_items() Returns a 3-tuple containing (date_list, object_list, extra_context). date_list is the list of dates for which data is available. object_list is the list of objects. extra_context is a dictionary of context data that will be added to any context data provided by the MultipleObjectMixin.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.BaseDateListView.get_dated_items
get_dated_queryset(**lookup) Returns a queryset, filtered using the query arguments defined by lookup. Enforces any restrictions on the queryset, such as allow_empty and allow_future.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.BaseDateListView.get_dated_queryset
class BaseDayArchiveView
django.ref.class-based-views.generic-date-based#django.views.generic.dates.BaseDayArchiveView
class BaseMonthArchiveView
django.ref.class-based-views.generic-date-based#django.views.generic.dates.BaseMonthArchiveView
class BaseTodayArchiveView
django.ref.class-based-views.generic-date-based#django.views.generic.dates.BaseTodayArchiveView
class BaseWeekArchiveView
django.ref.class-based-views.generic-date-based#django.views.generic.dates.BaseWeekArchiveView
class BaseYearArchiveView
django.ref.class-based-views.generic-date-based#django.views.generic.dates.BaseYearArchiveView
class DateDetailView A page representing an individual object. If the object has a date value in the future, the view will throw a 404 error by default, unless you set allow_future to True. Ancestors (MRO) django.views.generic.detail.SingleObjectTemplateResponseMixin django.views.generic.base.TemplateResponseMixin django.views.generic.dates.BaseDateDetailView django.views.generic.dates.YearMixin django.views.generic.dates.MonthMixin django.views.generic.dates.DayMixin django.views.generic.dates.DateMixin django.views.generic.detail.BaseDetailView django.views.generic.detail.SingleObjectMixin django.views.generic.base.View Context Includes the single object associated with the model specified in the DateDetailView. Notes Uses a default template_name_suffix of _detail. Example myapp/urls.py: from django.urls import path from django.views.generic.dates import DateDetailView urlpatterns = [ path('<int:year>/<str:month>/<int:day>/<int:pk>/', DateDetailView.as_view(model=Article, date_field="pub_date"), name="archive_date_detail"), ] Example myapp/article_detail.html: <h1>{{ object.title }}</h1>
django.ref.class-based-views.generic-date-based#django.views.generic.dates.DateDetailView
class DateMixin A mixin class providing common behavior for all date-based views. Methods and Attributes date_field The name of the DateField or DateTimeField in the QuerySet’s model that the date-based archive should use to determine the list of objects to display on the page. When time zone support is enabled and date_field is a DateTimeField, dates are assumed to be in the current time zone. Otherwise, the queryset could include objects from the previous or the next day in the end user’s time zone. Warning In this situation, if you have implemented per-user time zone selection, the same URL may show a different set of objects, depending on the end user’s time zone. To avoid this, you should use a DateField as the date_field attribute. allow_future A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. By default, this is False. get_date_field() Returns the name of the field that contains the date data that this view will operate on. Returns date_field by default. get_allow_future() Determine whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. Returns allow_future by default.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DateMixin
allow_future A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. By default, this is False.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DateMixin.allow_future
date_field The name of the DateField or DateTimeField in the QuerySet’s model that the date-based archive should use to determine the list of objects to display on the page. When time zone support is enabled and date_field is a DateTimeField, dates are assumed to be in the current time zone. Otherwise, the queryset could include objects from the previous or the next day in the end user’s time zone. Warning In this situation, if you have implemented per-user time zone selection, the same URL may show a different set of objects, depending on the end user’s time zone. To avoid this, you should use a DateField as the date_field attribute.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DateMixin.date_field
get_allow_future() Determine whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. Returns allow_future by default.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DateMixin.get_allow_future
get_date_field() Returns the name of the field that contains the date data that this view will operate on. Returns date_field by default.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DateMixin.get_date_field
class DayArchiveView A day archive page showing all objects in a given day. Days in the future throw a 404 error, regardless of whether any objects exist for future days, unless you set allow_future to True. Ancestors (MRO) django.views.generic.list.MultipleObjectTemplateResponseMixin django.views.generic.base.TemplateResponseMixin django.views.generic.dates.BaseDayArchiveView django.views.generic.dates.YearMixin django.views.generic.dates.MonthMixin django.views.generic.dates.DayMixin django.views.generic.dates.BaseDateListView django.views.generic.list.MultipleObjectMixin django.views.generic.dates.DateMixin django.views.generic.base.View Context In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be: day: A date object representing the given day. next_day: A date object representing the next day, according to allow_empty and allow_future. previous_day: A date object representing the previous day, according to allow_empty and allow_future. next_month: A date object representing the first day of the next month, according to allow_empty and allow_future. previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future. Notes Uses a default template_name_suffix of _archive_day. Example myapp/views.py: from django.views.generic.dates import DayArchiveView from myapp.models import Article class ArticleDayArchiveView(DayArchiveView): queryset = Article.objects.all() date_field = "pub_date" allow_future = True Example myapp/urls.py: from django.urls import path from myapp.views import ArticleDayArchiveView urlpatterns = [ # Example: /2012/nov/10/ path('<int:year>/<str:month>/<int:day>/', ArticleDayArchiveView.as_view(), name="archive_day"), ] Example myapp/article_archive_day.html: <h1>{{ day }}</h1> <ul> {% for article in object_list %} <li>{{ article.pub_date|date:"F j, Y" }}: {{ article.title }}</li> {% endfor %} </ul> <p> {% if previous_day %} Previous Day: {{ previous_day }} {% endif %} {% if previous_day and next_day %}--{% endif %} {% if next_day %} Next Day: {{ next_day }} {% endif %} </p>
django.ref.class-based-views.generic-date-based#django.views.generic.dates.DayArchiveView
class DayMixin A mixin that can be used to retrieve and provide parsing information for a day component of a date. Methods and Attributes day_format The strftime() format to use when parsing the day. By default, this is '%d'. day Optional The value for the day, as a string. By default, set to None, which means the day will be determined using other means. get_day_format() Returns the strftime() format to use when parsing the day. Returns day_format by default. get_day() Returns the day for which this view will display data, as a string. Tries the following sources, in order: The value of the DayMixin.day attribute. The value of the day argument captured in the URL pattern. The value of the day GET query argument. Raises a 404 if no valid day specification can be found. get_next_day(date) Returns a date object containing the next valid day after the date provided. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future. get_previous_day(date) Returns a date object containing the previous valid day. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DayMixin
day Optional The value for the day, as a string. By default, set to None, which means the day will be determined using other means.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DayMixin.day
day_format The strftime() format to use when parsing the day. By default, this is '%d'.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DayMixin.day_format
get_day() Returns the day for which this view will display data, as a string. Tries the following sources, in order: The value of the DayMixin.day attribute. The value of the day argument captured in the URL pattern. The value of the day GET query argument. Raises a 404 if no valid day specification can be found.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DayMixin.get_day
get_day_format() Returns the strftime() format to use when parsing the day. Returns day_format by default.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DayMixin.get_day_format
get_next_day(date) Returns a date object containing the next valid day after the date provided. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DayMixin.get_next_day
get_previous_day(date) Returns a date object containing the previous valid day. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.DayMixin.get_previous_day
class MonthArchiveView A monthly archive page showing all objects in a given month. Objects with a date in the future are not displayed unless you set allow_future to True. Ancestors (MRO) django.views.generic.list.MultipleObjectTemplateResponseMixin django.views.generic.base.TemplateResponseMixin django.views.generic.dates.BaseMonthArchiveView django.views.generic.dates.YearMixin django.views.generic.dates.MonthMixin django.views.generic.dates.BaseDateListView django.views.generic.list.MultipleObjectMixin django.views.generic.dates.DateMixin django.views.generic.base.View Context In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be: date_list: A QuerySet object containing all days that have objects available in the given month, according to queryset, represented as datetime.datetime objects, in ascending order. month: A date object representing the given month. next_month: A date object representing the first day of the next month, according to allow_empty and allow_future. previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future. Notes Uses a default template_name_suffix of _archive_month. Example myapp/views.py: from django.views.generic.dates import MonthArchiveView from myapp.models import Article class ArticleMonthArchiveView(MonthArchiveView): queryset = Article.objects.all() date_field = "pub_date" allow_future = True Example myapp/urls.py: from django.urls import path from myapp.views import ArticleMonthArchiveView urlpatterns = [ # Example: /2012/08/ path('<int:year>/<int:month>/', ArticleMonthArchiveView.as_view(month_format='%m'), name="archive_month_numeric"), # Example: /2012/aug/ path('<int:year>/<str:month>/', ArticleMonthArchiveView.as_view(), name="archive_month"), ] Example myapp/article_archive_month.html: <ul> {% for article in object_list %} <li>{{ article.pub_date|date:"F j, Y" }}: {{ article.title }}</li> {% endfor %} </ul> <p> {% if previous_month %} Previous Month: {{ previous_month|date:"F Y" }} {% endif %} {% if next_month %} Next Month: {{ next_month|date:"F Y" }} {% endif %} </p>
django.ref.class-based-views.generic-date-based#django.views.generic.dates.MonthArchiveView
class MonthMixin A mixin that can be used to retrieve and provide parsing information for a month component of a date. Methods and Attributes month_format The strftime() format to use when parsing the month. By default, this is '%b'. month Optional The value for the month, as a string. By default, set to None, which means the month will be determined using other means. get_month_format() Returns the strftime() format to use when parsing the month. Returns month_format by default. get_month() Returns the month for which this view will display data, as a string. Tries the following sources, in order: The value of the MonthMixin.month attribute. The value of the month argument captured in the URL pattern. The value of the month GET query argument. Raises a 404 if no valid month specification can be found. get_next_month(date) Returns a date object containing the first day of the month after the date provided. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future. get_previous_month(date) Returns a date object containing the first day of the month before the date provided. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.MonthMixin
get_month() Returns the month for which this view will display data, as a string. Tries the following sources, in order: The value of the MonthMixin.month attribute. The value of the month argument captured in the URL pattern. The value of the month GET query argument. Raises a 404 if no valid month specification can be found.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.MonthMixin.get_month
get_month_format() Returns the strftime() format to use when parsing the month. Returns month_format by default.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.MonthMixin.get_month_format
get_next_month(date) Returns a date object containing the first day of the month after the date provided. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.MonthMixin.get_next_month
get_previous_month(date) Returns a date object containing the first day of the month before the date provided. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.
django.ref.class-based-views.mixins-date-based#django.views.generic.dates.MonthMixin.get_previous_month