diff --git a/testbed/django__django/django/__init__.py b/testbed/django__django/django/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42317d407ad7dd26736687fb83e733583e21ede5 --- /dev/null +++ b/testbed/django__django/django/__init__.py @@ -0,0 +1,24 @@ +from django.utils.version import get_version + +VERSION = (5, 0, 0, "alpha", 0) + +__version__ = get_version(VERSION) + + +def setup(set_prefix=True): + """ + Configure the settings (this happens as a side effect of accessing the + first setting), configure logging and populate the app registry. + Set the thread-local urlresolvers script prefix if `set_prefix` is True. + """ + from django.apps import apps + from django.conf import settings + from django.urls import set_script_prefix + from django.utils.log import configure_logging + + configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) + if set_prefix: + set_script_prefix( + "/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME + ) + apps.populate(settings.INSTALLED_APPS) diff --git a/testbed/django__django/django/__main__.py b/testbed/django__django/django/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b96e91ea855199db68e7098d5c437d8157ad0ba --- /dev/null +++ b/testbed/django__django/django/__main__.py @@ -0,0 +1,9 @@ +""" +Invokes django-admin when the django module is run as a script. + +Example: python -m django check +""" +from django.core import management + +if __name__ == "__main__": + management.execute_from_command_line() diff --git a/testbed/django__django/django/shortcuts.py b/testbed/django__django/django/shortcuts.py new file mode 100644 index 0000000000000000000000000000000000000000..90ec1bedc52d77fe503bf2748c0fd30d254d6c3e --- /dev/null +++ b/testbed/django__django/django/shortcuts.py @@ -0,0 +1,155 @@ +""" +This module collects helper functions and classes that "span" multiple levels +of MVC. In other words, these functions/classes introduce controlled coupling +for convenience's sake. +""" +from django.http import ( + Http404, + HttpResponse, + HttpResponsePermanentRedirect, + HttpResponseRedirect, +) +from django.template import loader +from django.urls import NoReverseMatch, reverse +from django.utils.functional import Promise + + +def render( + request, template_name, context=None, content_type=None, status=None, using=None +): + """ + Return an HttpResponse whose content is filled with the result of calling + django.template.loader.render_to_string() with the passed arguments. + """ + content = loader.render_to_string(template_name, context, request, using=using) + return HttpResponse(content, content_type, status) + + +def redirect(to, *args, permanent=False, **kwargs): + """ + Return an HttpResponseRedirect to the appropriate URL for the arguments + passed. + + The arguments could be: + + * A model: the model's `get_absolute_url()` function will be called. + + * A view name, possibly with arguments: `urls.reverse()` will be used + to reverse-resolve the name. + + * A URL, which will be used as-is for the redirect location. + + Issues a temporary redirect by default; pass permanent=True to issue a + permanent redirect. + """ + redirect_class = ( + HttpResponsePermanentRedirect if permanent else HttpResponseRedirect + ) + return redirect_class(resolve_url(to, *args, **kwargs)) + + +def _get_queryset(klass): + """ + Return a QuerySet or a Manager. + Duck typing in action: any class with a `get()` method (for + get_object_or_404) or a `filter()` method (for get_list_or_404) might do + the job. + """ + # If it is a model class or anything else with ._default_manager + if hasattr(klass, "_default_manager"): + return klass._default_manager.all() + return klass + + +def get_object_or_404(klass, *args, **kwargs): + """ + Use get() to return an object, or raise an Http404 exception if the object + does not exist. + + klass may be a Model, Manager, or QuerySet object. All other passed + arguments and keyword arguments are used in the get() query. + + Like with QuerySet.get(), MultipleObjectsReturned is raised if more than + one object is found. + """ + queryset = _get_queryset(klass) + if not hasattr(queryset, "get"): + klass__name = ( + klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ + ) + raise ValueError( + "First argument to get_object_or_404() must be a Model, Manager, " + "or QuerySet, not '%s'." % klass__name + ) + try: + return queryset.get(*args, **kwargs) + except queryset.model.DoesNotExist: + raise Http404( + "No %s matches the given query." % queryset.model._meta.object_name + ) + + +def get_list_or_404(klass, *args, **kwargs): + """ + Use filter() to return a list of objects, or raise an Http404 exception if + the list is empty. + + klass may be a Model, Manager, or QuerySet object. All other passed + arguments and keyword arguments are used in the filter() query. + """ + queryset = _get_queryset(klass) + if not hasattr(queryset, "filter"): + klass__name = ( + klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ + ) + raise ValueError( + "First argument to get_list_or_404() must be a Model, Manager, or " + "QuerySet, not '%s'." % klass__name + ) + obj_list = list(queryset.filter(*args, **kwargs)) + if not obj_list: + raise Http404( + "No %s matches the given query." % queryset.model._meta.object_name + ) + return obj_list + + +def resolve_url(to, *args, **kwargs): + """ + Return a URL appropriate for the arguments passed. + + The arguments could be: + + * A model: the model's `get_absolute_url()` function will be called. + + * A view name, possibly with arguments: `urls.reverse()` will be used + to reverse-resolve the name. + + * A URL, which will be returned as-is. + """ + # If it's a model, use get_absolute_url() + if hasattr(to, "get_absolute_url"): + return to.get_absolute_url() + + if isinstance(to, Promise): + # Expand the lazy instance, as it can cause issues when it is passed + # further to some Python functions like urlparse. + to = str(to) + + # Handle relative URLs + if isinstance(to, str) and to.startswith(("./", "../")): + return to + + # Next try a reverse URL resolution. + try: + return reverse(to, args=args, kwargs=kwargs) + except NoReverseMatch: + # If this is a callable, re-raise. + if callable(to): + raise + # If this doesn't "feel" like a URL, re-raise. + if "/" not in to and "." not in to: + raise + + # Finally, fall back and assume it's a URL + return to diff --git a/testbed/django__django/django/views/__init__.py b/testbed/django__django/django/views/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1440d433458d338cc35c1f3440d38d4991dc4f7a --- /dev/null +++ b/testbed/django__django/django/views/__init__.py @@ -0,0 +1,3 @@ +from django.views.generic.base import View + +__all__ = ["View"] diff --git a/testbed/django__django/django/views/csrf.py b/testbed/django__django/django/views/csrf.py new file mode 100644 index 0000000000000000000000000000000000000000..3c572a621ade2bce3955ee1a35e79bbcfc2255e3 --- /dev/null +++ b/testbed/django__django/django/views/csrf.py @@ -0,0 +1,79 @@ +from pathlib import Path + +from django.conf import settings +from django.http import HttpResponseForbidden +from django.template import Context, Engine, TemplateDoesNotExist, loader +from django.utils.translation import gettext as _ +from django.utils.version import get_docs_version + +CSRF_FAILURE_TEMPLATE_NAME = "403_csrf.html" + + +def builtin_template_path(name): + """ + Return a path to a builtin template. + + Avoid calling this function at the module level or in a class-definition + because __file__ may not exist, e.g. in frozen environments. + """ + return Path(__file__).parent / "templates" / name + + +def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME): + """ + Default view used when request fails CSRF protection + """ + from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER + + c = { + "title": _("Forbidden"), + "main": _("CSRF verification failed. Request aborted."), + "reason": reason, + "no_referer": reason == REASON_NO_REFERER, + "no_referer1": _( + "You are seeing this message because this HTTPS site requires a " + "“Referer header” to be sent by your web browser, but none was " + "sent. This header is required for security reasons, to ensure " + "that your browser is not being hijacked by third parties." + ), + "no_referer2": _( + "If you have configured your browser to disable “Referer” headers, " + "please re-enable them, at least for this site, or for HTTPS " + "connections, or for “same-origin” requests." + ), + "no_referer3": _( + 'If you are using the tag or including the “Referrer-Policy: ' + "no-referrer” header, please remove them. The CSRF protection " + "requires the “Referer” header to do strict referer checking. If " + "you’re concerned about privacy, use alternatives like " + ' for links to third-party sites.' + ), + "no_cookie": reason == REASON_NO_CSRF_COOKIE, + "no_cookie1": _( + "You are seeing this message because this site requires a CSRF " + "cookie when submitting forms. This cookie is required for " + "security reasons, to ensure that your browser is not being " + "hijacked by third parties." + ), + "no_cookie2": _( + "If you have configured your browser to disable cookies, please " + "re-enable them, at least for this site, or for “same-origin” " + "requests." + ), + "DEBUG": settings.DEBUG, + "docs_version": get_docs_version(), + "more": _("More information is available with DEBUG=True."), + } + try: + t = loader.get_template(template_name) + except TemplateDoesNotExist: + if template_name == CSRF_FAILURE_TEMPLATE_NAME: + # If the default template doesn't exist, use the fallback template. + with builtin_template_path("csrf_403.html").open(encoding="utf-8") as fh: + t = Engine().from_string(fh.read()) + c = Context(c) + else: + # Raise if a developer-specified template doesn't exist. + raise + return HttpResponseForbidden(t.render(c)) diff --git a/testbed/django__django/django/views/debug.py b/testbed/django__django/django/views/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..c1265bfe6be3013d09d3b30505bd9d4dfe38904a --- /dev/null +++ b/testbed/django__django/django/views/debug.py @@ -0,0 +1,665 @@ +import functools +import inspect +import itertools +import re +import sys +import types +import warnings +from pathlib import Path + +from django.conf import settings +from django.http import Http404, HttpResponse, HttpResponseNotFound +from django.template import Context, Engine, TemplateDoesNotExist +from django.template.defaultfilters import pprint +from django.urls import resolve +from django.utils import timezone +from django.utils.datastructures import MultiValueDict +from django.utils.encoding import force_str +from django.utils.module_loading import import_string +from django.utils.regex_helper import _lazy_re_compile +from django.utils.version import PY311, get_docs_version +from django.views.decorators.debug import coroutine_functions_to_sensitive_variables + +# Minimal Django templates engine to render the error templates +# regardless of the project's TEMPLATES setting. Templates are +# read directly from the filesystem so that the error handler +# works even if the template loader is broken. +DEBUG_ENGINE = Engine( + debug=True, + libraries={"i18n": "django.templatetags.i18n"}, +) + + +def builtin_template_path(name): + """ + Return a path to a builtin template. + + Avoid calling this function at the module level or in a class-definition + because __file__ may not exist, e.g. in frozen environments. + """ + return Path(__file__).parent / "templates" / name + + +class ExceptionCycleWarning(UserWarning): + pass + + +class CallableSettingWrapper: + """ + Object to wrap callable appearing in settings. + * Not to call in the debug page (#21345). + * Not to break the debug page if the callable forbidding to set attributes + (#23070). + """ + + def __init__(self, callable_setting): + self._wrapped = callable_setting + + def __repr__(self): + return repr(self._wrapped) + + +def technical_500_response(request, exc_type, exc_value, tb, status_code=500): + """ + Create a technical server error response. The last three arguments are + the values returned from sys.exc_info() and friends. + """ + reporter = get_exception_reporter_class(request)(request, exc_type, exc_value, tb) + if request.accepts("text/html"): + html = reporter.get_traceback_html() + return HttpResponse(html, status=status_code) + else: + text = reporter.get_traceback_text() + return HttpResponse( + text, status=status_code, content_type="text/plain; charset=utf-8" + ) + + +@functools.lru_cache +def get_default_exception_reporter_filter(): + # Instantiate the default filter for the first time and cache it. + return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)() + + +def get_exception_reporter_filter(request): + default_filter = get_default_exception_reporter_filter() + return getattr(request, "exception_reporter_filter", default_filter) + + +def get_exception_reporter_class(request): + default_exception_reporter_class = import_string( + settings.DEFAULT_EXCEPTION_REPORTER + ) + return getattr( + request, "exception_reporter_class", default_exception_reporter_class + ) + + +def get_caller(request): + resolver_match = request.resolver_match + if resolver_match is None: + try: + resolver_match = resolve(request.path) + except Http404: + pass + return "" if resolver_match is None else resolver_match._func_path + + +class SafeExceptionReporterFilter: + """ + Use annotations made by the sensitive_post_parameters and + sensitive_variables decorators to filter out sensitive information. + """ + + cleansed_substitute = "********************" + hidden_settings = _lazy_re_compile( + "API|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE", flags=re.I + ) + + def cleanse_setting(self, key, value): + """ + Cleanse an individual setting key/value of sensitive content. If the + value is a dictionary, recursively cleanse the keys in that dictionary. + """ + if key == settings.SESSION_COOKIE_NAME: + is_sensitive = True + else: + try: + is_sensitive = self.hidden_settings.search(key) + except TypeError: + is_sensitive = False + + if is_sensitive: + cleansed = self.cleansed_substitute + elif isinstance(value, dict): + cleansed = {k: self.cleanse_setting(k, v) for k, v in value.items()} + elif isinstance(value, list): + cleansed = [self.cleanse_setting("", v) for v in value] + elif isinstance(value, tuple): + cleansed = tuple([self.cleanse_setting("", v) for v in value]) + else: + cleansed = value + + if callable(cleansed): + cleansed = CallableSettingWrapper(cleansed) + + return cleansed + + def get_safe_settings(self): + """ + Return a dictionary of the settings module with values of sensitive + settings replaced with stars (*********). + """ + settings_dict = {} + for k in dir(settings): + if k.isupper(): + settings_dict[k] = self.cleanse_setting(k, getattr(settings, k)) + return settings_dict + + def get_safe_request_meta(self, request): + """ + Return a dictionary of request.META with sensitive values redacted. + """ + if not hasattr(request, "META"): + return {} + return {k: self.cleanse_setting(k, v) for k, v in request.META.items()} + + def get_safe_cookies(self, request): + """ + Return a dictionary of request.COOKIES with sensitive values redacted. + """ + if not hasattr(request, "COOKIES"): + return {} + return {k: self.cleanse_setting(k, v) for k, v in request.COOKIES.items()} + + def is_active(self, request): + """ + This filter is to add safety in production environments (i.e. DEBUG + is False). If DEBUG is True then your site is not safe anyway. + This hook is provided as a convenience to easily activate or + deactivate the filter on a per request basis. + """ + return settings.DEBUG is False + + def get_cleansed_multivaluedict(self, request, multivaluedict): + """ + Replace the keys in a MultiValueDict marked as sensitive with stars. + This mitigates leaking sensitive POST parameters if something like + request.POST['nonexistent_key'] throws an exception (#21098). + """ + sensitive_post_parameters = getattr(request, "sensitive_post_parameters", []) + if self.is_active(request) and sensitive_post_parameters: + multivaluedict = multivaluedict.copy() + for param in sensitive_post_parameters: + if param in multivaluedict: + multivaluedict[param] = self.cleansed_substitute + return multivaluedict + + def get_post_parameters(self, request): + """ + Replace the values of POST parameters marked as sensitive with + stars (*********). + """ + if request is None: + return {} + else: + sensitive_post_parameters = getattr( + request, "sensitive_post_parameters", [] + ) + if self.is_active(request) and sensitive_post_parameters: + cleansed = request.POST.copy() + if sensitive_post_parameters == "__ALL__": + # Cleanse all parameters. + for k in cleansed: + cleansed[k] = self.cleansed_substitute + return cleansed + else: + # Cleanse only the specified parameters. + for param in sensitive_post_parameters: + if param in cleansed: + cleansed[param] = self.cleansed_substitute + return cleansed + else: + return request.POST + + def cleanse_special_types(self, request, value): + try: + # If value is lazy or a complex object of another kind, this check + # might raise an exception. isinstance checks that lazy + # MultiValueDicts will have a return value. + is_multivalue_dict = isinstance(value, MultiValueDict) + except Exception as e: + return "{!r} while evaluating {!r}".format(e, value) + + if is_multivalue_dict: + # Cleanse MultiValueDicts (request.POST is the one we usually care about) + value = self.get_cleansed_multivaluedict(request, value) + return value + + def get_traceback_frame_variables(self, request, tb_frame): + """ + Replace the values of variables marked as sensitive with + stars (*********). + """ + sensitive_variables = None + + # Coroutines don't have a proper `f_back` so they need to be inspected + # separately. Handle this by stashing the registered sensitive + # variables in a global dict indexed by `hash(file_path:line_number)`. + if ( + tb_frame.f_code.co_flags & inspect.CO_COROUTINE != 0 + and tb_frame.f_code.co_name != "sensitive_variables_wrapper" + ): + key = hash( + f"{tb_frame.f_code.co_filename}:{tb_frame.f_code.co_firstlineno}" + ) + sensitive_variables = coroutine_functions_to_sensitive_variables.get( + key, None + ) + + if sensitive_variables is None: + # Loop through the frame's callers to see if the + # sensitive_variables decorator was used. + current_frame = tb_frame + while current_frame is not None: + if ( + current_frame.f_code.co_name == "sensitive_variables_wrapper" + and "sensitive_variables_wrapper" in current_frame.f_locals + ): + # The sensitive_variables decorator was used, so take note + # of the sensitive variables' names. + wrapper = current_frame.f_locals["sensitive_variables_wrapper"] + sensitive_variables = getattr(wrapper, "sensitive_variables", None) + break + current_frame = current_frame.f_back + + cleansed = {} + if self.is_active(request) and sensitive_variables: + if sensitive_variables == "__ALL__": + # Cleanse all variables + for name in tb_frame.f_locals: + cleansed[name] = self.cleansed_substitute + else: + # Cleanse specified variables + for name, value in tb_frame.f_locals.items(): + if name in sensitive_variables: + value = self.cleansed_substitute + else: + value = self.cleanse_special_types(request, value) + cleansed[name] = value + else: + # Potentially cleanse the request and any MultiValueDicts if they + # are one of the frame variables. + for name, value in tb_frame.f_locals.items(): + cleansed[name] = self.cleanse_special_types(request, value) + + if ( + tb_frame.f_code.co_name == "sensitive_variables_wrapper" + and "sensitive_variables_wrapper" in tb_frame.f_locals + ): + # For good measure, obfuscate the decorated function's arguments in + # the sensitive_variables decorator's frame, in case the variables + # associated with those arguments were meant to be obfuscated from + # the decorated function's frame. + cleansed["func_args"] = self.cleansed_substitute + cleansed["func_kwargs"] = self.cleansed_substitute + + return cleansed.items() + + +class ExceptionReporter: + """Organize and coordinate reporting on exceptions.""" + + @property + def html_template_path(self): + return builtin_template_path("technical_500.html") + + @property + def text_template_path(self): + return builtin_template_path("technical_500.txt") + + def __init__(self, request, exc_type, exc_value, tb, is_email=False): + self.request = request + self.filter = get_exception_reporter_filter(self.request) + self.exc_type = exc_type + self.exc_value = exc_value + self.tb = tb + self.is_email = is_email + + self.template_info = getattr(self.exc_value, "template_debug", None) + self.template_does_not_exist = False + self.postmortem = None + + def _get_raw_insecure_uri(self): + """ + Return an absolute URI from variables available in this request. Skip + allowed hosts protection, so may return insecure URI. + """ + return "{scheme}://{host}{path}".format( + scheme=self.request.scheme, + host=self.request._get_raw_host(), + path=self.request.get_full_path(), + ) + + def get_traceback_data(self): + """Return a dictionary containing traceback information.""" + if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist): + self.template_does_not_exist = True + self.postmortem = self.exc_value.chain or [self.exc_value] + + frames = self.get_traceback_frames() + for i, frame in enumerate(frames): + if "vars" in frame: + frame_vars = [] + for k, v in frame["vars"]: + v = pprint(v) + # Trim large blobs of data + if len(v) > 4096: + v = "%s… " % (v[0:4096], len(v)) + frame_vars.append((k, v)) + frame["vars"] = frame_vars + frames[i] = frame + + unicode_hint = "" + if self.exc_type and issubclass(self.exc_type, UnicodeError): + start = getattr(self.exc_value, "start", None) + end = getattr(self.exc_value, "end", None) + if start is not None and end is not None: + unicode_str = self.exc_value.args[1] + unicode_hint = force_str( + unicode_str[max(start - 5, 0) : min(end + 5, len(unicode_str))], + "ascii", + errors="replace", + ) + from django import get_version + + if self.request is None: + user_str = None + else: + try: + user_str = str(self.request.user) + except Exception: + # request.user may raise OperationalError if the database is + # unavailable, for example. + user_str = "[unable to retrieve the current user]" + + c = { + "is_email": self.is_email, + "unicode_hint": unicode_hint, + "frames": frames, + "request": self.request, + "request_meta": self.filter.get_safe_request_meta(self.request), + "request_COOKIES_items": self.filter.get_safe_cookies(self.request).items(), + "user_str": user_str, + "filtered_POST_items": list( + self.filter.get_post_parameters(self.request).items() + ), + "settings": self.filter.get_safe_settings(), + "sys_executable": sys.executable, + "sys_version_info": "%d.%d.%d" % sys.version_info[0:3], + "server_time": timezone.now(), + "django_version_info": get_version(), + "sys_path": sys.path, + "template_info": self.template_info, + "template_does_not_exist": self.template_does_not_exist, + "postmortem": self.postmortem, + } + if self.request is not None: + c["request_GET_items"] = self.request.GET.items() + c["request_FILES_items"] = self.request.FILES.items() + c["request_insecure_uri"] = self._get_raw_insecure_uri() + c["raising_view_name"] = get_caller(self.request) + + # Check whether exception info is available + if self.exc_type: + c["exception_type"] = self.exc_type.__name__ + if self.exc_value: + c["exception_value"] = str(self.exc_value) + if exc_notes := getattr(self.exc_value, "__notes__", None): + c["exception_notes"] = "\n" + "\n".join(exc_notes) + if frames: + c["lastframe"] = frames[-1] + return c + + def get_traceback_html(self): + """Return HTML version of debug 500 HTTP error page.""" + with self.html_template_path.open(encoding="utf-8") as fh: + t = DEBUG_ENGINE.from_string(fh.read()) + c = Context(self.get_traceback_data(), use_l10n=False) + return t.render(c) + + def get_traceback_text(self): + """Return plain text version of debug 500 HTTP error page.""" + with self.text_template_path.open(encoding="utf-8") as fh: + t = DEBUG_ENGINE.from_string(fh.read()) + c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) + return t.render(c) + + def _get_source(self, filename, loader, module_name): + source = None + if hasattr(loader, "get_source"): + try: + source = loader.get_source(module_name) + except ImportError: + pass + if source is not None: + source = source.splitlines() + if source is None: + try: + with open(filename, "rb") as fp: + source = fp.read().splitlines() + except OSError: + pass + return source + + def _get_lines_from_file( + self, filename, lineno, context_lines, loader=None, module_name=None + ): + """ + Return context_lines before and after lineno from file. + Return (pre_context_lineno, pre_context, context_line, post_context). + """ + source = self._get_source(filename, loader, module_name) + if source is None: + return None, [], None, [] + + # If we just read the source from a file, or if the loader did not + # apply tokenize.detect_encoding to decode the source into a + # string, then we should do that ourselves. + if isinstance(source[0], bytes): + encoding = "ascii" + for line in source[:2]: + # File coding may be specified. Match pattern from PEP-263 + # (https://www.python.org/dev/peps/pep-0263/) + match = re.search(rb"coding[:=]\s*([-\w.]+)", line) + if match: + encoding = match[1].decode("ascii") + break + source = [str(sline, encoding, "replace") for sline in source] + + lower_bound = max(0, lineno - context_lines) + upper_bound = lineno + context_lines + + try: + pre_context = source[lower_bound:lineno] + context_line = source[lineno] + post_context = source[lineno + 1 : upper_bound] + except IndexError: + return None, [], None, [] + return lower_bound, pre_context, context_line, post_context + + def _get_explicit_or_implicit_cause(self, exc_value): + explicit = getattr(exc_value, "__cause__", None) + suppress_context = getattr(exc_value, "__suppress_context__", None) + implicit = getattr(exc_value, "__context__", None) + return explicit or (None if suppress_context else implicit) + + def get_traceback_frames(self): + # Get the exception and all its causes + exceptions = [] + exc_value = self.exc_value + while exc_value: + exceptions.append(exc_value) + exc_value = self._get_explicit_or_implicit_cause(exc_value) + if exc_value in exceptions: + warnings.warn( + "Cycle in the exception chain detected: exception '%s' " + "encountered again." % exc_value, + ExceptionCycleWarning, + ) + # Avoid infinite loop if there's a cyclic reference (#29393). + break + + frames = [] + # No exceptions were supplied to ExceptionReporter + if not exceptions: + return frames + + # In case there's just one exception, take the traceback from self.tb + exc_value = exceptions.pop() + tb = self.tb if not exceptions else exc_value.__traceback__ + while True: + frames.extend(self.get_exception_traceback_frames(exc_value, tb)) + try: + exc_value = exceptions.pop() + except IndexError: + break + tb = exc_value.__traceback__ + return frames + + def get_exception_traceback_frames(self, exc_value, tb): + exc_cause = self._get_explicit_or_implicit_cause(exc_value) + exc_cause_explicit = getattr(exc_value, "__cause__", True) + if tb is None: + yield { + "exc_cause": exc_cause, + "exc_cause_explicit": exc_cause_explicit, + "tb": None, + "type": "user", + } + while tb is not None: + # Support for __traceback_hide__ which is used by a few libraries + # to hide internal frames. + if tb.tb_frame.f_locals.get("__traceback_hide__"): + tb = tb.tb_next + continue + filename = tb.tb_frame.f_code.co_filename + function = tb.tb_frame.f_code.co_name + lineno = tb.tb_lineno - 1 + loader = tb.tb_frame.f_globals.get("__loader__") + module_name = tb.tb_frame.f_globals.get("__name__") or "" + ( + pre_context_lineno, + pre_context, + context_line, + post_context, + ) = self._get_lines_from_file( + filename, + lineno, + 7, + loader, + module_name, + ) + if pre_context_lineno is None: + pre_context_lineno = lineno + pre_context = [] + context_line = "" + post_context = [] + + colno = tb_area_colno = "" + if PY311: + _, _, start_column, end_column = next( + itertools.islice( + tb.tb_frame.f_code.co_positions(), tb.tb_lasti // 2, None + ) + ) + if start_column and end_column: + underline = "^" * (end_column - start_column) + spaces = " " * (start_column + len(str(lineno + 1)) + 2) + colno = f"\n{spaces}{underline}" + tb_area_spaces = " " * ( + 4 + + start_column + - (len(context_line) - len(context_line.lstrip())) + ) + tb_area_colno = f"\n{tb_area_spaces}{underline}" + yield { + "exc_cause": exc_cause, + "exc_cause_explicit": exc_cause_explicit, + "tb": tb, + "type": "django" if module_name.startswith("django.") else "user", + "filename": filename, + "function": function, + "lineno": lineno + 1, + "vars": self.filter.get_traceback_frame_variables( + self.request, tb.tb_frame + ), + "id": id(tb), + "pre_context": pre_context, + "context_line": context_line, + "post_context": post_context, + "pre_context_lineno": pre_context_lineno + 1, + "colno": colno, + "tb_area_colno": tb_area_colno, + } + tb = tb.tb_next + + +def technical_404_response(request, exception): + """Create a technical 404 error response. `exception` is the Http404.""" + try: + error_url = exception.args[0]["path"] + except (IndexError, TypeError, KeyError): + error_url = request.path_info[1:] # Trim leading slash + + try: + tried = exception.args[0]["tried"] + except (IndexError, TypeError, KeyError): + resolved = True + tried = request.resolver_match.tried if request.resolver_match else None + else: + resolved = False + if not tried or ( # empty URLconf + request.path == "/" + and len(tried) == 1 + and len(tried[0]) == 1 # default URLconf + and getattr(tried[0][0], "app_name", "") + == getattr(tried[0][0], "namespace", "") + == "admin" + ): + return default_urlconf(request) + + urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) + if isinstance(urlconf, types.ModuleType): + urlconf = urlconf.__name__ + + with builtin_template_path("technical_404.html").open(encoding="utf-8") as fh: + t = DEBUG_ENGINE.from_string(fh.read()) + reporter_filter = get_default_exception_reporter_filter() + c = Context( + { + "urlconf": urlconf, + "root_urlconf": settings.ROOT_URLCONF, + "request_path": error_url, + "urlpatterns": tried, + "resolved": resolved, + "reason": str(exception), + "request": request, + "settings": reporter_filter.get_safe_settings(), + "raising_view_name": get_caller(request), + } + ) + return HttpResponseNotFound(t.render(c)) + + +def default_urlconf(request): + """Create an empty URLconf 404 error response.""" + with builtin_template_path("default_urlconf.html").open(encoding="utf-8") as fh: + t = DEBUG_ENGINE.from_string(fh.read()) + c = Context( + { + "version": get_docs_version(), + } + ) + + return HttpResponse(t.render(c)) diff --git a/testbed/django__django/django/views/decorators/clickjacking.py b/testbed/django__django/django/views/decorators/clickjacking.py new file mode 100644 index 0000000000000000000000000000000000000000..c20fa59d2a296e5f7f3c1fb404780bf2762ec2a2 --- /dev/null +++ b/testbed/django__django/django/views/decorators/clickjacking.py @@ -0,0 +1,90 @@ +from functools import wraps + +from asgiref.sync import iscoroutinefunction + + +def xframe_options_deny(view_func): + """ + Modify a view function so its response has the X-Frame-Options HTTP + header set to 'DENY' as long as the response doesn't already have that + header set. Usage: + + @xframe_options_deny + def some_view(request): + ... + """ + + if iscoroutinefunction(view_func): + + async def _view_wrapper(*args, **kwargs): + response = await view_func(*args, **kwargs) + if response.get("X-Frame-Options") is None: + response["X-Frame-Options"] = "DENY" + return response + + else: + + def _view_wrapper(*args, **kwargs): + response = view_func(*args, **kwargs) + if response.get("X-Frame-Options") is None: + response["X-Frame-Options"] = "DENY" + return response + + return wraps(view_func)(_view_wrapper) + + +def xframe_options_sameorigin(view_func): + """ + Modify a view function so its response has the X-Frame-Options HTTP + header set to 'SAMEORIGIN' as long as the response doesn't already have + that header set. Usage: + + @xframe_options_sameorigin + def some_view(request): + ... + """ + + if iscoroutinefunction(view_func): + + async def _view_wrapper(*args, **kwargs): + response = await view_func(*args, **kwargs) + if response.get("X-Frame-Options") is None: + response["X-Frame-Options"] = "SAMEORIGIN" + return response + + else: + + def _view_wrapper(*args, **kwargs): + response = view_func(*args, **kwargs) + if response.get("X-Frame-Options") is None: + response["X-Frame-Options"] = "SAMEORIGIN" + return response + + return wraps(view_func)(_view_wrapper) + + +def xframe_options_exempt(view_func): + """ + Modify a view function by setting a response variable that instructs + XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header. Usage: + + @xframe_options_exempt + def some_view(request): + ... + """ + + if iscoroutinefunction(view_func): + + async def _view_wrapper(*args, **kwargs): + response = await view_func(*args, **kwargs) + response.xframe_options_exempt = True + return response + + else: + + def _view_wrapper(*args, **kwargs): + response = view_func(*args, **kwargs) + response.xframe_options_exempt = True + return response + + return wraps(view_func)(_view_wrapper) diff --git a/testbed/django__django/django/views/decorators/debug.py b/testbed/django__django/django/views/decorators/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea8a540de8235c4ceac3a41aa664a3642c8f2b4 --- /dev/null +++ b/testbed/django__django/django/views/decorators/debug.py @@ -0,0 +1,145 @@ +import inspect +from functools import wraps + +from asgiref.sync import iscoroutinefunction + +from django.http import HttpRequest + +coroutine_functions_to_sensitive_variables = {} + + +def sensitive_variables(*variables): + """ + Indicate which variables used in the decorated function are sensitive so + that those variables can later be treated in a special way, for example + by hiding them when logging unhandled exceptions. + + Accept two forms: + + * with specified variable names: + + @sensitive_variables('user', 'password', 'credit_card') + def my_function(user): + password = user.pass_word + credit_card = user.credit_card_number + ... + + * without any specified variable names, in which case consider all + variables are sensitive: + + @sensitive_variables() + def my_function() + ... + """ + if len(variables) == 1 and callable(variables[0]): + raise TypeError( + "sensitive_variables() must be called to use it as a decorator, " + "e.g., use @sensitive_variables(), not @sensitive_variables." + ) + + def decorator(func): + if iscoroutinefunction(func): + sensitive_variables_wrapper = func + + wrapped_func = func + while getattr(wrapped_func, "__wrapped__", None) is not None: + wrapped_func = wrapped_func.__wrapped__ + + try: + file_path = inspect.getfile(wrapped_func) + _, first_file_line = inspect.getsourcelines(wrapped_func) + except TypeError: # Raises for builtins or native functions. + raise ValueError( + f"{func.__name__} cannot safely be wrapped by " + "@sensitive_variables, make it either non-async or defined in a " + "Python file (not a builtin or from a native extension)." + ) + else: + key = hash(f"{file_path}:{first_file_line}") + + if variables: + coroutine_functions_to_sensitive_variables[key] = variables + else: + coroutine_functions_to_sensitive_variables[key] = "__ALL__" + + else: + + @wraps(func) + def sensitive_variables_wrapper(*func_args, **func_kwargs): + if variables: + sensitive_variables_wrapper.sensitive_variables = variables + else: + sensitive_variables_wrapper.sensitive_variables = "__ALL__" + return func(*func_args, **func_kwargs) + + return sensitive_variables_wrapper + + return decorator + + +def sensitive_post_parameters(*parameters): + """ + Indicate which POST parameters used in the decorated view are sensitive, + so that those parameters can later be treated in a special way, for example + by hiding them when logging unhandled exceptions. + + Accept two forms: + + * with specified parameters: + + @sensitive_post_parameters('password', 'credit_card') + def my_view(request): + pw = request.POST['password'] + cc = request.POST['credit_card'] + ... + + * without any specified parameters, in which case consider all + variables are sensitive: + + @sensitive_post_parameters() + def my_view(request) + ... + """ + if len(parameters) == 1 and callable(parameters[0]): + raise TypeError( + "sensitive_post_parameters() must be called to use it as a " + "decorator, e.g., use @sensitive_post_parameters(), not " + "@sensitive_post_parameters." + ) + + def decorator(view): + if iscoroutinefunction(view): + + @wraps(view) + async def sensitive_post_parameters_wrapper(request, *args, **kwargs): + if not isinstance(request, HttpRequest): + raise TypeError( + "sensitive_post_parameters didn't receive an HttpRequest " + "object. If you are decorating a classmethod, make sure to use " + "@method_decorator." + ) + if parameters: + request.sensitive_post_parameters = parameters + else: + request.sensitive_post_parameters = "__ALL__" + return await view(request, *args, **kwargs) + + else: + + @wraps(view) + def sensitive_post_parameters_wrapper(request, *args, **kwargs): + if not isinstance(request, HttpRequest): + raise TypeError( + "sensitive_post_parameters didn't receive an HttpRequest " + "object. If you are decorating a classmethod, make sure to use " + "@method_decorator." + ) + if parameters: + request.sensitive_post_parameters = parameters + else: + request.sensitive_post_parameters = "__ALL__" + return view(request, *args, **kwargs) + + return sensitive_post_parameters_wrapper + + return decorator diff --git a/testbed/django__django/django/views/decorators/vary.py b/testbed/django__django/django/views/decorators/vary.py new file mode 100644 index 0000000000000000000000000000000000000000..9beab8b4db845f0594efae20233b93b1e631be10 --- /dev/null +++ b/testbed/django__django/django/views/decorators/vary.py @@ -0,0 +1,44 @@ +from functools import wraps + +from asgiref.sync import iscoroutinefunction + +from django.utils.cache import patch_vary_headers + + +def vary_on_headers(*headers): + """ + A view decorator that adds the specified headers to the Vary header of the + response. Usage: + + @vary_on_headers('Cookie', 'Accept-language') + def index(request): + ... + + Note that the header names are not case-sensitive. + """ + + def decorator(func): + if iscoroutinefunction(func): + + async def _view_wrapper(request, *args, **kwargs): + response = await func(request, *args, **kwargs) + patch_vary_headers(response, headers) + return response + + else: + + def _view_wrapper(request, *args, **kwargs): + response = func(request, *args, **kwargs) + patch_vary_headers(response, headers) + return response + + return wraps(func)(_view_wrapper) + + return decorator + + +vary_on_cookie = vary_on_headers("Cookie") +vary_on_cookie.__doc__ = ( + 'A view decorator that adds "Cookie" to the Vary header of a response. This ' + "indicates that a page's contents depends on cookies." +) diff --git a/testbed/django__django/django/views/generic/__init__.py b/testbed/django__django/django/views/generic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8514bae51587f9848943de1b1e81450354495b24 --- /dev/null +++ b/testbed/django__django/django/views/generic/__init__.py @@ -0,0 +1,39 @@ +from django.views.generic.base import RedirectView, TemplateView, View +from django.views.generic.dates import ( + ArchiveIndexView, + DateDetailView, + DayArchiveView, + MonthArchiveView, + TodayArchiveView, + WeekArchiveView, + YearArchiveView, +) +from django.views.generic.detail import DetailView +from django.views.generic.edit import CreateView, DeleteView, FormView, UpdateView +from django.views.generic.list import ListView + +__all__ = [ + "View", + "TemplateView", + "RedirectView", + "ArchiveIndexView", + "YearArchiveView", + "MonthArchiveView", + "WeekArchiveView", + "DayArchiveView", + "TodayArchiveView", + "DateDetailView", + "DetailView", + "FormView", + "CreateView", + "UpdateView", + "DeleteView", + "ListView", + "GenericViewError", +] + + +class GenericViewError(Exception): + """A problem in a generic view.""" + + pass diff --git a/testbed/django__django/django/views/generic/dates.py b/testbed/django__django/django/views/generic/dates.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b776c1223d96e29f7cfd28f39f60d4b8d83ea0 --- /dev/null +++ b/testbed/django__django/django/views/generic/dates.py @@ -0,0 +1,795 @@ +import datetime + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from django.db import models +from django.http import Http404 +from django.utils import timezone +from django.utils.functional import cached_property +from django.utils.translation import gettext as _ +from django.views.generic.base import View +from django.views.generic.detail import ( + BaseDetailView, + SingleObjectTemplateResponseMixin, +) +from django.views.generic.list import ( + MultipleObjectMixin, + MultipleObjectTemplateResponseMixin, +) + + +class YearMixin: + """Mixin for views manipulating year-based data.""" + + year_format = "%Y" + year = None + + def get_year_format(self): + """ + Get a year format string in strptime syntax to be used to parse the + year from url variables. + """ + return self.year_format + + def get_year(self): + """Return the year for which this view should display data.""" + year = self.year + if year is None: + try: + year = self.kwargs["year"] + except KeyError: + try: + year = self.request.GET["year"] + except KeyError: + raise Http404(_("No year specified")) + return year + + def get_next_year(self, date): + """Get the next valid year.""" + return _get_next_prev(self, date, is_previous=False, period="year") + + def get_previous_year(self, date): + """Get the previous valid year.""" + return _get_next_prev(self, date, is_previous=True, period="year") + + def _get_next_year(self, date): + """ + Return the start date of the next interval. + + The interval is defined by start date <= item date < next start date. + """ + try: + return date.replace(year=date.year + 1, month=1, day=1) + except ValueError: + raise Http404(_("Date out of range")) + + def _get_current_year(self, date): + """Return the start date of the current interval.""" + return date.replace(month=1, day=1) + + +class MonthMixin: + """Mixin for views manipulating month-based data.""" + + month_format = "%b" + month = None + + def get_month_format(self): + """ + Get a month format string in strptime syntax to be used to parse the + month from url variables. + """ + return self.month_format + + def get_month(self): + """Return the month for which this view should display data.""" + month = self.month + if month is None: + try: + month = self.kwargs["month"] + except KeyError: + try: + month = self.request.GET["month"] + except KeyError: + raise Http404(_("No month specified")) + return month + + def get_next_month(self, date): + """Get the next valid month.""" + return _get_next_prev(self, date, is_previous=False, period="month") + + def get_previous_month(self, date): + """Get the previous valid month.""" + return _get_next_prev(self, date, is_previous=True, period="month") + + def _get_next_month(self, date): + """ + Return the start date of the next interval. + + The interval is defined by start date <= item date < next start date. + """ + if date.month == 12: + try: + return date.replace(year=date.year + 1, month=1, day=1) + except ValueError: + raise Http404(_("Date out of range")) + else: + return date.replace(month=date.month + 1, day=1) + + def _get_current_month(self, date): + """Return the start date of the previous interval.""" + return date.replace(day=1) + + +class DayMixin: + """Mixin for views manipulating day-based data.""" + + day_format = "%d" + day = None + + def get_day_format(self): + """ + Get a day format string in strptime syntax to be used to parse the day + from url variables. + """ + return self.day_format + + def get_day(self): + """Return the day for which this view should display data.""" + day = self.day + if day is None: + try: + day = self.kwargs["day"] + except KeyError: + try: + day = self.request.GET["day"] + except KeyError: + raise Http404(_("No day specified")) + return day + + def get_next_day(self, date): + """Get the next valid day.""" + return _get_next_prev(self, date, is_previous=False, period="day") + + def get_previous_day(self, date): + """Get the previous valid day.""" + return _get_next_prev(self, date, is_previous=True, period="day") + + def _get_next_day(self, date): + """ + Return the start date of the next interval. + + The interval is defined by start date <= item date < next start date. + """ + return date + datetime.timedelta(days=1) + + def _get_current_day(self, date): + """Return the start date of the current interval.""" + return date + + +class WeekMixin: + """Mixin for views manipulating week-based data.""" + + week_format = "%U" + week = None + + def get_week_format(self): + """ + Get a week format string in strptime syntax to be used to parse the + week from url variables. + """ + return self.week_format + + def get_week(self): + """Return the week for which this view should display data.""" + week = self.week + if week is None: + try: + week = self.kwargs["week"] + except KeyError: + try: + week = self.request.GET["week"] + except KeyError: + raise Http404(_("No week specified")) + return week + + def get_next_week(self, date): + """Get the next valid week.""" + return _get_next_prev(self, date, is_previous=False, period="week") + + def get_previous_week(self, date): + """Get the previous valid week.""" + return _get_next_prev(self, date, is_previous=True, period="week") + + def _get_next_week(self, date): + """ + Return the start date of the next interval. + + The interval is defined by start date <= item date < next start date. + """ + try: + return date + datetime.timedelta(days=7 - self._get_weekday(date)) + except OverflowError: + raise Http404(_("Date out of range")) + + def _get_current_week(self, date): + """Return the start date of the current interval.""" + return date - datetime.timedelta(self._get_weekday(date)) + + def _get_weekday(self, date): + """ + Return the weekday for a given date. + + The first day according to the week format is 0 and the last day is 6. + """ + week_format = self.get_week_format() + if week_format in {"%W", "%V"}: # week starts on Monday + return date.weekday() + elif week_format == "%U": # week starts on Sunday + return (date.weekday() + 1) % 7 + else: + raise ValueError("unknown week format: %s" % week_format) + + +class DateMixin: + """Mixin class for views manipulating date-based data.""" + + date_field = None + allow_future = False + + def get_date_field(self): + """Get the name of the date field to be used to filter by.""" + if self.date_field is None: + raise ImproperlyConfigured( + "%s.date_field is required." % self.__class__.__name__ + ) + return self.date_field + + def get_allow_future(self): + """ + Return `True` if the view should be allowed to display objects from + the future. + """ + return self.allow_future + + # Note: the following three methods only work in subclasses that also + # inherit SingleObjectMixin or MultipleObjectMixin. + + @cached_property + def uses_datetime_field(self): + """ + Return `True` if the date field is a `DateTimeField` and `False` + if it's a `DateField`. + """ + model = self.get_queryset().model if self.model is None else self.model + field = model._meta.get_field(self.get_date_field()) + return isinstance(field, models.DateTimeField) + + def _make_date_lookup_arg(self, value): + """ + Convert a date into a datetime when the date field is a DateTimeField. + + When time zone support is enabled, `date` is assumed to be in the + current time zone, so that displayed items are consistent with the URL. + """ + if self.uses_datetime_field: + value = datetime.datetime.combine(value, datetime.time.min) + if settings.USE_TZ: + value = timezone.make_aware(value) + return value + + def _make_single_date_lookup(self, date): + """ + Get the lookup kwargs for filtering on a single date. + + If the date field is a DateTimeField, we can't just filter on + date_field=date because that doesn't take the time into account. + """ + date_field = self.get_date_field() + if self.uses_datetime_field: + since = self._make_date_lookup_arg(date) + until = self._make_date_lookup_arg(date + datetime.timedelta(days=1)) + return { + "%s__gte" % date_field: since, + "%s__lt" % date_field: until, + } + else: + # Skip self._make_date_lookup_arg, it's a no-op in this branch. + return {date_field: date} + + +class BaseDateListView(MultipleObjectMixin, DateMixin, View): + """Abstract base class for date-based views displaying a list of objects.""" + + allow_empty = False + date_list_period = "year" + + def get(self, request, *args, **kwargs): + self.date_list, self.object_list, extra_context = self.get_dated_items() + context = self.get_context_data( + object_list=self.object_list, date_list=self.date_list, **extra_context + ) + return self.render_to_response(context) + + def get_dated_items(self): + """Obtain the list of dates and items.""" + raise NotImplementedError( + "A DateView must provide an implementation of get_dated_items()" + ) + + def get_ordering(self): + """ + Return the field or fields to use for ordering the queryset; use the + date field by default. + """ + return "-%s" % self.get_date_field() if self.ordering is None else self.ordering + + def get_dated_queryset(self, **lookup): + """ + Get a queryset properly filtered according to `allow_future` and any + extra lookup kwargs. + """ + qs = self.get_queryset().filter(**lookup) + date_field = self.get_date_field() + allow_future = self.get_allow_future() + allow_empty = self.get_allow_empty() + paginate_by = self.get_paginate_by(qs) + + if not allow_future: + now = timezone.now() if self.uses_datetime_field else timezone_today() + qs = qs.filter(**{"%s__lte" % date_field: now}) + + if not allow_empty: + # When pagination is enabled, it's better to do a cheap query + # than to load the unpaginated queryset in memory. + is_empty = not qs if paginate_by is None else not qs.exists() + if is_empty: + raise Http404( + _("No %(verbose_name_plural)s available") + % { + "verbose_name_plural": qs.model._meta.verbose_name_plural, + } + ) + + return qs + + def get_date_list_period(self): + """ + Get the aggregation period for the list of dates: 'year', 'month', or + 'day'. + """ + return self.date_list_period + + def get_date_list(self, queryset, date_type=None, ordering="ASC"): + """ + Get a date list by calling `queryset.dates/datetimes()`, checking + along the way for empty lists that aren't allowed. + """ + date_field = self.get_date_field() + allow_empty = self.get_allow_empty() + if date_type is None: + date_type = self.get_date_list_period() + + if self.uses_datetime_field: + date_list = queryset.datetimes(date_field, date_type, ordering) + else: + date_list = queryset.dates(date_field, date_type, ordering) + if date_list is not None and not date_list and not allow_empty: + raise Http404( + _("No %(verbose_name_plural)s available") + % { + "verbose_name_plural": queryset.model._meta.verbose_name_plural, + } + ) + + return date_list + + +class BaseArchiveIndexView(BaseDateListView): + """ + Base class for archives of date-based items. Requires a response mixin. + """ + + context_object_name = "latest" + + def get_dated_items(self): + """Return (date_list, items, extra_context) for this request.""" + qs = self.get_dated_queryset() + date_list = self.get_date_list(qs, ordering="DESC") + + if not date_list: + qs = qs.none() + + return (date_list, qs, {}) + + +class ArchiveIndexView(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView): + """Top-level archive of date-based items.""" + + template_name_suffix = "_archive" + + +class BaseYearArchiveView(YearMixin, BaseDateListView): + """List of objects published in a given year.""" + + date_list_period = "month" + make_object_list = False + + def get_dated_items(self): + """Return (date_list, items, extra_context) for this request.""" + year = self.get_year() + + date_field = self.get_date_field() + date = _date_from_string(year, self.get_year_format()) + + since = self._make_date_lookup_arg(date) + until = self._make_date_lookup_arg(self._get_next_year(date)) + lookup_kwargs = { + "%s__gte" % date_field: since, + "%s__lt" % date_field: until, + } + + qs = self.get_dated_queryset(**lookup_kwargs) + date_list = self.get_date_list(qs) + + if not self.get_make_object_list(): + # We need this to be a queryset since parent classes introspect it + # to find information about the model. + qs = qs.none() + + return ( + date_list, + qs, + { + "year": date, + "next_year": self.get_next_year(date), + "previous_year": self.get_previous_year(date), + }, + ) + + def get_make_object_list(self): + """ + Return `True` if this view should contain the full list of objects in + the given year. + """ + return self.make_object_list + + +class YearArchiveView(MultipleObjectTemplateResponseMixin, BaseYearArchiveView): + """List of objects published in a given year.""" + + template_name_suffix = "_archive_year" + + +class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView): + """List of objects published in a given month.""" + + date_list_period = "day" + + def get_dated_items(self): + """Return (date_list, items, extra_context) for this request.""" + year = self.get_year() + month = self.get_month() + + date_field = self.get_date_field() + date = _date_from_string( + year, self.get_year_format(), month, self.get_month_format() + ) + + since = self._make_date_lookup_arg(date) + until = self._make_date_lookup_arg(self._get_next_month(date)) + lookup_kwargs = { + "%s__gte" % date_field: since, + "%s__lt" % date_field: until, + } + + qs = self.get_dated_queryset(**lookup_kwargs) + date_list = self.get_date_list(qs) + + return ( + date_list, + qs, + { + "month": date, + "next_month": self.get_next_month(date), + "previous_month": self.get_previous_month(date), + }, + ) + + +class MonthArchiveView(MultipleObjectTemplateResponseMixin, BaseMonthArchiveView): + """List of objects published in a given month.""" + + template_name_suffix = "_archive_month" + + +class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView): + """List of objects published in a given week.""" + + def get_dated_items(self): + """Return (date_list, items, extra_context) for this request.""" + year = self.get_year() + week = self.get_week() + + date_field = self.get_date_field() + week_format = self.get_week_format() + week_choices = {"%W": "1", "%U": "0", "%V": "1"} + try: + week_start = week_choices[week_format] + except KeyError: + raise ValueError( + "Unknown week format %r. Choices are: %s" + % ( + week_format, + ", ".join(sorted(week_choices)), + ) + ) + year_format = self.get_year_format() + if week_format == "%V" and year_format != "%G": + raise ValueError( + "ISO week directive '%s' is incompatible with the year " + "directive '%s'. Use the ISO year '%%G' instead." + % ( + week_format, + year_format, + ) + ) + date = _date_from_string(year, year_format, week_start, "%w", week, week_format) + since = self._make_date_lookup_arg(date) + until = self._make_date_lookup_arg(self._get_next_week(date)) + lookup_kwargs = { + "%s__gte" % date_field: since, + "%s__lt" % date_field: until, + } + + qs = self.get_dated_queryset(**lookup_kwargs) + + return ( + None, + qs, + { + "week": date, + "next_week": self.get_next_week(date), + "previous_week": self.get_previous_week(date), + }, + ) + + +class WeekArchiveView(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView): + """List of objects published in a given week.""" + + template_name_suffix = "_archive_week" + + +class BaseDayArchiveView(YearMixin, MonthMixin, DayMixin, BaseDateListView): + """List of objects published on a given day.""" + + def get_dated_items(self): + """Return (date_list, items, extra_context) for this request.""" + year = self.get_year() + month = self.get_month() + day = self.get_day() + + date = _date_from_string( + year, + self.get_year_format(), + month, + self.get_month_format(), + day, + self.get_day_format(), + ) + + return self._get_dated_items(date) + + def _get_dated_items(self, date): + """ + Do the actual heavy lifting of getting the dated items; this accepts a + date object so that TodayArchiveView can be trivial. + """ + lookup_kwargs = self._make_single_date_lookup(date) + qs = self.get_dated_queryset(**lookup_kwargs) + + return ( + None, + qs, + { + "day": date, + "previous_day": self.get_previous_day(date), + "next_day": self.get_next_day(date), + "previous_month": self.get_previous_month(date), + "next_month": self.get_next_month(date), + }, + ) + + +class DayArchiveView(MultipleObjectTemplateResponseMixin, BaseDayArchiveView): + """List of objects published on a given day.""" + + template_name_suffix = "_archive_day" + + +class BaseTodayArchiveView(BaseDayArchiveView): + """List of objects published today.""" + + def get_dated_items(self): + """Return (date_list, items, extra_context) for this request.""" + return self._get_dated_items(datetime.date.today()) + + +class TodayArchiveView(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView): + """List of objects published today.""" + + template_name_suffix = "_archive_day" + + +class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView): + """ + Detail view of a single object on a single date; this differs from the + standard DetailView by accepting a year/month/day in the URL. + """ + + def get_object(self, queryset=None): + """Get the object this request displays.""" + year = self.get_year() + month = self.get_month() + day = self.get_day() + date = _date_from_string( + year, + self.get_year_format(), + month, + self.get_month_format(), + day, + self.get_day_format(), + ) + + # Use a custom queryset if provided + qs = self.get_queryset() if queryset is None else queryset + + if not self.get_allow_future() and date > datetime.date.today(): + raise Http404( + _( + "Future %(verbose_name_plural)s not available because " + "%(class_name)s.allow_future is False." + ) + % { + "verbose_name_plural": qs.model._meta.verbose_name_plural, + "class_name": self.__class__.__name__, + } + ) + + # Filter down a queryset from self.queryset using the date from the + # URL. This'll get passed as the queryset to DetailView.get_object, + # which'll handle the 404 + lookup_kwargs = self._make_single_date_lookup(date) + qs = qs.filter(**lookup_kwargs) + + return super().get_object(queryset=qs) + + +class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView): + """ + Detail view of a single object on a single date; this differs from the + standard DetailView by accepting a year/month/day in the URL. + """ + + template_name_suffix = "_detail" + + +def _date_from_string( + year, year_format, month="", month_format="", day="", day_format="", delim="__" +): + """ + Get a datetime.date object given a format string and a year, month, and day + (only year is mandatory). Raise a 404 for an invalid date. + """ + format = year_format + delim + month_format + delim + day_format + datestr = str(year) + delim + str(month) + delim + str(day) + try: + return datetime.datetime.strptime(datestr, format).date() + except ValueError: + raise Http404( + _("Invalid date string “%(datestr)s” given format “%(format)s”") + % { + "datestr": datestr, + "format": format, + } + ) + + +def _get_next_prev(generic_view, date, is_previous, period): + """ + Get the next or the previous valid date. The idea is to allow links on + month/day views to never be 404s by never providing a date that'll be + invalid for the given view. + + This is a bit complicated since it handles different intervals of time, + hence the coupling to generic_view. + + However in essence the logic comes down to: + + * If allow_empty and allow_future are both true, this is easy: just + return the naive result (just the next/previous day/week/month, + regardless of object existence.) + + * If allow_empty is true, allow_future is false, and the naive result + isn't in the future, then return it; otherwise return None. + + * If allow_empty is false and allow_future is true, return the next + date *that contains a valid object*, even if it's in the future. If + there are no next objects, return None. + + * If allow_empty is false and allow_future is false, return the next + date that contains a valid object. If that date is in the future, or + if there are no next objects, return None. + """ + date_field = generic_view.get_date_field() + allow_empty = generic_view.get_allow_empty() + allow_future = generic_view.get_allow_future() + + get_current = getattr(generic_view, "_get_current_%s" % period) + get_next = getattr(generic_view, "_get_next_%s" % period) + + # Bounds of the current interval + start, end = get_current(date), get_next(date) + + # If allow_empty is True, the naive result will be valid + if allow_empty: + if is_previous: + result = get_current(start - datetime.timedelta(days=1)) + else: + result = end + + if allow_future or result <= timezone_today(): + return result + else: + return None + + # Otherwise, we'll need to go to the database to look for an object + # whose date_field is at least (greater than/less than) the given + # naive result + else: + # Construct a lookup and an ordering depending on whether we're doing + # a previous date or a next date lookup. + if is_previous: + lookup = {"%s__lt" % date_field: generic_view._make_date_lookup_arg(start)} + ordering = "-%s" % date_field + else: + lookup = {"%s__gte" % date_field: generic_view._make_date_lookup_arg(end)} + ordering = date_field + + # Filter out objects in the future if appropriate. + if not allow_future: + # Fortunately, to match the implementation of allow_future, + # we need __lte, which doesn't conflict with __lt above. + if generic_view.uses_datetime_field: + now = timezone.now() + else: + now = timezone_today() + lookup["%s__lte" % date_field] = now + + qs = generic_view.get_queryset().filter(**lookup).order_by(ordering) + + # Snag the first object from the queryset; if it doesn't exist that + # means there's no next/previous link available. + try: + result = getattr(qs[0], date_field) + except IndexError: + return None + + # Convert datetimes to dates in the current time zone. + if generic_view.uses_datetime_field: + if settings.USE_TZ: + result = timezone.localtime(result) + result = result.date() + + # Return the first day of the period. + return get_current(result) + + +def timezone_today(): + """Return the current date in the current time zone.""" + if settings.USE_TZ: + return timezone.localdate() + else: + return datetime.date.today() diff --git a/testbed/django__django/django/views/generic/edit.py b/testbed/django__django/django/views/generic/edit.py new file mode 100644 index 0000000000000000000000000000000000000000..97934f58cbc1f7b513e4a3da1fd13ae93c43f3ea --- /dev/null +++ b/testbed/django__django/django/views/generic/edit.py @@ -0,0 +1,274 @@ +from django.core.exceptions import ImproperlyConfigured +from django.forms import Form +from django.forms import models as model_forms +from django.http import HttpResponseRedirect +from django.views.generic.base import ContextMixin, TemplateResponseMixin, View +from django.views.generic.detail import ( + BaseDetailView, + SingleObjectMixin, + SingleObjectTemplateResponseMixin, +) + + +class FormMixin(ContextMixin): + """Provide a way to show and handle a form in a request.""" + + initial = {} + form_class = None + success_url = None + prefix = None + + def get_initial(self): + """Return the initial data to use for forms on this view.""" + return self.initial.copy() + + def get_prefix(self): + """Return the prefix to use for forms.""" + return self.prefix + + def get_form_class(self): + """Return the form class to use.""" + return self.form_class + + def get_form(self, form_class=None): + """Return an instance of the form to be used in this view.""" + if form_class is None: + form_class = self.get_form_class() + return form_class(**self.get_form_kwargs()) + + def get_form_kwargs(self): + """Return the keyword arguments for instantiating the form.""" + kwargs = { + "initial": self.get_initial(), + "prefix": self.get_prefix(), + } + + if self.request.method in ("POST", "PUT"): + kwargs.update( + { + "data": self.request.POST, + "files": self.request.FILES, + } + ) + return kwargs + + def get_success_url(self): + """Return the URL to redirect to after processing a valid form.""" + if not self.success_url: + raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.") + return str(self.success_url) # success_url may be lazy + + def form_valid(self, form): + """If the form is valid, redirect to the supplied URL.""" + return HttpResponseRedirect(self.get_success_url()) + + def form_invalid(self, form): + """If the form is invalid, render the invalid form.""" + return self.render_to_response(self.get_context_data(form=form)) + + def get_context_data(self, **kwargs): + """Insert the form into the context dict.""" + if "form" not in kwargs: + kwargs["form"] = self.get_form() + return super().get_context_data(**kwargs) + + +class ModelFormMixin(FormMixin, SingleObjectMixin): + """Provide a way to show and handle a ModelForm in a request.""" + + fields = None + + def get_form_class(self): + """Return the form class to use in this view.""" + if self.fields is not None and self.form_class: + raise ImproperlyConfigured( + "Specifying both 'fields' and 'form_class' is not permitted." + ) + if self.form_class: + return self.form_class + else: + if self.model is not None: + # If a model has been explicitly provided, use it + model = self.model + elif getattr(self, "object", None) is not None: + # If this view is operating on a single object, use + # the class of that object + model = self.object.__class__ + else: + # Try to get a queryset and extract the model class + # from that + model = self.get_queryset().model + + if self.fields is None: + raise ImproperlyConfigured( + "Using ModelFormMixin (base class of %s) without " + "the 'fields' attribute is prohibited." % self.__class__.__name__ + ) + + return model_forms.modelform_factory(model, fields=self.fields) + + def get_form_kwargs(self): + """Return the keyword arguments for instantiating the form.""" + kwargs = super().get_form_kwargs() + if hasattr(self, "object"): + kwargs.update({"instance": self.object}) + return kwargs + + def get_success_url(self): + """Return the URL to redirect to after processing a valid form.""" + if self.success_url: + url = self.success_url.format(**self.object.__dict__) + else: + try: + url = self.object.get_absolute_url() + except AttributeError: + raise ImproperlyConfigured( + "No URL to redirect to. Either provide a url or define" + " a get_absolute_url method on the Model." + ) + return url + + def form_valid(self, form): + """If the form is valid, save the associated model.""" + self.object = form.save() + return super().form_valid(form) + + +class ProcessFormView(View): + """Render a form on GET and processes it on POST.""" + + def get(self, request, *args, **kwargs): + """Handle GET requests: instantiate a blank version of the form.""" + return self.render_to_response(self.get_context_data()) + + def post(self, request, *args, **kwargs): + """ + Handle POST requests: instantiate a form instance with the passed + POST variables and then check if it's valid. + """ + form = self.get_form() + if form.is_valid(): + return self.form_valid(form) + else: + return self.form_invalid(form) + + # PUT is a valid HTTP verb for creating (with a known URL) or editing an + # object, note that browsers only support POST for now. + def put(self, *args, **kwargs): + return self.post(*args, **kwargs) + + +class BaseFormView(FormMixin, ProcessFormView): + """A base view for displaying a form.""" + + +class FormView(TemplateResponseMixin, BaseFormView): + """A view for displaying a form and rendering a template response.""" + + +class BaseCreateView(ModelFormMixin, ProcessFormView): + """ + Base view for creating a new object instance. + + Using this base class requires subclassing to provide a response mixin. + """ + + def get(self, request, *args, **kwargs): + self.object = None + return super().get(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + self.object = None + return super().post(request, *args, **kwargs) + + +class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView): + """ + View for creating a new object, with a response rendered by a template. + """ + + template_name_suffix = "_form" + + +class BaseUpdateView(ModelFormMixin, ProcessFormView): + """ + Base view for updating an existing object. + + Using this base class requires subclassing to provide a response mixin. + """ + + def get(self, request, *args, **kwargs): + self.object = self.get_object() + return super().get(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + self.object = self.get_object() + return super().post(request, *args, **kwargs) + + +class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView): + """View for updating an object, with a response rendered by a template.""" + + template_name_suffix = "_form" + + +class DeletionMixin: + """Provide the ability to delete objects.""" + + success_url = None + + def delete(self, request, *args, **kwargs): + """ + Call the delete() method on the fetched object and then redirect to the + success URL. + """ + self.object = self.get_object() + success_url = self.get_success_url() + self.object.delete() + return HttpResponseRedirect(success_url) + + # Add support for browsers which only accept GET and POST for now. + def post(self, request, *args, **kwargs): + return self.delete(request, *args, **kwargs) + + def get_success_url(self): + if self.success_url: + return self.success_url.format(**self.object.__dict__) + else: + raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.") + + +class BaseDeleteView(DeletionMixin, FormMixin, BaseDetailView): + """ + Base view for deleting an object. + + Using this base class requires subclassing to provide a response mixin. + """ + + form_class = Form + + def post(self, request, *args, **kwargs): + # Set self.object before the usual form processing flow. + # Inlined because having DeletionMixin as the first base, for + # get_success_url(), makes leveraging super() with ProcessFormView + # overly complex. + self.object = self.get_object() + form = self.get_form() + if form.is_valid(): + return self.form_valid(form) + else: + return self.form_invalid(form) + + def form_valid(self, form): + success_url = self.get_success_url() + self.object.delete() + return HttpResponseRedirect(success_url) + + +class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView): + """ + View for deleting an object retrieved with self.get_object(), with a + response rendered by a template. + """ + + template_name_suffix = "_confirm_delete" diff --git a/testbed/django__django/django/views/generic/list.py b/testbed/django__django/django/views/generic/list.py new file mode 100644 index 0000000000000000000000000000000000000000..830a8df630d579d77ed381914fe99498c36c881d --- /dev/null +++ b/testbed/django__django/django/views/generic/list.py @@ -0,0 +1,220 @@ +from django.core.exceptions import ImproperlyConfigured +from django.core.paginator import InvalidPage, Paginator +from django.db.models import QuerySet +from django.http import Http404 +from django.utils.translation import gettext as _ +from django.views.generic.base import ContextMixin, TemplateResponseMixin, View + + +class MultipleObjectMixin(ContextMixin): + """A mixin for views manipulating multiple objects.""" + + allow_empty = True + queryset = None + model = None + paginate_by = None + paginate_orphans = 0 + context_object_name = None + paginator_class = Paginator + page_kwarg = "page" + ordering = None + + def get_queryset(self): + """ + Return the list of items for this view. + + The return value must be an iterable and may be an instance of + `QuerySet` in which case `QuerySet` specific behavior will be enabled. + """ + if self.queryset is not None: + queryset = self.queryset + if isinstance(queryset, QuerySet): + queryset = queryset.all() + elif self.model is not None: + queryset = self.model._default_manager.all() + else: + raise ImproperlyConfigured( + "%(cls)s is missing a QuerySet. Define " + "%(cls)s.model, %(cls)s.queryset, or override " + "%(cls)s.get_queryset()." % {"cls": self.__class__.__name__} + ) + ordering = self.get_ordering() + if ordering: + if isinstance(ordering, str): + ordering = (ordering,) + queryset = queryset.order_by(*ordering) + + return queryset + + def get_ordering(self): + """Return the field or fields to use for ordering the queryset.""" + return self.ordering + + def paginate_queryset(self, queryset, page_size): + """Paginate the queryset, if needed.""" + paginator = self.get_paginator( + queryset, + page_size, + orphans=self.get_paginate_orphans(), + allow_empty_first_page=self.get_allow_empty(), + ) + page_kwarg = self.page_kwarg + page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 + try: + page_number = int(page) + except ValueError: + if page == "last": + page_number = paginator.num_pages + else: + raise Http404( + _("Page is not “last”, nor can it be converted to an int.") + ) + try: + page = paginator.page(page_number) + return (paginator, page, page.object_list, page.has_other_pages()) + except InvalidPage as e: + raise Http404( + _("Invalid page (%(page_number)s): %(message)s") + % {"page_number": page_number, "message": str(e)} + ) + + def get_paginate_by(self, queryset): + """ + Get the number of items to paginate by, or ``None`` for no pagination. + """ + return self.paginate_by + + def get_paginator( + self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs + ): + """Return an instance of the paginator for this view.""" + return self.paginator_class( + queryset, + per_page, + orphans=orphans, + allow_empty_first_page=allow_empty_first_page, + **kwargs, + ) + + def get_paginate_orphans(self): + """ + Return the maximum number of orphans extend the last page by when + paginating. + """ + return self.paginate_orphans + + def get_allow_empty(self): + """ + Return ``True`` if the view should display empty lists and ``False`` + if a 404 should be raised instead. + """ + return self.allow_empty + + def get_context_object_name(self, object_list): + """Get the name of the item to be used in the context.""" + if self.context_object_name: + return self.context_object_name + elif hasattr(object_list, "model"): + return "%s_list" % object_list.model._meta.model_name + else: + return None + + def get_context_data(self, *, object_list=None, **kwargs): + """Get the context for this view.""" + queryset = object_list if object_list is not None else self.object_list + page_size = self.get_paginate_by(queryset) + context_object_name = self.get_context_object_name(queryset) + if page_size: + paginator, page, queryset, is_paginated = self.paginate_queryset( + queryset, page_size + ) + context = { + "paginator": paginator, + "page_obj": page, + "is_paginated": is_paginated, + "object_list": queryset, + } + else: + context = { + "paginator": None, + "page_obj": None, + "is_paginated": False, + "object_list": queryset, + } + if context_object_name is not None: + context[context_object_name] = queryset + context.update(kwargs) + return super().get_context_data(**context) + + +class BaseListView(MultipleObjectMixin, View): + """A base view for displaying a list of objects.""" + + def get(self, request, *args, **kwargs): + self.object_list = self.get_queryset() + allow_empty = self.get_allow_empty() + + if not allow_empty: + # When pagination is enabled and object_list is a queryset, + # it's better to do a cheap query than to load the unpaginated + # queryset in memory. + if self.get_paginate_by(self.object_list) is not None and hasattr( + self.object_list, "exists" + ): + is_empty = not self.object_list.exists() + else: + is_empty = not self.object_list + if is_empty: + raise Http404( + _("Empty list and “%(class_name)s.allow_empty” is False.") + % { + "class_name": self.__class__.__name__, + } + ) + context = self.get_context_data() + return self.render_to_response(context) + + +class MultipleObjectTemplateResponseMixin(TemplateResponseMixin): + """Mixin for responding with a template and list of objects.""" + + template_name_suffix = "_list" + + def get_template_names(self): + """ + Return a list of template names to be used for the request. Must return + a list. May not be called if render_to_response is overridden. + """ + try: + names = super().get_template_names() + except ImproperlyConfigured: + # If template_name isn't specified, it's not a problem -- + # we just start with an empty list. + names = [] + + # If the list is a queryset, we'll invent a template name based on the + # app and model name. This name gets put at the end of the template + # name list so that user-supplied names override the automatically- + # generated ones. + if hasattr(self.object_list, "model"): + opts = self.object_list.model._meta + names.append( + "%s/%s%s.html" + % (opts.app_label, opts.model_name, self.template_name_suffix) + ) + elif not names: + raise ImproperlyConfigured( + "%(cls)s requires either a 'template_name' attribute " + "or a get_queryset() method that returns a QuerySet." + % { + "cls": self.__class__.__name__, + } + ) + return names + + +class ListView(MultipleObjectTemplateResponseMixin, BaseListView): + """ + Render some list of objects, set by `self.model` or `self.queryset`. + `self.queryset` can actually be any iterable of items, not just a queryset. + """ diff --git a/testbed/django__django/django/views/i18n.py b/testbed/django__django/django/views/i18n.py new file mode 100644 index 0000000000000000000000000000000000000000..771035d8ab2994b7396ae9585d9bdd5045aa15fd --- /dev/null +++ b/testbed/django__django/django/views/i18n.py @@ -0,0 +1,251 @@ +import json +import os +import re +from pathlib import Path + +from django.apps import apps +from django.conf import settings +from django.http import HttpResponse, HttpResponseRedirect, JsonResponse +from django.template import Context, Engine +from django.urls import translate_url +from django.utils.formats import get_format +from django.utils.http import url_has_allowed_host_and_scheme +from django.utils.translation import check_for_language, get_language +from django.utils.translation.trans_real import DjangoTranslation +from django.views.generic import View + +LANGUAGE_QUERY_PARAMETER = "language" + + +def builtin_template_path(name): + """ + Return a path to a builtin template. + + Avoid calling this function at the module level or in a class-definition + because __file__ may not exist, e.g. in frozen environments. + """ + return Path(__file__).parent / "templates" / name + + +def set_language(request): + """ + Redirect to a given URL while setting the chosen language in the session + (if enabled) and in a cookie. The URL and the language code need to be + specified in the request parameters. + + Since this view changes how the user will see the rest of the site, it must + only be accessed as a POST request. If called as a GET request, it will + redirect to the page in the request (the 'next' parameter) without changing + any state. + """ + next_url = request.POST.get("next", request.GET.get("next")) + if ( + next_url or request.accepts("text/html") + ) and not url_has_allowed_host_and_scheme( + url=next_url, + allowed_hosts={request.get_host()}, + require_https=request.is_secure(), + ): + next_url = request.META.get("HTTP_REFERER") + if not url_has_allowed_host_and_scheme( + url=next_url, + allowed_hosts={request.get_host()}, + require_https=request.is_secure(), + ): + next_url = "/" + response = HttpResponseRedirect(next_url) if next_url else HttpResponse(status=204) + if request.method == "POST": + lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) + if lang_code and check_for_language(lang_code): + if next_url: + next_trans = translate_url(next_url, lang_code) + if next_trans != next_url: + response = HttpResponseRedirect(next_trans) + response.set_cookie( + settings.LANGUAGE_COOKIE_NAME, + lang_code, + max_age=settings.LANGUAGE_COOKIE_AGE, + path=settings.LANGUAGE_COOKIE_PATH, + domain=settings.LANGUAGE_COOKIE_DOMAIN, + secure=settings.LANGUAGE_COOKIE_SECURE, + httponly=settings.LANGUAGE_COOKIE_HTTPONLY, + samesite=settings.LANGUAGE_COOKIE_SAMESITE, + ) + return response + + +def get_formats(): + """Return all formats strings required for i18n to work.""" + FORMAT_SETTINGS = ( + "DATE_FORMAT", + "DATETIME_FORMAT", + "TIME_FORMAT", + "YEAR_MONTH_FORMAT", + "MONTH_DAY_FORMAT", + "SHORT_DATE_FORMAT", + "SHORT_DATETIME_FORMAT", + "FIRST_DAY_OF_WEEK", + "DECIMAL_SEPARATOR", + "THOUSAND_SEPARATOR", + "NUMBER_GROUPING", + "DATE_INPUT_FORMATS", + "TIME_INPUT_FORMATS", + "DATETIME_INPUT_FORMATS", + ) + return {attr: get_format(attr) for attr in FORMAT_SETTINGS} + + +class JavaScriptCatalog(View): + """ + Return the selected language catalog as a JavaScript library. + + Receive the list of packages to check for translations in the `packages` + kwarg either from the extra dictionary passed to the path() function or as + a plus-sign delimited string from the request. Default is 'django.conf'. + + You can override the gettext domain for this view, but usually you don't + want to do that as JavaScript messages go to the djangojs domain. This + might be needed if you deliver your JavaScript source from Django templates. + """ + + domain = "djangojs" + packages = None + + def get(self, request, *args, **kwargs): + locale = get_language() + domain = kwargs.get("domain", self.domain) + # If packages are not provided, default to all installed packages, as + # DjangoTranslation without localedirs harvests them all. + packages = kwargs.get("packages", "") + packages = packages.split("+") if packages else self.packages + paths = self.get_paths(packages) if packages else None + self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) + context = self.get_context_data(**kwargs) + return self.render_to_response(context) + + def get_paths(self, packages): + allowable_packages = { + app_config.name: app_config for app_config in apps.get_app_configs() + } + app_configs = [ + allowable_packages[p] for p in packages if p in allowable_packages + ] + if len(app_configs) < len(packages): + excluded = [p for p in packages if p not in allowable_packages] + raise ValueError( + "Invalid package(s) provided to JavaScriptCatalog: %s" + % ",".join(excluded) + ) + # paths of requested packages + return [os.path.join(app.path, "locale") for app in app_configs] + + @property + def _num_plurals(self): + """ + Return the number of plurals for this catalog language, or 2 if no + plural string is available. + """ + match = re.search(r"nplurals=\s*(\d+)", self._plural_string or "") + if match: + return int(match[1]) + return 2 + + @property + def _plural_string(self): + """ + Return the plural string (including nplurals) for this catalog language, + or None if no plural string is available. + """ + if "" in self.translation._catalog: + for line in self.translation._catalog[""].split("\n"): + if line.startswith("Plural-Forms:"): + return line.split(":", 1)[1].strip() + return None + + def get_plural(self): + plural = self._plural_string + if plural is not None: + # This should be a compiled function of a typical plural-form: + # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : + # n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; + plural = [ + el.strip() + for el in plural.split(";") + if el.strip().startswith("plural=") + ][0].split("=", 1)[1] + return plural + + def get_catalog(self): + pdict = {} + catalog = {} + translation = self.translation + seen_keys = set() + while True: + for key, value in translation._catalog.items(): + if key == "" or key in seen_keys: + continue + if isinstance(key, str): + catalog[key] = value + elif isinstance(key, tuple): + msgid, cnt = key + pdict.setdefault(msgid, {})[cnt] = value + else: + raise TypeError(key) + seen_keys.add(key) + if translation._fallback: + translation = translation._fallback + else: + break + + num_plurals = self._num_plurals + for k, v in pdict.items(): + catalog[k] = [v.get(i, "") for i in range(num_plurals)] + return catalog + + def get_context_data(self, **kwargs): + return { + "catalog": self.get_catalog(), + "formats": get_formats(), + "plural": self.get_plural(), + } + + def render_to_response(self, context, **response_kwargs): + def indent(s): + return s.replace("\n", "\n ") + + with builtin_template_path("i18n_catalog.js").open(encoding="utf-8") as fh: + template = Engine().from_string(fh.read()) + context["catalog_str"] = ( + indent(json.dumps(context["catalog"], sort_keys=True, indent=2)) + if context["catalog"] + else None + ) + context["formats_str"] = indent( + json.dumps(context["formats"], sort_keys=True, indent=2) + ) + + return HttpResponse( + template.render(Context(context)), 'text/javascript; charset="utf-8"' + ) + + +class JSONCatalog(JavaScriptCatalog): + """ + Return the selected language catalog as a JSON object. + + Receive the same parameters as JavaScriptCatalog and return a response + with a JSON object of the following format: + + { + "catalog": { + # Translations catalog + }, + "formats": { + # Language formats for date, time, etc. + }, + "plural": '...' # Expression for plural forms, or null. + } + """ + + def render_to_response(self, context, **response_kwargs): + return JsonResponse(context) diff --git a/testbed/django__django/django/views/static.py b/testbed/django__django/django/views/static.py new file mode 100644 index 0000000000000000000000000000000000000000..df46c53093e09bf12b84e6a2b079891fb7774633 --- /dev/null +++ b/testbed/django__django/django/views/static.py @@ -0,0 +1,121 @@ +""" +Views and functions for serving static files. These are only to be used +during development, and SHOULD NOT be used in a production setting. +""" +import mimetypes +import posixpath +from pathlib import Path + +from django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified +from django.template import Context, Engine, TemplateDoesNotExist, loader +from django.utils._os import safe_join +from django.utils.http import http_date, parse_http_date +from django.utils.translation import gettext as _ +from django.utils.translation import gettext_lazy + + +def builtin_template_path(name): + """ + Return a path to a builtin template. + + Avoid calling this function at the module level or in a class-definition + because __file__ may not exist, e.g. in frozen environments. + """ + return Path(__file__).parent / "templates" / name + + +def serve(request, path, document_root=None, show_indexes=False): + """ + Serve static files below a given point in the directory structure. + + To use, put a URL pattern such as:: + + from django.views.static import serve + + path('', serve, {'document_root': '/path/to/my/files/'}) + + in your URLconf. You must provide the ``document_root`` param. You may + also set ``show_indexes`` to ``True`` if you'd like to serve a basic index + of the directory. This index view will use the template hardcoded below, + but if you'd like to override it, you can create a template called + ``static/directory_index.html``. + """ + path = posixpath.normpath(path).lstrip("/") + fullpath = Path(safe_join(document_root, path)) + if fullpath.is_dir(): + if show_indexes: + return directory_index(path, fullpath) + raise Http404(_("Directory indexes are not allowed here.")) + if not fullpath.exists(): + raise Http404(_("“%(path)s” does not exist") % {"path": fullpath}) + # Respect the If-Modified-Since header. + statobj = fullpath.stat() + if not was_modified_since( + request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj.st_mtime + ): + return HttpResponseNotModified() + content_type, encoding = mimetypes.guess_type(str(fullpath)) + content_type = content_type or "application/octet-stream" + response = FileResponse(fullpath.open("rb"), content_type=content_type) + response.headers["Last-Modified"] = http_date(statobj.st_mtime) + if encoding: + response.headers["Content-Encoding"] = encoding + return response + + +# Translatable string for static directory index template title. +template_translatable = gettext_lazy("Index of %(directory)s") + + +def directory_index(path, fullpath): + try: + t = loader.select_template( + [ + "static/directory_index.html", + "static/directory_index", + ] + ) + except TemplateDoesNotExist: + with builtin_template_path("directory_index.html").open(encoding="utf-8") as fh: + t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string( + fh.read() + ) + c = Context() + else: + c = {} + files = [] + for f in fullpath.iterdir(): + if not f.name.startswith("."): + url = str(f.relative_to(fullpath)) + if f.is_dir(): + url += "/" + files.append(url) + c.update( + { + "directory": path + "/", + "file_list": files, + } + ) + return HttpResponse(t.render(c)) + + +def was_modified_since(header=None, mtime=0): + """ + Was something modified since the user last downloaded it? + + header + This is the value of the If-Modified-Since header. If this is None, + I'll just return True. + + mtime + This is the modification time of the item we're talking about. + """ + try: + if header is None: + raise ValueError + header_mtime = parse_http_date(header) + if int(mtime) > header_mtime: + raise ValueError + except (ValueError, OverflowError): + return True + return False diff --git a/testbed/django__django/django/views/templates/csrf_403.html b/testbed/django__django/django/views/templates/csrf_403.html new file mode 100644 index 0000000000000000000000000000000000000000..402a2c6cdd4e6e3508d61d6807e02284b7cd0513 --- /dev/null +++ b/testbed/django__django/django/views/templates/csrf_403.html @@ -0,0 +1,84 @@ + + + + + + 403 Forbidden + + + +
+

{{ title }} (403)

+

{{ main }}

+{% if no_referer %} +

{{ no_referer1 }}

+

{{ no_referer2 }}

+

{{ no_referer3 }}

+{% endif %} +{% if no_cookie %} +

{{ no_cookie1 }}

+

{{ no_cookie2 }}

+{% endif %} +
+{% if DEBUG %} +
+

Help

+ {% if reason %} +

Reason given for failure:

+
+    {{ reason }}
+    
+ {% endif %} + +

In general, this can occur when there is a genuine Cross Site Request Forgery, or when + Django’s + CSRF mechanism has not been used correctly. For POST forms, you need to + ensure:

+ + + +

You’re seeing the help section of this page because you have DEBUG = + True in your Django settings file. Change that to False, + and only the initial error message will be displayed.

+ +

You can customize this page using the CSRF_FAILURE_VIEW setting.

+
+{% else %} +
+

{{ more }}

+
+{% endif %} + + diff --git a/testbed/django__django/django/views/templates/directory_index.html b/testbed/django__django/django/views/templates/directory_index.html new file mode 100644 index 0000000000000000000000000000000000000000..d67e5e0edd58ac0a89dc45087cadd5d255f7170c --- /dev/null +++ b/testbed/django__django/django/views/templates/directory_index.html @@ -0,0 +1,21 @@ +{% load i18n %} + + + + + + + {% blocktranslate %}Index of {{ directory }}{% endblocktranslate %} + + +

{% blocktranslate %}Index of {{ directory }}{% endblocktranslate %}

+ + + diff --git a/testbed/django__django/django/views/templates/technical_404.html b/testbed/django__django/django/views/templates/technical_404.html new file mode 100644 index 0000000000000000000000000000000000000000..c47dae22af20e0afd5c1bfd12f948662e39a80ca --- /dev/null +++ b/testbed/django__django/django/views/templates/technical_404.html @@ -0,0 +1,82 @@ + + + + + Page not found at {{ request.path_info }} + + + + +
+

Page not found (404)

+ {% if reason and resolved %}
{{ reason }}
{% endif %} + + + + + + + + + + {% if raising_view_name %} + + + + + {% endif %} +
Request Method:{{ request.META.REQUEST_METHOD }}
Request URL:{{ request.build_absolute_uri }}
Raised by:{{ raising_view_name }}
+
+
+ {% if urlpatterns %} +

+ Using the URLconf defined in {{ urlconf }}, + Django tried these URL patterns, in this order: +

+
    + {% for pattern in urlpatterns %} +
  1. + {% for pat in pattern %} + {{ pat.pattern }} + {% if forloop.last and pat.name %}[name='{{ pat.name }}']{% endif %} + {% endfor %} +
  2. + {% endfor %} +
+

+ {% if request_path %} + The current path, {{ request_path }}, + {% else %} + The empty path + {% endif %} + {% if resolved %}matched the last one.{% else %}didn’t match any of these.{% endif %} +

+ {% endif %} +
+ +
+

+ You’re seeing this error because you have DEBUG = True in + your Django settings file. Change that to False, and Django + will display a standard 404 page. +

+
+ + diff --git a/testbed/django__django/django/views/templates/technical_500.html b/testbed/django__django/django/views/templates/technical_500.html new file mode 100644 index 0000000000000000000000000000000000000000..a5c187147bb33ccb20e79487e0990855bde14018 --- /dev/null +++ b/testbed/django__django/django/views/templates/technical_500.html @@ -0,0 +1,491 @@ + + + + + + {% if exception_type %}{{ exception_type }}{% else %}Report{% endif %} + {% if request %} at {{ request.path_info }}{% endif %} + + {% if not is_email %} + + {% endif %} + + +
+

{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %} + {% if request %} at {{ request.path_info }}{% endif %}

+
{% if exception_value %}{{ exception_value|force_escape }}{% if exception_notes %}{{ exception_notes }}{% endif %}{% else %}No exception message supplied{% endif %}
+ +{% if request %} + + + + + + + + +{% endif %} + + + + +{% if exception_type %} + + + + +{% endif %} +{% if exception_type and exception_value %} + + + + +{% endif %} +{% if lastframe %} + + + + +{% endif %} +{% if raising_view_name %} + + + + +{% endif %} + + + + + + + + + + + + + + + + +
Request Method:{{ request.META.REQUEST_METHOD }}
Request URL:{{ request_insecure_uri }}
Django Version:{{ django_version_info }}
Exception Type:{{ exception_type }}
Exception Value:
{{ exception_value|force_escape }}
Exception Location:{{ lastframe.filename }}, line {{ lastframe.lineno }}, in {{ lastframe.function }}
Raised during:{{ raising_view_name }}
Python Executable:{{ sys_executable }}
Python Version:{{ sys_version_info }}
Python Path:
{{ sys_path|pprint }}
Server time:{{server_time|date:"r"}}
+
+{% if unicode_hint %} +
+

Unicode error hint

+

The string that could not be encoded/decoded was: {{ unicode_hint }}

+
+{% endif %} +{% if template_does_not_exist %} +
+

Template-loader postmortem

+ {% if postmortem %} +

Django tried loading these templates, in this order:

+ {% for entry in postmortem %} +

Using engine {{ entry.backend.name }}:

+ + {% endfor %} + {% else %} +

No templates were found because your 'TEMPLATES' setting is not configured.

+ {% endif %} +
+{% endif %} +{% if template_info %} +
+

Error during template rendering

+

In template {{ template_info.name }}, error at line {{ template_info.line }}

+

{{ template_info.message|force_escape }}

+ + {% for source_line in template_info.source_lines %} + {% if source_line.0 == template_info.line %} + + + + {% else %} + + + {% endif %} + {% endfor %} +
{{ source_line.0 }}{{ template_info.before }}{{ template_info.during }}{{ template_info.after }}
{{ source_line.0 }}{{ source_line.1 }}
+
+{% endif %} +{% if frames %} +
+

Traceback{% if not is_email %} + Switch to copy-and-paste view{% endif %} +

+
+ +
+{% if not is_email %} +
+
+ + + + + +

+ +
+
+{% endif %} +
+{% endif %} + +
+

Request information

+ +{% if request %} + {% if user_str %} +

USER

+

{{ user_str }}

+ {% endif %} + +

GET

+ {% if request.GET %} + + + + + + + + + {% for k, v in request_GET_items %} + + + + + {% endfor %} + +
VariableValue
{{ k }}
{{ v|pprint }}
+ {% else %} +

No GET data

+ {% endif %} + +

POST

+ {% if filtered_POST_items %} + + + + + + + + + {% for k, v in filtered_POST_items %} + + + + + {% endfor %} + +
VariableValue
{{ k }}
{{ v|pprint }}
+ {% else %} +

No POST data

+ {% endif %} + +

FILES

+ {% if request.FILES %} + + + + + + + + + {% for k, v in request_FILES_items %} + + + + + {% endfor %} + +
VariableValue
{{ k }}
{{ v|pprint }}
+ {% else %} +

No FILES data

+ {% endif %} + + + {% if request.COOKIES %} + + + + + + + + + {% for k, v in request_COOKIES_items %} + + + + + {% endfor %} + +
VariableValue
{{ k }}
{{ v|pprint }}
+ {% else %} +

No cookie data

+ {% endif %} + +

META

+ + + + + + + + + {% for k, v in request_meta.items|dictsort:0 %} + + + + + {% endfor %} + +
VariableValue
{{ k }}
{{ v|pprint }}
+{% else %} +

Request data not supplied

+{% endif %} + +

Settings

+

Using settings module {{ settings.SETTINGS_MODULE }}

+ + + + + + + + + {% for k, v in settings.items|dictsort:0 %} + + + + + {% endfor %} + +
SettingValue
{{ k }}
{{ v|pprint }}
+ +
+{% if not is_email %} +
+

+ You’re seeing this error because you have DEBUG = True in your + Django settings file. Change that to False, and Django will + display a standard page generated by the handler for this status code. +

+
+{% endif %} + + diff --git a/testbed/django__django/django/views/templates/technical_500.txt b/testbed/django__django/django/views/templates/technical_500.txt new file mode 100644 index 0000000000000000000000000000000000000000..5a75324ebc97472f4e41b88e4235c1e9483827e2 --- /dev/null +++ b/testbed/django__django/django/views/templates/technical_500.txt @@ -0,0 +1,66 @@ +{% firstof exception_type 'Report' %}{% if request %} at {{ request.path_info }}{% endif %} +{% firstof exception_value 'No exception message supplied' %} +{% if request %} +Request Method: {{ request.META.REQUEST_METHOD }} +Request URL: {{ request_insecure_uri }}{% endif %} +Django Version: {{ django_version_info }} +Python Executable: {{ sys_executable }} +Python Version: {{ sys_version_info }} +Python Path: {{ sys_path }} +Server time: {{server_time|date:"r"}} +Installed Applications: +{{ settings.INSTALLED_APPS|pprint }} +Installed Middleware: +{{ settings.MIDDLEWARE|pprint }} +{% if template_does_not_exist %}Template loader postmortem +{% if postmortem %}Django tried loading these templates, in this order: +{% for entry in postmortem %} +Using engine {{ entry.backend.name }}: +{% if entry.tried %}{% for attempt in entry.tried %} * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) +{% endfor %}{% else %} This engine did not provide a list of tried templates. +{% endif %}{% endfor %} +{% else %}No templates were found because your 'TEMPLATES' setting is not configured. +{% endif %} +{% endif %}{% if template_info %} +Template error: +In template {{ template_info.name }}, error at line {{ template_info.line }} + {{ template_info.message }} +{% for source_line in template_info.source_lines %}{% if source_line.0 == template_info.line %} {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}{% else %} {{ source_line.0 }} : {{ source_line.1 }}{% endif %}{% endfor %}{% endif %}{% if frames %} + +Traceback (most recent call last): +{% for frame in frames %}{% ifchanged frame.exc_cause %}{% if frame.exc_cause %} +{% if frame.exc_cause_explicit %}The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception:{% else %}During handling of the above exception ({{ frame.exc_cause }}), another exception occurred:{% endif %} +{% endif %}{% endifchanged %} {% if frame.tb %}File "{{ frame.filename }}"{% if frame.context_line %}, line {{ frame.lineno }}{% endif %}, in {{ frame.function }} +{% if frame.context_line %} {% spaceless %}{{ frame.context_line }}{% endspaceless %}{{ frame.tb_area_colno }}{% endif %}{% elif forloop.first %}None{% else %}Traceback: None{% endif %} +{% endfor %} +{% if exception_type %}Exception Type: {{ exception_type }}{% if request %} at {{ request.path_info }}{% endif %} +{% if exception_value %}Exception Value: {{ exception_value }}{% endif %}{% if exception_notes %}{{ exception_notes }}{% endif %}{% endif %}{% endif %} +{% if raising_view_name %}Raised during: {{ raising_view_name }}{% endif %} +{% if request %}Request information: +{% if user_str %}USER: {{ user_str }}{% endif %} + +GET:{% for k, v in request_GET_items %} +{{ k }} = {{ v|stringformat:"r" }}{% empty %} No GET data{% endfor %} + +POST:{% for k, v in filtered_POST_items %} +{{ k }} = {{ v|stringformat:"r" }}{% empty %} No POST data{% endfor %} + +FILES:{% for k, v in request_FILES_items %} +{{ k }} = {{ v|stringformat:"r" }}{% empty %} No FILES data{% endfor %} + +COOKIES:{% for k, v in request_COOKIES_items %} +{{ k }} = {{ v|stringformat:"r" }}{% empty %} No cookie data{% endfor %} + +META:{% for k, v in request_meta.items|dictsort:0 %} +{{ k }} = {{ v|stringformat:"r" }}{% endfor %} +{% else %}Request data not supplied +{% endif %} +Settings: +Using settings module {{ settings.SETTINGS_MODULE }}{% for k, v in settings.items|dictsort:0 %} +{{ k }} = {{ v|stringformat:"r" }}{% endfor %} + +{% if not is_email %} +You’re seeing this error because you have DEBUG = True in your +Django settings file. Change that to False, and Django will +display a standard page generated by the handler for this status code. +{% endif %} diff --git a/testbed/django__django/docs/_ext/djangodocs.py b/testbed/django__django/docs/_ext/djangodocs.py new file mode 100644 index 0000000000000000000000000000000000000000..866b8f891d62af1c418f3edfc26c02cb5eef4783 --- /dev/null +++ b/testbed/django__django/docs/_ext/djangodocs.py @@ -0,0 +1,396 @@ +""" +Sphinx plugins for Django documentation. +""" +import json +import os +import re + +from docutils import nodes +from docutils.parsers.rst import Directive +from docutils.statemachine import ViewList +from sphinx import addnodes +from sphinx.builders.html import StandaloneHTMLBuilder +from sphinx.directives.code import CodeBlock +from sphinx.domains.std import Cmdoption +from sphinx.errors import ExtensionError +from sphinx.util import logging +from sphinx.util.console import bold +from sphinx.writers.html import HTMLTranslator + +logger = logging.getLogger(__name__) +# RE for option descriptions without a '--' prefix +simple_option_desc_re = re.compile(r"([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)") + + +def setup(app): + app.add_crossref_type( + directivename="setting", + rolename="setting", + indextemplate="pair: %s; setting", + ) + app.add_crossref_type( + directivename="templatetag", + rolename="ttag", + indextemplate="pair: %s; template tag", + ) + app.add_crossref_type( + directivename="templatefilter", + rolename="tfilter", + indextemplate="pair: %s; template filter", + ) + app.add_crossref_type( + directivename="fieldlookup", + rolename="lookup", + indextemplate="pair: %s; field lookup type", + ) + app.add_object_type( + directivename="django-admin", + rolename="djadmin", + indextemplate="pair: %s; django-admin command", + parse_node=parse_django_admin_node, + ) + app.add_directive("django-admin-option", Cmdoption) + app.add_config_value("django_next_version", "0.0", True) + app.add_directive("versionadded", VersionDirective) + app.add_directive("versionchanged", VersionDirective) + app.add_builder(DjangoStandaloneHTMLBuilder) + app.set_translator("djangohtml", DjangoHTMLTranslator) + app.set_translator("json", DjangoHTMLTranslator) + app.add_node( + ConsoleNode, + html=(visit_console_html, None), + latex=(visit_console_dummy, depart_console_dummy), + man=(visit_console_dummy, depart_console_dummy), + text=(visit_console_dummy, depart_console_dummy), + texinfo=(visit_console_dummy, depart_console_dummy), + ) + app.add_directive("console", ConsoleDirective) + app.connect("html-page-context", html_page_context_hook) + app.add_role("default-role-error", default_role_error) + return {"parallel_read_safe": True} + + +class VersionDirective(Directive): + has_content = True + required_arguments = 1 + optional_arguments = 1 + final_argument_whitespace = True + option_spec = {} + + def run(self): + if len(self.arguments) > 1: + msg = """Only one argument accepted for directive '{directive_name}::'. + Comments should be provided as content, + not as an extra argument.""".format( + directive_name=self.name + ) + raise self.error(msg) + + env = self.state.document.settings.env + ret = [] + node = addnodes.versionmodified() + ret.append(node) + + if self.arguments[0] == env.config.django_next_version: + node["version"] = "Development version" + else: + node["version"] = self.arguments[0] + + node["type"] = self.name + if self.content: + self.state.nested_parse(self.content, self.content_offset, node) + try: + env.get_domain("changeset").note_changeset(node) + except ExtensionError: + # Sphinx < 1.8: Domain 'changeset' is not registered + env.note_versionchange(node["type"], node["version"], node, self.lineno) + return ret + + +class DjangoHTMLTranslator(HTMLTranslator): + """ + Django-specific reST to HTML tweaks. + """ + + # Don't use border=1, which docutils does by default. + def visit_table(self, node): + self.context.append(self.compact_p) + self.compact_p = True + # Needed by Sphinx. + self._table_row_indices.append(0) + self.body.append(self.starttag(node, "table", CLASS="docutils")) + + def depart_table(self, node): + self.compact_p = self.context.pop() + self._table_row_indices.pop() + self.body.append("\n") + + def visit_desc_parameterlist(self, node): + self.body.append("(") # by default sphinx puts around the "(" + self.first_param = 1 + self.optional_param_level = 0 + self.param_separator = node.child_text_separator + self.required_params_left = sum( + isinstance(c, addnodes.desc_parameter) for c in node.children + ) + + def depart_desc_parameterlist(self, node): + self.body.append(")") + + # + # Turn the "new in version" stuff (versionadded/versionchanged) into a + # better callout -- the Sphinx default is just a little span, + # which is a bit less obvious that I'd like. + # + # FIXME: these messages are all hardcoded in English. We need to change + # that to accommodate other language docs, but I can't work out how to make + # that work. + # + version_text = { + "versionchanged": "Changed in Django %s", + "versionadded": "New in Django %s", + } + + def visit_versionmodified(self, node): + self.body.append(self.starttag(node, "div", CLASS=node["type"])) + version_text = self.version_text.get(node["type"]) + if version_text: + title = "%s%s" % (version_text % node["version"], ":" if len(node) else ".") + self.body.append('%s ' % title) + + def depart_versionmodified(self, node): + self.body.append("\n") + + # Give each section a unique ID -- nice for custom CSS hooks + def visit_section(self, node): + old_ids = node.get("ids", []) + node["ids"] = ["s-" + i for i in old_ids] + node["ids"].extend(old_ids) + super().visit_section(node) + node["ids"] = old_ids + + +def parse_django_admin_node(env, sig, signode): + command = sig.split(" ")[0] + env.ref_context["std:program"] = command + title = "django-admin %s" % sig + signode += addnodes.desc_name(title, title) + return command + + +class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder): + """ + Subclass to add some extra things we need. + """ + + name = "djangohtml" + + def finish(self): + super().finish() + logger.info(bold("writing templatebuiltins.js...")) + xrefs = self.env.domaindata["std"]["objects"] + templatebuiltins = { + "ttags": [ + n + for ((t, n), (k, a)) in xrefs.items() + if t == "templatetag" and k == "ref/templates/builtins" + ], + "tfilters": [ + n + for ((t, n), (k, a)) in xrefs.items() + if t == "templatefilter" and k == "ref/templates/builtins" + ], + } + outfilename = os.path.join(self.outdir, "templatebuiltins.js") + with open(outfilename, "w") as fp: + fp.write("var django_template_builtins = ") + json.dump(templatebuiltins, fp) + fp.write(";\n") + + +class ConsoleNode(nodes.literal_block): + """ + Custom node to override the visit/depart event handlers at registration + time. Wrap a literal_block object and defer to it. + """ + + tagname = "ConsoleNode" + + def __init__(self, litblk_obj): + self.wrapped = litblk_obj + + def __getattr__(self, attr): + if attr == "wrapped": + return self.__dict__.wrapped + return getattr(self.wrapped, attr) + + +def visit_console_dummy(self, node): + """Defer to the corresponding parent's handler.""" + self.visit_literal_block(node) + + +def depart_console_dummy(self, node): + """Defer to the corresponding parent's handler.""" + self.depart_literal_block(node) + + +def visit_console_html(self, node): + """Generate HTML for the console directive.""" + if self.builder.name in ("djangohtml", "json") and node["win_console_text"]: + # Put a mark on the document object signaling the fact the directive + # has been used on it. + self.document._console_directive_used_flag = True + uid = node["uid"] + self.body.append( + """\ +
+ + + + +
\n""" + % {"id": uid} + ) + try: + self.visit_literal_block(node) + except nodes.SkipNode: + pass + self.body.append("
\n") + + self.body.append( + '
\n' % {"id": uid} + ) + win_text = node["win_console_text"] + highlight_args = {"force": True} + linenos = node.get("linenos", False) + + def warner(msg): + self.builder.warn(msg, (self.builder.current_docname, node.line)) + + highlighted = self.highlighter.highlight_block( + win_text, "doscon", warn=warner, linenos=linenos, **highlight_args + ) + self.body.append(highlighted) + self.body.append("
\n") + self.body.append("
\n") + raise nodes.SkipNode + else: + self.visit_literal_block(node) + + +class ConsoleDirective(CodeBlock): + """ + A reStructuredText directive which renders a two-tab code block in which + the second tab shows a Windows command line equivalent of the usual + Unix-oriented examples. + """ + + required_arguments = 0 + # The 'doscon' Pygments formatter needs a prompt like this. '>' alone + # won't do it because then it simply paints the whole command line as a + # gray comment with no highlighting at all. + WIN_PROMPT = r"...\> " + + def run(self): + def args_to_win(cmdline): + changed = False + out = [] + for token in cmdline.split(): + if token[:2] == "./": + token = token[2:] + changed = True + elif token[:2] == "~/": + token = "%HOMEPATH%\\" + token[2:] + changed = True + elif token == "make": + token = "make.bat" + changed = True + if "://" not in token and "git" not in cmdline: + out.append(token.replace("/", "\\")) + changed = True + else: + out.append(token) + if changed: + return " ".join(out) + return cmdline + + def cmdline_to_win(line): + if line.startswith("# "): + return "REM " + args_to_win(line[2:]) + if line.startswith("$ # "): + return "REM " + args_to_win(line[4:]) + if line.startswith("$ ./manage.py"): + return "manage.py " + args_to_win(line[13:]) + if line.startswith("$ manage.py"): + return "manage.py " + args_to_win(line[11:]) + if line.startswith("$ ./runtests.py"): + return "runtests.py " + args_to_win(line[15:]) + if line.startswith("$ ./"): + return args_to_win(line[4:]) + if line.startswith("$ python3"): + return "py " + args_to_win(line[9:]) + if line.startswith("$ python"): + return "py " + args_to_win(line[8:]) + if line.startswith("$ "): + return args_to_win(line[2:]) + return None + + def code_block_to_win(content): + bchanged = False + lines = [] + for line in content: + modline = cmdline_to_win(line) + if modline is None: + lines.append(line) + else: + lines.append(self.WIN_PROMPT + modline) + bchanged = True + if bchanged: + return ViewList(lines) + return None + + env = self.state.document.settings.env + self.arguments = ["console"] + lit_blk_obj = super().run()[0] + + # Only do work when the djangohtml HTML Sphinx builder is being used, + # invoke the default behavior for the rest. + if env.app.builder.name not in ("djangohtml", "json"): + return [lit_blk_obj] + + lit_blk_obj["uid"] = str(env.new_serialno("console")) + # Only add the tabbed UI if there is actually a Windows-specific + # version of the CLI example. + win_content = code_block_to_win(self.content) + if win_content is None: + lit_blk_obj["win_console_text"] = None + else: + self.content = win_content + lit_blk_obj["win_console_text"] = super().run()[0].rawsource + + # Replace the literal_node object returned by Sphinx's CodeBlock with + # the ConsoleNode wrapper. + return [ConsoleNode(lit_blk_obj)] + + +def html_page_context_hook(app, pagename, templatename, context, doctree): + # Put a bool on the context used to render the template. It's used to + # control inclusion of console-tabs.css and activation of the JavaScript. + # This way it's include only from HTML files rendered from reST files where + # the ConsoleDirective is used. + context["include_console_assets"] = getattr( + doctree, "_console_directive_used_flag", False + ) + + +def default_role_error( + name, rawtext, text, lineno, inliner, options=None, content=None +): + msg = ( + "Default role used (`single backticks`): %s. Did you mean to use two " + "backticks for ``code``, or miss an underscore for a `link`_ ?" % rawtext + ) + logger.warning(msg, location=(inliner.document.current_source, lineno)) + return [nodes.Text(text)], [] diff --git a/testbed/django__django/docs/_theme/djangodocs-epub/epub-cover.html b/testbed/django__django/docs/_theme/djangodocs-epub/epub-cover.html new file mode 100644 index 0000000000000000000000000000000000000000..e7ea031244166c69311345173ec97ac77874dde4 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs-epub/epub-cover.html @@ -0,0 +1,10 @@ +{%- extends "epub/epub-cover.html" %} + +{% block content %} +
+

Django Documentation

+

Release {{ release }}

+

{{ copyright }}

+

{{ last_updated }}

+
+{% endblock %} diff --git a/testbed/django__django/docs/_theme/djangodocs-epub/static/epub.css b/testbed/django__django/docs/_theme/djangodocs-epub/static/epub.css new file mode 100644 index 0000000000000000000000000000000000000000..7db68b53fb1a78c5b2aaeede04820b809678b729 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs-epub/static/epub.css @@ -0,0 +1,66 @@ +h1 { margin-top: 0; } + +/* Keep lists a bit narrow to maximize page estate regarding width. */ +ol, ul { + margin: 0; + padding: 0 0 0 1.3em; +} + +/* Images should never exceed the width of the page. */ +img { max-width: 100%; } + +/* Don't display URL after links, this is not print. */ +.link-target { display: none; } + +/* This is the front cover page of the book. */ +.epub-cover { text-align: center; } +.epub-cover h1 { margin: 4em 0 0 0; } +.epub-cover h2 { margin: 1em 0; } +.epub-cover h3 { margin: 3em 0 2em 0; } + +/* Code examples should never exceed the width of the page, so wrap instead. */ +pre, span.pre { white-space: pre-wrap; } + +pre { + background-color: #f6f6f6; + border: 0; + padding: 0.5em; + font-size: 90%; +} + +/* Header for some code blocks. */ +.code-block-caption { + background-color: #393939; + color: white; + margin: 0; + padding: 0.5em; + font: bold 90% monospace; +} +.literal-block-wrapper pre { + margin-top: 0; +} + +a:link, a:visited { color: #396623; } +a:hover { color: #1d3311; } + +/* Use special styled note boxes from the default theme, but with the left side +fitted after the icon, to allow text resizing with breaking. */ +.note, .admonition { + background-position: 9px 0.8em; + background-repeat: no-repeat; + padding: 0.8em 1em 0.8em 65px; + margin: 1em 0; + border: 0.01em solid black; +} + +.note, .admonition { background-image: url(docicons-note.png); } +div.admonition-philosophy { background-image: url(docicons-philosophy.png); } +div.admonition-behind-the-scenes { background-image: url(docicons-behindscenes.png); } +.admonition.warning { background-image: url(docicons-warning.png); } + +.admonition-title { + font-weight: bold; + margin: 0; +} + +.admonition .last { margin-bottom: 0; } diff --git a/testbed/django__django/docs/_theme/djangodocs-epub/theme.conf b/testbed/django__django/docs/_theme/djangodocs-epub/theme.conf new file mode 100644 index 0000000000000000000000000000000000000000..8fa091823a66d2ffa00bdf7a28b4e0b1e7af1491 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs-epub/theme.conf @@ -0,0 +1,8 @@ +[theme] +inherit = epub +stylesheet = epub.css +pygments_style = trac + +[options] +relbar1 = false +footer = false diff --git a/testbed/django__django/docs/_theme/djangodocs/genindex.html b/testbed/django__django/docs/_theme/djangodocs/genindex.html new file mode 100644 index 0000000000000000000000000000000000000000..032b70df8fd36c4caeed5f8ba5f7ff86d9c192ec --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/genindex.html @@ -0,0 +1,4 @@ +{% extends "basic/genindex.html" %} + +{% block bodyclass %}{% endblock %} +{% block sidebarwrapper %}{% endblock %} diff --git a/testbed/django__django/docs/_theme/djangodocs/layout.html b/testbed/django__django/docs/_theme/djangodocs/layout.html new file mode 100644 index 0000000000000000000000000000000000000000..487c2b49220f891db9b97b0fb63f28ff7e7bde67 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/layout.html @@ -0,0 +1,147 @@ +{% extends "basic/layout.html" %} + +{%- macro secondnav() %} + {%- if prev %} + « previous + {{ reldelim2 }} + {%- endif %} + {%- if parents %} + up + {%- else %} + up + {%- endif %} + {%- if next %} + {{ reldelim2 }} + next » + {%- endif %} +{%- endmacro %} + +{% block extrahead %} +{# When building htmlhelp (CHM format) disable jQuery inclusion, #} +{# as it causes problems in compiled CHM files. #} +{% if builder != "htmlhelp" %} +{{ super() }} + + +{% endif %} +{%- if include_console_assets -%} + +{%- endif -%} +{% endblock %} + +{% block document %} +
+
+

{{ docstitle }}

+ + +
+ +
+
+
+
+ {% block body %}{% endblock %} +
+
+
+ {% block sidebarwrapper %} + {% if pagename != 'index' %} + + {% endif %} + {% endblock %} +
+ +
+ +
+
+{% endblock %} + +{% block sidebarrel %} +

Browse

+ +

You are here:

+ +{% endblock %} + +{# Empty some default blocks out #} +{% block relbar1 %}{% endblock %} +{% block relbar2 %}{% endblock %} +{% block sidebar1 %}{% endblock %} +{% block sidebar2 %}{% endblock %} +{% block footer %}{% endblock %} diff --git a/testbed/django__django/docs/_theme/djangodocs/modindex.html b/testbed/django__django/docs/_theme/djangodocs/modindex.html new file mode 100644 index 0000000000000000000000000000000000000000..ca5a2d460ca53ad70a183bfe51be914748958e8a --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/modindex.html @@ -0,0 +1,3 @@ +{% extends "basic/modindex.html" %} +{% block bodyclass %}{% endblock %} +{% block sidebarwrapper %}{% endblock %} diff --git a/testbed/django__django/docs/_theme/djangodocs/search.html b/testbed/django__django/docs/_theme/djangodocs/search.html new file mode 100644 index 0000000000000000000000000000000000000000..4fdc7f6a84a2907f1a182c36d921436605888501 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/search.html @@ -0,0 +1,3 @@ +{% extends "basic/search.html" %} +{% block bodyclass %}{% endblock %} +{% block sidebarwrapper %}{% endblock %} diff --git a/testbed/django__django/docs/_theme/djangodocs/static/console-tabs.css b/testbed/django__django/docs/_theme/djangodocs/static/console-tabs.css new file mode 100644 index 0000000000000000000000000000000000000000..c13ec7b1ac48f1ee3a8f0eb6fd4325a8bf66215e --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/console-tabs.css @@ -0,0 +1,46 @@ +@import url("{{ pathto('_static/fontawesome/css/fa-brands.min.css', 1) }}"); + +.console-block { + text-align: right; +} + +.console-block *:before, +.console-block *:after { + box-sizing: border-box; +} + +.console-block > section { + display: none; + text-align: left; +} + +.console-block > input.c-tab-unix, +.console-block > input.c-tab-win { + display: none; +} + +.console-block > label { + display: inline-block; + padding: 4px 8px; + font-weight: normal; + text-align: center; + color: #bbb; + border: 1px solid transparent; + font-family: fontawesome; +} + +.console-block > input:checked + label { + color: #555; + border: 1px solid #ddd; + border-top: 2px solid #ab5603; + border-bottom: 1px solid #fff; +} + +.console-block > .c-tab-unix:checked ~ .c-content-unix, +.console-block > .c-tab-win:checked ~ .c-content-win { + display: block; +} + +.console-block pre { + margin-top: 0px; +} diff --git a/testbed/django__django/docs/_theme/djangodocs/static/default.css b/testbed/django__django/docs/_theme/djangodocs/static/default.css new file mode 100644 index 0000000000000000000000000000000000000000..8f1e38f9e7d2ad0b4f246e0a1f2eb27a45af5461 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/default.css @@ -0,0 +1,3 @@ +@import url(reset-fonts-grids.css); +@import url(djangodocs.css); +@import url(homepage.css); diff --git a/testbed/django__django/docs/_theme/djangodocs/static/djangodocs.css b/testbed/django__django/docs/_theme/djangodocs/static/djangodocs.css new file mode 100644 index 0000000000000000000000000000000000000000..0b6a8b9ad3bcf2253c7a98c7ea60d40a258a5eee --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/djangodocs.css @@ -0,0 +1,145 @@ +/*** setup ***/ +html { background:#092e20;} +body { font:12px/1.5 Verdana,sans-serif; background:#092e20; color: white;} +#custom-doc { width:76.54em;*width:74.69em;min-width:995px; max-width:100em; margin:auto; text-align:left; padding-top:16px; margin-top:0;} +#hd { padding: 4px 0 12px 0; } +#bd { background:#234F32; } +#ft { color:#487858; font-size:90%; padding-bottom: 2em; } + +/*** links ***/ +a {text-decoration: none;} +a img {border: none;} +a:link, a:visited { color:#ffc757; } +#bd a:link, #bd a:visited { color:#ab5603; text-decoration:underline; } +#bd #sidebar a:link, #bd #sidebar a:visited { color:#ffc757; text-decoration:none; } +a:hover { color:#ffe761; } +#bd a:hover { background-color:#E0FFB8; color:#234f32; text-decoration:none; } +#bd #sidebar a:hover { color:#ffe761; background:none; } +h2 a, h3 a, h4 a { text-decoration:none !important; } +a.reference em { font-style: normal; } + +/*** sidebar ***/ +#sidebar div.sphinxsidebarwrapper { font-size:92%; margin-right: 14px; } +#sidebar h3, #sidebar h4 { color: white; font-size: 125%; } +#sidebar a { color: white; } +#sidebar ul ul { margin-top:0; margin-bottom:0; } +#sidebar li { margin-top: 0.2em; margin-bottom: 0.2em; } + +/*** nav ***/ +div.nav { margin: 0; font-size: 11px; text-align: right; color: #487858;} +#hd div.nav { margin-top: -27px; } +#ft div.nav { margin-bottom: -18px; } +#hd h1 a { color: white; } +#global-nav { position:absolute; top:5px; margin-left: -5px; padding:7px 0; color:#263E2B; } +#global-nav a:link, #global-nav a:visited {color:#487858;} +#global-nav a {padding:0 4px;} +#global-nav a.about {padding-left:0;} +#global-nav:hover {color:#fff;} +#global-nav:hover a:link, #global-nav:hover a:visited { color:#ffc757; } + +/*** content ***/ +#yui-main div.yui-b { position: relative; } +#yui-main div.yui-b { margin: 0 0 0 20px; background: white; color: black; padding: 0.3em 2em 1em 2em; } + +/*** basic styles ***/ +dd { margin-left:15px; } +h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12 { margin-top:1em; font-family:"Trebuchet MS",sans-serif; font-weight:normal; } +h1 { font-size:218%; margin-top:0.6em; margin-bottom:.4em; line-height:1.1em; } +h2 { font-size:175%; margin-bottom:.6em; line-height:1.2em; color:#092e20; } +h3 { font-size:150%; font-weight:bold; margin-bottom:.2em; color:#487858; } +h4 { font-size:125%; font-weight:bold; margin-top:1.5em; margin-bottom:3px; } +h5 { font-size:110%; font-weight:bold; margin-top:1em; margin-bottom:3px; } +h6,h7,h8,h9,h10,h11,h12 { font-weight:bold; margin-bottom:3px; } +div.figure { text-align: center; } +div.figure p.caption { font-size:1em; margin-top:0; margin-bottom:1.5em; color: #555;} +hr { color:#ccc; background-color:#ccc; height:1px; border:0; } +p, ul, dl { margin-top:.6em; margin-bottom:1em; padding-bottom: 0.1em;} +#yui-main div.yui-b img { max-width: 50em; margin-left: auto; margin-right: auto; display: block; } +caption { font-size:1em; font-weight:bold; margin-top:0.5em; margin-bottom:0.5em; margin-left: 2px; text-align: center; } +blockquote { padding: 0 1em; margin: 1em 0; font:125%/1.2em "Trebuchet MS", sans-serif; color:#234f32; border-left:2px solid #94da3a; } +strong { font-weight: bold; } +em { font-style: italic; } +ins { font-weight: bold; text-decoration: none; } + +/*** lists ***/ +ul { padding-left:30px; } +ol { padding-left:30px; } +ol.arabic li { list-style-type: decimal; } +ul li { list-style-type:square; margin-bottom:.4em; } +ul ul li { list-style-type:disc; } +ul ul ul li { list-style-type:circle; } +ol li { margin-bottom: .4em; } +ul ul { padding-left:1.2em; } +ul ul ul { padding-left:1em; } +ul.linklist, ul.toc { padding-left:0; } +ul.toc ul { margin-left:.6em; } +ul.toc ul li { list-style-type:square; } +ul.toc ul ul li { list-style-type:disc; } +ul.linklist li, ul.toc li { list-style-type:none; } +dt { font-weight:bold; margin-top:.5em; font-size:1.1em; } +dd { margin-bottom:.8em; } +ol.toc { margin-bottom: 2em; } +ol.toc li { font-size:125%; padding: .5em; line-height:1.2em; clear: right; } +ol.toc li.b { background-color: #E0FFB8; } +ol.toc li a:hover { background-color: transparent !important; text-decoration: underline !important; } +ol.toc span.release-date { color:#487858; float: right; font-size: 85%; padding-right: .5em; } +ol.toc span.comment-count { font-size: 75%; color: #999; } + +/*** tables ***/ +table { color:#000; margin-bottom: 1em; width: 100%; } +table.docutils td p { margin-top:0; margin-bottom:.5em; } +table.docutils td, table.docutils th { border-bottom:1px solid #dfdfdf; padding:4px 2px;} +table.docutils thead th { border-bottom:2px solid #dfdfdf; text-align:left; font-weight: bold; white-space: nowrap; } +table.docutils thead th p { margin: 0; padding: 0; } +table.docutils { border-collapse:collapse; } + +/*** code blocks ***/ +.literal { color:#234f32; white-space:nowrap; } +dt > tt.literal { white-space: normal; } +#sidebar .literal { color:white; background:transparent; font-size:11px; } +h4 .literal { color: #234f32; font-size: 13px; } +pre { font-size:small; background:#E0FFB8; border:1px solid #94da3a; border-width:1px 0; margin: 1em 0; padding: .3em .4em; overflow: hidden; line-height: 1.3em; white-space: pre-wrap;} +dt .literal, table .literal { background:none; } +#bd a.reference { text-decoration: none; } +#bd a.reference tt.literal { border-bottom: 1px #234f32 dotted; } +div.code-block-caption { color: white; background-color: #234F32; margin: 0; padding: 2px 5px; width: 100%; font-family: monospace; font-size: small; line-height: 1.3em; } +div.code-block-caption .literal {color: white; } +div.literal-block-wrapper pre { margin-top: 0; } + +/* Restore colors of pygments hyperlinked code */ +#bd .highlight .k a:link, #bd .highlight .k a:visited { color: #000000; text-decoration: none; border-bottom: 1px dotted #000000; } +#bd .highlight .nf a:link, #bd .highlight .nf a:visited { color: #990000; text-decoration: none; border-bottom: 1px dotted #990000; } + + +/*** notes & admonitions ***/ +.note, .admonition { padding:.8em 1em .8em; margin: 1em 0; border:1px solid #94da3a; } +.admonition-title { font-weight:bold; margin-top:0 !important; margin-bottom:0 !important;} +.admonition .last { margin-bottom:0 !important; } +.note, .admonition { padding-left:65px; background:url(docicons-note.png) .8em .8em no-repeat;} +div.admonition-philosophy { padding-left:65px; background:url(docicons-philosophy.png) .8em .8em no-repeat;} +div.admonition-behind-the-scenes { padding-left:65px; background:url(docicons-behindscenes.png) .8em .8em no-repeat;} +.admonition.warning { background:url(docicons-warning.png) .8em .8em no-repeat; border:1px solid #ffc83c;} + +/*** versionadded/changes ***/ +div.versionadded, div.versionchanged { } +div.versionadded span.title, div.versionchanged span.title, span.versionmodified { font-weight: bold; } +div.versionadded, div.versionchanged, div.deprecated { color:#555; } + +/*** p-links ***/ +a.headerlink { color: #c60f0f; font-size: 0.8em; margin-left: 4px; opacity: 0; text-decoration: none; } +h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink { opacity: 1; } +a.headerlink:focus { opacity: 1; } + +/*** index ***/ +table.indextable td { text-align: left; vertical-align: top;} +table.indextable dl, table.indextable dd { margin-top: 0; margin-bottom: 0; } +table.indextable tr.pcap { height: 10px; } +table.indextable tr.cap { margin-top: 10px; background-color: #f2f2f2;} + +/*** page-specific overrides ***/ +div#contents ul { margin-bottom: 0;} +div#contents ul li { margin-bottom: 0;} +div#contents ul ul li { margin-top: 0.3em;} + +/*** IE hacks ***/ +* pre { width: 100%; } diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/LICENSE.txt b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..28c1c4bc730d7a0f9aabfcf2529555ca7ca8b83d --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/LICENSE.txt @@ -0,0 +1,34 @@ +Font Awesome Free License +------------------------- + +Font Awesome Free is free, open source, and GPL friendly. You can use it for +commercial projects, open source projects, or really almost whatever you want. +Full Font Awesome Free license: https://fontawesome.com/license. + +# Icons: CC BY 4.0 License (https://creativecommons.org/licenses/by/4.0/) +In the Font Awesome Free download, the CC BY 4.0 license applies to all icons +packaged as SVG and JS file types. + +# Fonts: SIL OFL 1.1 License (https://scripts.sil.org/OFL) +In the Font Awesome Free download, the SIL OLF license applies to all icons +packaged as web and desktop font files. + +# Code: MIT License (https://opensource.org/licenses/MIT) +In the Font Awesome Free download, the MIT license applies to all non-font and +non-icon files. + +# Attribution +Attribution is required by MIT, SIL OLF, and CC BY licenses. Downloaded Font +Awesome Free files already contain embedded comments with sufficient +attribution, so you shouldn't need to do anything additional when using these +files normally. + +We've kept attribution comments terse, so we ask that you do not actively work +to remove them from files, especially code. They're a great way for folks to +learn about Font Awesome. + +# Brand Icons +All brand icons are trademarks of their respective owners. The use of these +trademarks does not indicate endorsement of the trademark holder by Font +Awesome, nor vice versa. **Please do not use brand logos for any purpose except +to represent the company, product, or service to which they refer.** diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/README.md b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/README.md new file mode 100644 index 0000000000000000000000000000000000000000..72a373e34829c6b0cc524b10424604147e994838 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/README.md @@ -0,0 +1,7 @@ +# Font Awesome 5.0.4 + +Thanks for downloading Font Awesome! We're so excited you're here. + +Our documentation is available online. Just head here: + +https://fontawesome.com diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/css/fa-brands.min.css b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/css/fa-brands.min.css new file mode 100644 index 0000000000000000000000000000000000000000..244a01ef98338f22ab82de87b7662cafe913083d --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/css/fa-brands.min.css @@ -0,0 +1,5 @@ +/*! + * Font Awesome Free 5.0.4 by @fontawesome - http://fontawesome.com + * License - http://fontawesome.com/license (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) + */ +@font-face{font-family:Font Awesome\ 5 Brands;font-style:normal;font-weight:400;src:url(../webfonts/fa-brands-400.eot);src:url(../webfonts/fa-brands-400.eot?#iefix) format("embedded-opentype"),url(../webfonts/fa-brands-400.woff2) format("woff2"),url(../webfonts/fa-brands-400.woff) format("woff"),url(../webfonts/fa-brands-400.ttf) format("truetype"),url(../webfonts/fa-brands-400.svg#fontawesome) format("svg")}.fab{font-family:Font Awesome\ 5 Brands} \ No newline at end of file diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.eot b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.eot new file mode 100644 index 0000000000000000000000000000000000000000..45f12a121fd30ad41ca062c52f3739137910ca0f Binary files /dev/null and b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.eot differ diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.svg b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.svg new file mode 100644 index 0000000000000000000000000000000000000000..2f26609a1ab88270b42240fc29cbc87e2dcd8fe3 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.svg @@ -0,0 +1,996 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.ttf b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ed62125e4043eb5ad2dccdff0378110a11363809 Binary files /dev/null and b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.ttf differ diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.woff b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.woff new file mode 100644 index 0000000000000000000000000000000000000000..dc90ab137a7fe892340cfa643c3c10c4da207be0 Binary files /dev/null and b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.woff differ diff --git a/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.woff2 b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..d14f86eb8622da5d9155e15b4c9fec612d44345e Binary files /dev/null and b/testbed/django__django/docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.woff2 differ diff --git a/testbed/django__django/docs/_theme/djangodocs/static/homepage.css b/testbed/django__django/docs/_theme/djangodocs/static/homepage.css new file mode 100644 index 0000000000000000000000000000000000000000..3f69f01b2e760646ada7cdb5f180c7b106087afc --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/homepage.css @@ -0,0 +1,22 @@ +#index p.rubric { font-size:150%; font-weight:normal; margin-bottom:.2em; color:#487858; } + +#index div.section dt { font-weight: normal; } + +#index #s-getting-help { float: right; width: 35em; background: #E1ECE2; padding: 1em; margin: 2em 0 2em 2em; } +#index #s-getting-help h2 { margin: 0; } + +#index #s-django-documentation div.section div.section h3 { margin: 0; } +#index #s-django-documentation div.section div.section { background: #E1ECE2; padding: 1em; margin: 2em 0 2em 40.3em; } +#index #s-django-documentation div.section div.section a.reference { white-space: nowrap; } + +#index #s-using-django dl, +#index #s-add-on-contrib-applications dl, +#index #s-solving-specific-problems dl, +#index #s-reference dl + { float: left; width: 41em; } + +#index #s-add-on-contrib-applications, +#index #s-solving-specific-problems, +#index #s-reference, +#index #s-and-all-the-rest + { clear: left; } diff --git a/testbed/django__django/docs/_theme/djangodocs/static/reset-fonts-grids.css b/testbed/django__django/docs/_theme/djangodocs/static/reset-fonts-grids.css new file mode 100644 index 0000000000000000000000000000000000000000..f5238d7c91d665f383ba89eb5ac3cebc62d45130 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/static/reset-fonts-grids.css @@ -0,0 +1,8 @@ +/* +Copyright (c) 2008, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 2.5.1 +*/ +html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;font-variant:normal;}sup {vertical-align:text-top;}sub {vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}table {font-size:inherit;font:100%;}pre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%;} +body{text-align:center;}#ft{clear:both;}#doc,#doc2,#doc3,#doc4,.yui-t1,.yui-t2,.yui-t3,.yui-t4,.yui-t5,.yui-t6,.yui-t7{margin:auto;text-align:left;width:57.69em;*width:56.25em;min-width:750px;}#doc2{width:73.076em;*width:71.25em;}#doc3{margin:auto 10px;width:auto;}#doc4{width:74.923em;*width:73.05em;}.yui-b{position:relative;}.yui-b{_position:static;}#yui-main .yui-b{position:static;}#yui-main{width:100%;}.yui-t1 #yui-main,.yui-t2 #yui-main,.yui-t3 #yui-main{float:right;margin-left:-25em;}.yui-t4 #yui-main,.yui-t5 #yui-main,.yui-t6 #yui-main{float:left;margin-right:-25em;}.yui-t1 .yui-b{float:left;width:12.30769em;*width:12.00em;}.yui-t1 #yui-main .yui-b{margin-left:13.30769em;*margin-left:13.05em;}.yui-t2 .yui-b{float:left;width:13.8461em;*width:13.50em;}.yui-t2 #yui-main .yui-b{margin-left:14.8461em;*margin-left:14.55em;}.yui-t3 .yui-b{float:left;width:23.0769em;*width:22.50em;}.yui-t3 #yui-main .yui-b{margin-left:24.0769em;*margin-left:23.62em;}.yui-t4 .yui-b{float:right;width:13.8456em;*width:13.50em;}.yui-t4 #yui-main .yui-b{margin-right:14.8456em;*margin-right:14.55em;}.yui-t5 .yui-b{float:right;width:18.4615em;*width:18.00em;}.yui-t5 #yui-main .yui-b{margin-right:19.4615em;*margin-right:19.125em;}.yui-t6 .yui-b{float:right;width:23.0769em;*width:22.50em;}.yui-t6 #yui-main .yui-b{margin-right:24.0769em;*margin-right:23.62em;}.yui-t7 #yui-main .yui-b{display:block;margin:0 0 1em 0;}#yui-main .yui-b{float:none;width:auto;}.yui-gb .yui-u,.yui-g .yui-gb .yui-u,.yui-gb .yui-g,.yui-gb .yui-gb,.yui-gb .yui-gc,.yui-gb .yui-gd,.yui-gb .yui-ge,.yui-gb .yui-gf,.yui-gc .yui-u,.yui-gc .yui-g,.yui-gd .yui-u{float:left;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf,.yui-gc .yui-u,.yui-gd .yui-g,.yui-g .yui-gc .yui-u,.yui-ge .yui-u,.yui-ge .yui-g,.yui-gf .yui-g,.yui-gf .yui-u{float:right;}.yui-g div.first,.yui-gb div.first,.yui-gc div.first,.yui-gd div.first,.yui-ge div.first,.yui-gf div.first,.yui-g .yui-gc div.first,.yui-g .yui-ge div.first,.yui-gc div.first div.first{float:left;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf{width:49.1%;}.yui-gb .yui-u,.yui-g .yui-gb .yui-u,.yui-gb .yui-g,.yui-gb .yui-gb,.yui-gb .yui-gc,.yui-gb .yui-gd,.yui-gb .yui-ge,.yui-gb .yui-gf,.yui-gc .yui-u,.yui-gc .yui-g,.yui-gd .yui-u{width:32%;margin-left:1.99%;}.yui-gb .yui-u{*margin-left:1.9%;*width:31.9%;}.yui-gc div.first,.yui-gd .yui-u{width:66%;}.yui-gd div.first{width:32%;}.yui-ge div.first,.yui-gf .yui-u{width:74.2%;}.yui-ge .yui-u,.yui-gf div.first{width:24%;}.yui-g .yui-gb div.first,.yui-gb div.first,.yui-gc div.first,.yui-gd div.first{margin-left:0;}.yui-g .yui-g .yui-u,.yui-gb .yui-g .yui-u,.yui-gc .yui-g .yui-u,.yui-gd .yui-g .yui-u,.yui-ge .yui-g .yui-u,.yui-gf .yui-g .yui-u{width:49%;*width:48.1%;*margin-left:0;}.yui-g .yui-gb div.first,.yui-gb .yui-gb div.first{*margin-right:0;*width:32%;_width:31.7%;}.yui-g .yui-gc div.first,.yui-gd .yui-g{width:66%;}.yui-gb .yui-g div.first{*margin-right:4%;_margin-right:1.3%;}.yui-gb .yui-gc div.first,.yui-gb .yui-gd div.first{*margin-right:0;}.yui-gb .yui-gb .yui-u,.yui-gb .yui-gc .yui-u{*margin-left:1.8%;_margin-left:4%;}.yui-g .yui-gb .yui-u{_margin-left:1.0%;}.yui-gb .yui-gd .yui-u{*width:66%;_width:61.2%;}.yui-gb .yui-gd div.first{*width:31%;_width:29.5%;}.yui-g .yui-gc .yui-u,.yui-gb .yui-gc .yui-u{width:32%;_float:right;margin-right:0;_margin-left:0;}.yui-gb .yui-gc div.first{width:66%;*float:left;*margin-left:0;}.yui-gb .yui-ge .yui-u,.yui-gb .yui-gf .yui-u{margin:0;}.yui-gb .yui-gb .yui-u{_margin-left:.7%;}.yui-gb .yui-g div.first,.yui-gb .yui-gb div.first{*margin-left:0;}.yui-gc .yui-g .yui-u,.yui-gd .yui-g .yui-u{*width:48.1%;*margin-left:0;}s .yui-gb .yui-gd div.first{width:32%;}.yui-g .yui-gd div.first{_width:29.9%;}.yui-ge .yui-g{width:24%;}.yui-gf .yui-g{width:74.2%;}.yui-gb .yui-ge div.yui-u,.yui-gb .yui-gf div.yui-u{float:right;}.yui-gb .yui-ge div.first,.yui-gb .yui-gf div.first{float:left;}.yui-gb .yui-ge .yui-u,.yui-gb .yui-gf div.first{*width:24%;_width:20%;}.yui-gb .yui-ge div.first,.yui-gb .yui-gf .yui-u{*width:73.5%;_width:65.5%;}.yui-ge div.first .yui-gd .yui-u{width:65%;}.yui-ge div.first .yui-gd div.first{width:32%;}#bd:after,.yui-g:after,.yui-gb:after,.yui-gc:after,.yui-gd:after,.yui-ge:after,.yui-gf:after{content:".";display:block;height:0;clear:both;visibility:hidden;}#bd,.yui-g,.yui-gb,.yui-gc,.yui-gd,.yui-ge,.yui-gf{zoom:1;} \ No newline at end of file diff --git a/testbed/django__django/docs/_theme/djangodocs/theme.conf b/testbed/django__django/docs/_theme/djangodocs/theme.conf new file mode 100644 index 0000000000000000000000000000000000000000..be43c723ae61038f3d1bdf265ba7db3c19604c63 --- /dev/null +++ b/testbed/django__django/docs/_theme/djangodocs/theme.conf @@ -0,0 +1,4 @@ +[theme] +inherit = basic +stylesheet = default.css +pygments_style = trac diff --git a/testbed/django__django/docs/faq/admin.txt b/testbed/django__django/docs/faq/admin.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c6f7a12c7e0fd1a447a5f3248a7198f2efd538c --- /dev/null +++ b/testbed/django__django/docs/faq/admin.txt @@ -0,0 +1,111 @@ +============== +FAQ: The admin +============== + +I can't log in. When I enter a valid username and password, it just brings up the login page again, with no error messages. +=========================================================================================================================== + +The login cookie isn't being set correctly, because the domain of the cookie +sent out by Django doesn't match the domain in your browser. Try setting the +:setting:`SESSION_COOKIE_DOMAIN` setting to match your domain. For example, if +you're going to "https://www.example.com/admin/" in your browser, set +``SESSION_COOKIE_DOMAIN = 'www.example.com'``. + +I can't log in. When I enter a valid username and password, it brings up the login page again, with a "Please enter a correct username and password" error. +=========================================================================================================================================================== + +If you're sure your username and password are correct, make sure your user +account has :attr:`~django.contrib.auth.models.User.is_active` and +:attr:`~django.contrib.auth.models.User.is_staff` set to True. The admin site +only allows access to users with those two fields both set to True. + +How do I automatically set a field's value to the user who last edited the object in the admin? +=============================================================================================== + +The :class:`~django.contrib.admin.ModelAdmin` class provides customization hooks +that allow you to transform an object as it saved, using details from the +request. By extracting the current user from the request, and customizing the +:meth:`~django.contrib.admin.ModelAdmin.save_model` hook, you can update an +object to reflect the user that edited it. See :ref:`the documentation on +ModelAdmin methods ` for an example. + +How do I limit admin access so that objects can only be edited by the users who created them? +============================================================================================= + +The :class:`~django.contrib.admin.ModelAdmin` class also provides customization +hooks that allow you to control the visibility and editability of objects in the +admin. Using the same trick of extracting the user from the request, the +:meth:`~django.contrib.admin.ModelAdmin.get_queryset` and +:meth:`~django.contrib.admin.ModelAdmin.has_change_permission` can be used to +control the visibility and editability of objects in the admin. + +My admin-site CSS and images showed up fine using the development server, but they're not displaying when using mod_wsgi. +========================================================================================================================= + +See :ref:`serving the admin files ` +in the "How to use Django with mod_wsgi" documentation. + +My "list_filter" contains a ManyToManyField, but the filter doesn't display. +============================================================================ + +Django won't bother displaying the filter for a ``ManyToManyField`` if there +are no related objects. + +For example, if your :attr:`~django.contrib.admin.ModelAdmin.list_filter` +includes :doc:`sites `, and there are no sites in your +database, it won't display a "Site" filter. In that case, filtering by site +would be meaningless. + +Some objects aren't appearing in the admin. +=========================================== + +Inconsistent row counts may be caused by missing foreign key values or a +foreign key field incorrectly set to :attr:`null=False +`. If you have a record with a +:class:`~django.db.models.ForeignKey` pointing to a nonexistent object and +that foreign key is included is +:attr:`~django.contrib.admin.ModelAdmin.list_display`, the record will not be +shown in the admin changelist because the Django model is declaring an +integrity constraint that is not implemented at the database level. + +How can I customize the functionality of the admin interface? +============================================================= + +You've got several options. If you want to piggyback on top of an add/change +form that Django automatically generates, you can attach arbitrary JavaScript +modules to the page via the model's class Admin :ref:`js parameter +`. That parameter is a list of URLs, as strings, +pointing to JavaScript modules that will be included within the admin form via +a `` + +Setting the token on the AJAX request +------------------------------------- + +Finally, you'll need to set the header on your AJAX request. Using the +`fetch()`_ API: + +.. code-block:: javascript + + const request = new Request( + /* URL */, + { + method: 'POST', + headers: {'X-CSRFToken': csrftoken}, + mode: 'same-origin' // Do not send CSRF token to another domain. + } + ); + fetch(request).then(function(response) { + // ... + }); + +.. _fetch(): https://developer.mozilla.org/en-US/docs/Web/API/fetch + +Using CSRF protection in Jinja2 templates +========================================= + +Django's :class:`~django.template.backends.jinja2.Jinja2` template backend +adds ``{{ csrf_input }}`` to the context of all templates which is equivalent +to ``{% csrf_token %}`` in the Django template language. For example: + +.. code-block:: html+jinja + +
{{ csrf_input }} + +Using the decorator method +========================== + +Rather than adding ``CsrfViewMiddleware`` as a blanket protection, you can use +the :func:`~django.views.decorators.csrf.csrf_protect` decorator, which has +exactly the same functionality, on particular views that need the protection. +It must be used **both** on views that insert the CSRF token in the output, and +on those that accept the POST form data. (These are often the same view +function, but not always). + +Use of the decorator by itself is **not recommended**, since if you forget to +use it, you will have a security hole. The 'belt and braces' strategy of using +both is fine, and will incur minimal overhead. + +.. _csrf-rejected-requests: + +Handling rejected requests +========================== + +By default, a '403 Forbidden' response is sent to the user if an incoming +request fails the checks performed by ``CsrfViewMiddleware``. This should +usually only be seen when there is a genuine Cross Site Request Forgery, or +when, due to a programming error, the CSRF token has not been included with a +POST form. + +The error page, however, is not very friendly, so you may want to provide your +own view for handling this condition. To do this, set the +:setting:`CSRF_FAILURE_VIEW` setting. + +CSRF failures are logged as warnings to the :ref:`django.security.csrf +` logger. + +Using CSRF protection with caching +================================== + +If the :ttag:`csrf_token` template tag is used by a template (or the +``get_token`` function is called some other way), ``CsrfViewMiddleware`` will +add a cookie and a ``Vary: Cookie`` header to the response. This means that the +middleware will play well with the cache middleware if it is used as instructed +(``UpdateCacheMiddleware`` goes before all other middleware). + +However, if you use cache decorators on individual views, the CSRF middleware +will not yet have been able to set the Vary header or the CSRF cookie, and the +response will be cached without either one. In this case, on any views that +will require a CSRF token to be inserted you should use the +:func:`django.views.decorators.csrf.csrf_protect` decorator first:: + + from django.views.decorators.cache import cache_page + from django.views.decorators.csrf import csrf_protect + + + @cache_page(60 * 15) + @csrf_protect + def my_view(request): + ... + +If you are using class-based views, you can refer to :ref:`Decorating +class-based views`. + +Testing and CSRF protection +=========================== + +The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view +functions, due to the need for the CSRF token which must be sent with every POST +request. For this reason, Django's HTTP client for tests has been modified to +set a flag on requests which relaxes the middleware and the ``csrf_protect`` +decorator so that they no longer rejects requests. In every other respect +(e.g. sending cookies etc.), they behave the same. + +If, for some reason, you *want* the test client to perform CSRF +checks, you can create an instance of the test client that enforces +CSRF checks: + +.. code-block:: pycon + + >>> from django.test import Client + >>> csrf_client = Client(enforce_csrf_checks=True) + +Edge cases +========== + +Certain views can have unusual requirements that mean they don't fit the normal +pattern envisaged here. A number of utilities can be useful in these +situations. The scenarios they might be needed in are described in the following +section. + +Disabling CSRF protection for just a few views +---------------------------------------------- + +Most views requires CSRF protection, but a few do not. + +Solution: rather than disabling the middleware and applying ``csrf_protect`` to +all the views that need it, enable the middleware and use +:func:`~django.views.decorators.csrf.csrf_exempt`. + +Setting the token when ``CsrfViewMiddleware.process_view()`` is not used +------------------------------------------------------------------------ + +There are cases when ``CsrfViewMiddleware.process_view`` may not have run +before your view is run - 404 and 500 handlers, for example - but you still +need the CSRF token in a form. + +Solution: use :func:`~django.views.decorators.csrf.requires_csrf_token` + +Including the CSRF token in an unprotected view +----------------------------------------------- + +There may be some views that are unprotected and have been exempted by +``csrf_exempt``, but still need to include the CSRF token. + +Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by +:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token`` +should be the innermost decorator). + +Protecting a view for only one path +----------------------------------- + +A view needs CSRF protection under one set of conditions only, and mustn't have +it for the rest of the time. + +Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` for the whole +view function, and :func:`~django.views.decorators.csrf.csrf_protect` for the +path within it that needs protection. Example:: + + from django.views.decorators.csrf import csrf_exempt, csrf_protect + + + @csrf_exempt + def my_view(request): + @csrf_protect + def protected_path(request): + do_something() + + if some_condition(): + return protected_path(request) + else: + do_something_else() + +Protecting a page that uses AJAX without an HTML form +----------------------------------------------------- + +A page makes a POST request via AJAX, and the page does not have an HTML form +with a :ttag:`csrf_token` that would cause the required CSRF cookie to be sent. + +Solution: use :func:`~django.views.decorators.csrf.ensure_csrf_cookie` on the +view that sends the page. + +CSRF protection in reusable applications +======================================== + +Because it is possible for the developer to turn off the ``CsrfViewMiddleware``, +all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure +the security of these applications against CSRF. It is recommended that the +developers of other reusable apps that want the same guarantees also use the +``csrf_protect`` decorator on their views. diff --git a/testbed/django__django/docs/howto/custom-file-storage.txt b/testbed/django__django/docs/howto/custom-file-storage.txt new file mode 100644 index 0000000000000000000000000000000000000000..de44a1d9385bcda7fe169880a97bd34b7a08f6a0 --- /dev/null +++ b/testbed/django__django/docs/howto/custom-file-storage.txt @@ -0,0 +1,141 @@ +=================================== +How to write a custom storage class +=================================== + +.. currentmodule:: django.core.files.storage + +If you need to provide custom file storage -- a common example is storing files +on some remote system -- you can do so by defining a custom storage class. +You'll need to follow these steps: + +#. Your custom storage system must be a subclass of + ``django.core.files.storage.Storage``:: + + from django.core.files.storage import Storage + + + class MyStorage(Storage): + ... + +#. Django must be able to instantiate your storage system without any arguments. + This means that any settings should be taken from ``django.conf.settings``:: + + from django.conf import settings + from django.core.files.storage import Storage + + + class MyStorage(Storage): + def __init__(self, option=None): + if not option: + option = settings.CUSTOM_STORAGE_OPTIONS + ... + +#. Your storage class must implement the :meth:`_open()` and :meth:`_save()` + methods, along with any other methods appropriate to your storage class. See + below for more on these methods. + + In addition, if your class provides local file storage, it must override + the ``path()`` method. + +#. Your storage class must be :ref:`deconstructible ` + so it can be serialized when it's used on a field in a migration. As long + as your field has arguments that are themselves + :ref:`serializable `, you can use the + ``django.utils.deconstruct.deconstructible`` class decorator for this + (that's what Django uses on FileSystemStorage). + +By default, the following methods raise ``NotImplementedError`` and will +typically have to be overridden: + +* :meth:`Storage.delete` +* :meth:`Storage.exists` +* :meth:`Storage.listdir` +* :meth:`Storage.size` +* :meth:`Storage.url` + +Note however that not all these methods are required and may be deliberately +omitted. As it happens, it is possible to leave each method unimplemented and +still have a working Storage. + +By way of example, if listing the contents of certain storage backends turns +out to be expensive, you might decide not to implement ``Storage.listdir()``. + +Another example would be a backend that only handles writing to files. In this +case, you would not need to implement any of the above methods. + +Ultimately, which of these methods are implemented is up to you. Leaving some +methods unimplemented will result in a partial (possibly broken) interface. + +You'll also usually want to use hooks specifically designed for custom storage +objects. These are: + +.. method:: _open(name, mode='rb') + +**Required**. + +Called by ``Storage.open()``, this is the actual mechanism the storage class +uses to open the file. This must return a ``File`` object, though in most cases, +you'll want to return some subclass here that implements logic specific to the +backend storage system. + +.. method:: _save(name, content) + +Called by ``Storage.save()``. The ``name`` will already have gone through +``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a +``File`` object itself. + +Should return the actual name of name of the file saved (usually the ``name`` +passed in, but if the storage needs to change the file name return the new name +instead). + +.. method:: get_valid_name(name) + +Returns a filename suitable for use with the underlying storage system. The +``name`` argument passed to this method is either the original filename sent to +the server or, if ``upload_to`` is a callable, the filename returned by that +method after any path information is removed. Override this to customize how +non-standard characters are converted to safe filenames. + +The code provided on ``Storage`` retains only alpha-numeric characters, periods +and underscores from the original filename, removing everything else. + +.. method:: get_alternative_name(file_root, file_ext) + +Returns an alternative filename based on the ``file_root`` and ``file_ext`` +parameters. By default, an underscore plus a random 7 character alphanumeric +string is appended to the filename before the extension. + +.. method:: get_available_name(name, max_length=None) + +Returns a filename that is available in the storage mechanism, possibly taking +the provided filename into account. The ``name`` argument passed to this method +will have already cleaned to a filename valid for the storage system, according +to the ``get_valid_name()`` method described above. + +The length of the filename will not exceed ``max_length``, if provided. If a +free unique filename cannot be found, a :exc:`SuspiciousFileOperation +` exception is raised. + +If a file with ``name`` already exists, ``get_alternative_name()`` is called to +obtain an alternative name. + +.. _using-custom-storage-engine: + +Use your custom storage engine +============================== + +.. versionadded:: 4.2 + +The first step to using your custom storage with Django is to tell Django about +the file storage backend you'll be using. This is done using the +:setting:`STORAGES` setting. This setting maps storage aliases, which are a way +to refer to a specific storage throughout Django, to a dictionary of settings +for that specific storage backend. The settings in the inner dictionaries are +described fully in the :setting:`STORAGES` documentation. + +Storages are then accessed by alias from from the +:data:`django.core.files.storage.storages` dictionary:: + + from django.core.files.storage import storages + + example_storage = storages["example"] diff --git a/testbed/django__django/docs/howto/custom-lookups.txt b/testbed/django__django/docs/howto/custom-lookups.txt new file mode 100644 index 0000000000000000000000000000000000000000..61ec9295ebeeba21e45795112ff79a9676aacc95 --- /dev/null +++ b/testbed/django__django/docs/howto/custom-lookups.txt @@ -0,0 +1,354 @@ +=========================== +How to write custom lookups +=========================== + +.. currentmodule:: django.db.models + +Django offers a wide variety of :ref:`built-in lookups ` for +filtering (for example, ``exact`` and ``icontains``). This documentation +explains how to write custom lookups and how to alter the working of existing +lookups. For the API references of lookups, see the :doc:`/ref/models/lookups`. + +A lookup example +================ + +Let's start with a small custom lookup. We will write a custom lookup ``ne`` +which works opposite to ``exact``. ``Author.objects.filter(name__ne='Jack')`` +will translate to the SQL: + +.. code-block:: sql + + "author"."name" <> 'Jack' + +This SQL is backend independent, so we don't need to worry about different +databases. + +There are two steps to making this work. Firstly we need to implement the +lookup, then we need to tell Django about it:: + + from django.db.models import Lookup + + + class NotEqual(Lookup): + lookup_name = "ne" + + def as_sql(self, compiler, connection): + lhs, lhs_params = self.process_lhs(compiler, connection) + rhs, rhs_params = self.process_rhs(compiler, connection) + params = lhs_params + rhs_params + return "%s <> %s" % (lhs, rhs), params + +To register the ``NotEqual`` lookup we will need to call ``register_lookup`` on +the field class we want the lookup to be available for. In this case, the lookup +makes sense on all ``Field`` subclasses, so we register it with ``Field`` +directly:: + + from django.db.models import Field + + Field.register_lookup(NotEqual) + +Lookup registration can also be done using a decorator pattern:: + + from django.db.models import Field + + + @Field.register_lookup + class NotEqualLookup(Lookup): + ... + +We can now use ``foo__ne`` for any field ``foo``. You will need to ensure that +this registration happens before you try to create any querysets using it. You +could place the implementation in a ``models.py`` file, or register the lookup +in the ``ready()`` method of an ``AppConfig``. + +Taking a closer look at the implementation, the first required attribute is +``lookup_name``. This allows the ORM to understand how to interpret ``name__ne`` +and use ``NotEqual`` to generate the SQL. By convention, these names are always +lowercase strings containing only letters, but the only hard requirement is +that it must not contain the string ``__``. + +We then need to define the ``as_sql`` method. This takes a ``SQLCompiler`` +object, called ``compiler``, and the active database connection. +``SQLCompiler`` objects are not documented, but the only thing we need to know +about them is that they have a ``compile()`` method which returns a tuple +containing an SQL string, and the parameters to be interpolated into that +string. In most cases, you don't need to use it directly and can pass it on to +``process_lhs()`` and ``process_rhs()``. + +A ``Lookup`` works against two values, ``lhs`` and ``rhs``, standing for +left-hand side and right-hand side. The left-hand side is usually a field +reference, but it can be anything implementing the :ref:`query expression API +`. The right-hand is the value given by the user. In the +example ``Author.objects.filter(name__ne='Jack')``, the left-hand side is a +reference to the ``name`` field of the ``Author`` model, and ``'Jack'`` is the +right-hand side. + +We call ``process_lhs`` and ``process_rhs`` to convert them into the values we +need for SQL using the ``compiler`` object described before. These methods +return tuples containing some SQL and the parameters to be interpolated into +that SQL, just as we need to return from our ``as_sql`` method. In the above +example, ``process_lhs`` returns ``('"author"."name"', [])`` and +``process_rhs`` returns ``('"%s"', ['Jack'])``. In this example there were no +parameters for the left hand side, but this would depend on the object we have, +so we still need to include them in the parameters we return. + +Finally we combine the parts into an SQL expression with ``<>``, and supply all +the parameters for the query. We then return a tuple containing the generated +SQL string and the parameters. + +A transformer example +===================== + +The custom lookup above is great, but in some cases you may want to be able to +chain lookups together. For example, let's suppose we are building an +application where we want to make use of the ``abs()`` operator. +We have an ``Experiment`` model which records a start value, end value, and the +change (start - end). We would like to find all experiments where the change +was equal to a certain amount (``Experiment.objects.filter(change__abs=27)``), +or where it did not exceed a certain amount +(``Experiment.objects.filter(change__abs__lt=27)``). + +.. note:: + This example is somewhat contrived, but it nicely demonstrates the range of + functionality which is possible in a database backend independent manner, + and without duplicating functionality already in Django. + +We will start by writing an ``AbsoluteValue`` transformer. This will use the SQL +function ``ABS()`` to transform the value before comparison:: + + from django.db.models import Transform + + + class AbsoluteValue(Transform): + lookup_name = "abs" + function = "ABS" + +Next, let's register it for ``IntegerField``:: + + from django.db.models import IntegerField + + IntegerField.register_lookup(AbsoluteValue) + +We can now run the queries we had before. +``Experiment.objects.filter(change__abs=27)`` will generate the following SQL: + +.. code-block:: sql + + SELECT ... WHERE ABS("experiments"."change") = 27 + +By using ``Transform`` instead of ``Lookup`` it means we are able to chain +further lookups afterward. So +``Experiment.objects.filter(change__abs__lt=27)`` will generate the following +SQL: + +.. code-block:: sql + + SELECT ... WHERE ABS("experiments"."change") < 27 + +Note that in case there is no other lookup specified, Django interprets +``change__abs=27`` as ``change__abs__exact=27``. + +This also allows the result to be used in ``ORDER BY`` and ``DISTINCT ON`` +clauses. For example ``Experiment.objects.order_by('change__abs')`` generates: + +.. code-block:: sql + + SELECT ... ORDER BY ABS("experiments"."change") ASC + +And on databases that support distinct on fields (such as PostgreSQL), +``Experiment.objects.distinct('change__abs')`` generates: + +.. code-block:: sql + + SELECT ... DISTINCT ON ABS("experiments"."change") + +When looking for which lookups are allowable after the ``Transform`` has been +applied, Django uses the ``output_field`` attribute. We didn't need to specify +this here as it didn't change, but supposing we were applying ``AbsoluteValue`` +to some field which represents a more complex type (for example a point +relative to an origin, or a complex number) then we may have wanted to specify +that the transform returns a ``FloatField`` type for further lookups. This can +be done by adding an ``output_field`` attribute to the transform:: + + from django.db.models import FloatField, Transform + + + class AbsoluteValue(Transform): + lookup_name = "abs" + function = "ABS" + + @property + def output_field(self): + return FloatField() + +This ensures that further lookups like ``abs__lte`` behave as they would for +a ``FloatField``. + +Writing an efficient ``abs__lt`` lookup +======================================= + +When using the above written ``abs`` lookup, the SQL produced will not use +indexes efficiently in some cases. In particular, when we use +``change__abs__lt=27``, this is equivalent to ``change__gt=-27`` AND +``change__lt=27``. (For the ``lte`` case we could use the SQL ``BETWEEN``). + +So we would like ``Experiment.objects.filter(change__abs__lt=27)`` to generate +the following SQL: + +.. code-block:: sql + + SELECT .. WHERE "experiments"."change" < 27 AND "experiments"."change" > -27 + +The implementation is:: + + from django.db.models import Lookup + + + class AbsoluteValueLessThan(Lookup): + lookup_name = "lt" + + def as_sql(self, compiler, connection): + lhs, lhs_params = compiler.compile(self.lhs.lhs) + rhs, rhs_params = self.process_rhs(compiler, connection) + params = lhs_params + rhs_params + lhs_params + rhs_params + return "%s < %s AND %s > -%s" % (lhs, rhs, lhs, rhs), params + + + AbsoluteValue.register_lookup(AbsoluteValueLessThan) + +There are a couple of notable things going on. First, ``AbsoluteValueLessThan`` +isn't calling ``process_lhs()``. Instead it skips the transformation of the +``lhs`` done by ``AbsoluteValue`` and uses the original ``lhs``. That is, we +want to get ``"experiments"."change"`` not ``ABS("experiments"."change")``. +Referring directly to ``self.lhs.lhs`` is safe as ``AbsoluteValueLessThan`` +can be accessed only from the ``AbsoluteValue`` lookup, that is the ``lhs`` +is always an instance of ``AbsoluteValue``. + +Notice also that as both sides are used multiple times in the query the params +need to contain ``lhs_params`` and ``rhs_params`` multiple times. + +The final query does the inversion (``27`` to ``-27``) directly in the +database. The reason for doing this is that if the ``self.rhs`` is something else +than a plain integer value (for example an ``F()`` reference) we can't do the +transformations in Python. + +.. note:: + In fact, most lookups with ``__abs`` could be implemented as range queries + like this, and on most database backends it is likely to be more sensible to + do so as you can make use of the indexes. However with PostgreSQL you may + want to add an index on ``abs(change)`` which would allow these queries to + be very efficient. + +A bilateral transformer example +=============================== + +The ``AbsoluteValue`` example we discussed previously is a transformation which +applies to the left-hand side of the lookup. There may be some cases where you +want the transformation to be applied to both the left-hand side and the +right-hand side. For instance, if you want to filter a queryset based on the +equality of the left and right-hand side insensitively to some SQL function. + +Let's examine case-insensitive transformations here. This transformation isn't +very useful in practice as Django already comes with a bunch of built-in +case-insensitive lookups, but it will be a nice demonstration of bilateral +transformations in a database-agnostic way. + +We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()`` to +transform the values before comparison. We define +:attr:`bilateral = True ` to indicate that +this transformation should apply to both ``lhs`` and ``rhs``:: + + from django.db.models import Transform + + + class UpperCase(Transform): + lookup_name = "upper" + function = "UPPER" + bilateral = True + +Next, let's register it:: + + from django.db.models import CharField, TextField + + CharField.register_lookup(UpperCase) + TextField.register_lookup(UpperCase) + +Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a case +insensitive query like this: + +.. code-block:: sql + + SELECT ... WHERE UPPER("author"."name") = UPPER('doe') + +Writing alternative implementations for existing lookups +======================================================== + +Sometimes different database vendors require different SQL for the same +operation. For this example we will rewrite a custom implementation for +MySQL for the NotEqual operator. Instead of ``<>`` we will be using ``!=`` +operator. (Note that in reality almost all databases support both, including +all the official databases supported by Django). + +We can change the behavior on a specific backend by creating a subclass of +``NotEqual`` with an ``as_mysql`` method:: + + class MySQLNotEqual(NotEqual): + def as_mysql(self, compiler, connection, **extra_context): + lhs, lhs_params = self.process_lhs(compiler, connection) + rhs, rhs_params = self.process_rhs(compiler, connection) + params = lhs_params + rhs_params + return "%s != %s" % (lhs, rhs), params + + + Field.register_lookup(MySQLNotEqual) + +We can then register it with ``Field``. It takes the place of the original +``NotEqual`` class as it has the same ``lookup_name``. + +When compiling a query, Django first looks for ``as_%s % connection.vendor`` +methods, and then falls back to ``as_sql``. The vendor names for the in-built +backends are ``sqlite``, ``postgresql``, ``oracle`` and ``mysql``. + +How Django determines the lookups and transforms which are used +=============================================================== + +In some cases you may wish to dynamically change which ``Transform`` or +``Lookup`` is returned based on the name passed in, rather than fixing it. As +an example, you could have a field which stores coordinates or an arbitrary +dimension, and wish to allow a syntax like ``.filter(coords__x7=4)`` to return +the objects where the 7th coordinate has value 4. In order to do this, you +would override ``get_lookup`` with something like:: + + class CoordinatesField(Field): + def get_lookup(self, lookup_name): + if lookup_name.startswith("x"): + try: + dimension = int(lookup_name.removeprefix("x")) + except ValueError: + pass + else: + return get_coordinate_lookup(dimension) + return super().get_lookup(lookup_name) + +You would then define ``get_coordinate_lookup`` appropriately to return a +``Lookup`` subclass which handles the relevant value of ``dimension``. + +There is a similarly named method called ``get_transform()``. ``get_lookup()`` +should always return a ``Lookup`` subclass, and ``get_transform()`` a +``Transform`` subclass. It is important to remember that ``Transform`` +objects can be further filtered on, and ``Lookup`` objects cannot. + +When filtering, if there is only one lookup name remaining to be resolved, we +will look for a ``Lookup``. If there are multiple names, it will look for a +``Transform``. In the situation where there is only one name and a ``Lookup`` +is not found, we look for a ``Transform`` and then the ``exact`` lookup on that +``Transform``. All call sequences always end with a ``Lookup``. To clarify: + +- ``.filter(myfield__mylookup)`` will call ``myfield.get_lookup('mylookup')``. +- ``.filter(myfield__mytransform__mylookup)`` will call + ``myfield.get_transform('mytransform')``, and then + ``mytransform.get_lookup('mylookup')``. +- ``.filter(myfield__mytransform)`` will first call + ``myfield.get_lookup('mytransform')``, which will fail, so it will fall back + to calling ``myfield.get_transform('mytransform')`` and then + ``mytransform.get_lookup('exact')``. diff --git a/testbed/django__django/docs/howto/custom-management-commands.txt b/testbed/django__django/docs/howto/custom-management-commands.txt new file mode 100644 index 0000000000000000000000000000000000000000..8bdfb1e38b9dc535faed5ac8f3d452143110c85f --- /dev/null +++ b/testbed/django__django/docs/howto/custom-management-commands.txt @@ -0,0 +1,375 @@ +============================================== +How to create custom ``django-admin`` commands +============================================== + +.. module:: django.core.management + +Applications can register their own actions with ``manage.py``. For example, +you might want to add a ``manage.py`` action for a Django app that you're +distributing. In this document, we will be building a custom ``closepoll`` +command for the ``polls`` application from the +:doc:`tutorial`. + +To do this, add a ``management/commands`` directory to the application. Django +will register a ``manage.py`` command for each Python module in that directory +whose name doesn't begin with an underscore. For example: + +.. code-block:: text + + polls/ + __init__.py + models.py + management/ + __init__.py + commands/ + __init__.py + _private.py + closepoll.py + tests.py + views.py + +In this example, the ``closepoll`` command will be made available to any project +that includes the ``polls`` application in :setting:`INSTALLED_APPS`. + +The ``_private.py`` module will not be available as a management command. + +The ``closepoll.py`` module has only one requirement -- it must define a class +``Command`` that extends :class:`BaseCommand` or one of its +:ref:`subclasses`. + +.. admonition:: Standalone scripts + + Custom management commands are especially useful for running standalone + scripts or for scripts that are periodically executed from the UNIX crontab + or from Windows scheduled tasks control panel. + +To implement the command, edit ``polls/management/commands/closepoll.py`` to +look like this:: + + from django.core.management.base import BaseCommand, CommandError + from polls.models import Question as Poll + + + class Command(BaseCommand): + help = "Closes the specified poll for voting" + + def add_arguments(self, parser): + parser.add_argument("poll_ids", nargs="+", type=int) + + def handle(self, *args, **options): + for poll_id in options["poll_ids"]: + try: + poll = Poll.objects.get(pk=poll_id) + except Poll.DoesNotExist: + raise CommandError('Poll "%s" does not exist' % poll_id) + + poll.opened = False + poll.save() + + self.stdout.write( + self.style.SUCCESS('Successfully closed poll "%s"' % poll_id) + ) + +.. _management-commands-output: + +.. note:: + When you are using management commands and wish to provide console + output, you should write to ``self.stdout`` and ``self.stderr``, + instead of printing to ``stdout`` and ``stderr`` directly. By + using these proxies, it becomes much easier to test your custom + command. Note also that you don't need to end messages with a newline + character, it will be added automatically, unless you specify the ``ending`` + parameter:: + + self.stdout.write("Unterminated line", ending="") + +The new custom command can be called using ``python manage.py closepoll +``. + +The ``handle()`` method takes one or more ``poll_ids`` and sets ``poll.opened`` +to ``False`` for each one. If the user referenced any nonexistent polls, a +:exc:`CommandError` is raised. The ``poll.opened`` attribute does not exist in +the :doc:`tutorial` and was added to +``polls.models.Question`` for this example. + +.. _custom-commands-options: + +Accepting optional arguments +============================ + +The same ``closepoll`` could be easily modified to delete a given poll instead +of closing it by accepting additional command line options. These custom +options can be added in the :meth:`~BaseCommand.add_arguments` method like this:: + + class Command(BaseCommand): + def add_arguments(self, parser): + # Positional arguments + parser.add_argument("poll_ids", nargs="+", type=int) + + # Named (optional) arguments + parser.add_argument( + "--delete", + action="store_true", + help="Delete poll instead of closing it", + ) + + def handle(self, *args, **options): + # ... + if options["delete"]: + poll.delete() + # ... + +The option (``delete`` in our example) is available in the options dict +parameter of the handle method. See the :py:mod:`argparse` Python documentation +for more about ``add_argument`` usage. + +In addition to being able to add custom command line options, all +:doc:`management commands` can accept some default options +such as :option:`--verbosity` and :option:`--traceback`. + +.. _management-commands-and-locales: + +Management commands and locales +=============================== + +By default, management commands are executed with the current active locale. + +If, for some reason, your custom management command must run without an active +locale (for example, to prevent translated content from being inserted into +the database), deactivate translations using the ``@no_translations`` +decorator on your :meth:`~BaseCommand.handle` method:: + + from django.core.management.base import BaseCommand, no_translations + + + class Command(BaseCommand): + ... + + @no_translations + def handle(self, *args, **options): + ... + +Since translation deactivation requires access to configured settings, the +decorator can't be used for commands that work without configured settings. + +Testing +======= + +Information on how to test custom management commands can be found in the +:ref:`testing docs `. + +Overriding commands +=================== + +Django registers the built-in commands and then searches for commands in +:setting:`INSTALLED_APPS` in reverse. During the search, if a command name +duplicates an already registered command, the newly discovered command +overrides the first. + +In other words, to override a command, the new command must have the same name +and its app must be before the overridden command's app in +:setting:`INSTALLED_APPS`. + +Management commands from third-party apps that have been unintentionally +overridden can be made available under a new name by creating a new command in +one of your project's apps (ordered before the third-party app in +:setting:`INSTALLED_APPS`) which imports the ``Command`` of the overridden +command. + +Command objects +=============== + +.. class:: BaseCommand + +The base class from which all management commands ultimately derive. + +Use this class if you want access to all of the mechanisms which +parse the command-line arguments and work out what code to call in +response; if you don't need to change any of that behavior, +consider using one of its :ref:`subclasses`. + +Subclassing the :class:`BaseCommand` class requires that you implement the +:meth:`~BaseCommand.handle` method. + +Attributes +---------- + +All attributes can be set in your derived class and can be used in +:class:`BaseCommand`’s :ref:`subclasses`. + +.. attribute:: BaseCommand.help + + A short description of the command, which will be printed in the + help message when the user runs the command + ``python manage.py help ``. + +.. attribute:: BaseCommand.missing_args_message + + If your command defines mandatory positional arguments, you can customize + the message error returned in the case of missing arguments. The default is + output by :py:mod:`argparse` ("too few arguments"). + +.. attribute:: BaseCommand.output_transaction + + A boolean indicating whether the command outputs SQL statements; if + ``True``, the output will automatically be wrapped with ``BEGIN;`` and + ``COMMIT;``. Default value is ``False``. + +.. attribute:: BaseCommand.requires_migrations_checks + + A boolean; if ``True``, the command prints a warning if the set of + migrations on disk don't match the migrations in the database. A warning + doesn't prevent the command from executing. Default value is ``False``. + +.. attribute:: BaseCommand.requires_system_checks + + A list or tuple of tags, e.g. ``[Tags.staticfiles, Tags.models]``. System + checks :ref:`registered in the chosen tags ` + will be checked for errors prior to executing the command. The value + ``'__all__'`` can be used to specify that all system checks should be + performed. Default value is ``'__all__'``. + +.. attribute:: BaseCommand.style + + An instance attribute that helps create colored output when writing to + ``stdout`` or ``stderr``. For example:: + + self.stdout.write(self.style.SUCCESS("...")) + + See :ref:`syntax-coloring` to learn how to modify the color palette and to + see the available styles (use uppercased versions of the "roles" described + in that section). + + If you pass the :option:`--no-color` option when running your command, all + ``self.style()`` calls will return the original string uncolored. + +.. attribute:: BaseCommand.suppressed_base_arguments + + The default command options to suppress in the help output. This should be + a set of option names (e.g. ``'--verbosity'``). The default values for the + suppressed options are still passed. + +Methods +------- + +:class:`BaseCommand` has a few methods that can be overridden but only +the :meth:`~BaseCommand.handle` method must be implemented. + +.. admonition:: Implementing a constructor in a subclass + + If you implement ``__init__`` in your subclass of :class:`BaseCommand`, + you must call :class:`BaseCommand`’s ``__init__``:: + + class Command(BaseCommand): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # ... + +.. method:: BaseCommand.create_parser(prog_name, subcommand, **kwargs) + + Returns a ``CommandParser`` instance, which is an + :class:`~argparse.ArgumentParser` subclass with a few customizations for + Django. + + You can customize the instance by overriding this method and calling + ``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser` parameters. + +.. method:: BaseCommand.add_arguments(parser) + + Entry point to add parser arguments to handle command line arguments passed + to the command. Custom commands should override this method to add both + positional and optional arguments accepted by the command. Calling + ``super()`` is not needed when directly subclassing ``BaseCommand``. + +.. method:: BaseCommand.get_version() + + Returns the Django version, which should be correct for all built-in Django + commands. User-supplied commands can override this method to return their + own version. + +.. method:: BaseCommand.execute(*args, **options) + + Tries to execute this command, performing system checks if needed (as + controlled by the :attr:`requires_system_checks` attribute). If the command + raises a :exc:`CommandError`, it's intercepted and printed to ``stderr``. + +.. admonition:: Calling a management command in your code + + ``execute()`` should not be called directly from your code to execute a + command. Use :func:`~django.core.management.call_command` instead. + +.. method:: BaseCommand.handle(*args, **options) + + The actual logic of the command. Subclasses must implement this method. + + It may return a string which will be printed to ``stdout`` (wrapped + by ``BEGIN;`` and ``COMMIT;`` if :attr:`output_transaction` is ``True``). + +.. method:: BaseCommand.check(app_configs=None, tags=None, display_num_errors=False) + + Uses the system check framework to inspect the entire Django project for + potential problems. Serious problems are raised as a :exc:`CommandError`; + warnings are output to ``stderr``; minor notifications are output to + ``stdout``. + + If ``app_configs`` and ``tags`` are both ``None``, all system checks are + performed. ``tags`` can be a list of check tags, like ``compatibility`` or + ``models``. + +.. _ref-basecommand-subclasses: + +``BaseCommand`` subclasses +-------------------------- + +.. class:: AppCommand + +A management command which takes one or more installed application labels as +arguments, and does something with each of them. + +Rather than implementing :meth:`~BaseCommand.handle`, subclasses must +implement :meth:`~AppCommand.handle_app_config`, which will be called once for +each application. + +.. method:: AppCommand.handle_app_config(app_config, **options) + + Perform the command's actions for ``app_config``, which will be an + :class:`~django.apps.AppConfig` instance corresponding to an application + label given on the command line. + +.. class:: LabelCommand + +A management command which takes one or more arbitrary arguments (labels) on +the command line, and does something with each of them. + +Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement +:meth:`~LabelCommand.handle_label`, which will be called once for each label. + +.. attribute:: LabelCommand.label + + A string describing the arbitrary arguments passed to the command. The + string is used in the usage text and error messages of the command. + Defaults to ``'label'``. + +.. method:: LabelCommand.handle_label(label, **options) + + Perform the command's actions for ``label``, which will be the string as + given on the command line. + +Command exceptions +------------------ + +.. exception:: CommandError(returncode=1) + +Exception class indicating a problem while executing a management command. + +If this exception is raised during the execution of a management command from a +command line console, it will be caught and turned into a nicely-printed error +message to the appropriate output stream (i.e., ``stderr``); as a result, +raising this exception (with a sensible description of the error) is the +preferred way to indicate that something has gone wrong in the execution of a +command. It accepts the optional ``returncode`` argument to customize the exit +status for the management command to exit with, using :func:`sys.exit`. + +If a management command is called from code through +:func:`~django.core.management.call_command`, it's up to you to catch the +exception when needed. diff --git a/testbed/django__django/docs/howto/custom-model-fields.txt b/testbed/django__django/docs/howto/custom-model-fields.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa5c4389d75c9825f0dae91b40ccbe2f27548c54 --- /dev/null +++ b/testbed/django__django/docs/howto/custom-model-fields.txt @@ -0,0 +1,778 @@ +================================= +How to create custom model fields +================================= + +.. currentmodule:: django.db.models + +Introduction +============ + +The :doc:`model reference ` documentation explains how to use +Django's standard field classes -- :class:`~django.db.models.CharField`, +:class:`~django.db.models.DateField`, etc. For many purposes, those classes are +all you'll need. Sometimes, though, the Django version won't meet your precise +requirements, or you'll want to use a field that is entirely different from +those shipped with Django. + +Django's built-in field types don't cover every possible database column type -- +only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure +column types, such as geographic polygons or even user-created types such as +`PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses. + +.. _PostgreSQL custom types: https://www.postgresql.org/docs/current/sql-createtype.html + +Alternatively, you may have a complex Python object that can somehow be +serialized to fit into a standard database column type. This is another case +where a ``Field`` subclass will help you use your object with your models. + +Our example object +------------------ + +Creating custom fields requires a bit of attention to detail. To make things +easier to follow, we'll use a consistent example throughout this document: +wrapping a Python object representing the deal of cards in a hand of Bridge_. +Don't worry, you don't have to know how to play Bridge to follow this example. +You only need to know that 52 cards are dealt out equally to four players, who +are traditionally called *north*, *east*, *south* and *west*. Our class looks +something like this:: + + class Hand: + """A hand of cards (bridge style)""" + + def __init__(self, north, east, south, west): + # Input parameters are lists of cards ('Ah', '9s', etc.) + self.north = north + self.east = east + self.south = south + self.west = west + + # ... (other possibly useful methods omitted) ... + +.. _Bridge: https://en.wikipedia.org/wiki/Contract_bridge + +This is an ordinary Python class, with nothing Django-specific about it. +We'd like to be able to do things like this in our models (we assume the +``hand`` attribute on the model is an instance of ``Hand``):: + + example = MyModel.objects.get(pk=1) + print(example.hand.north) + + new_hand = Hand(north, east, south, west) + example.hand = new_hand + example.save() + +We assign to and retrieve from the ``hand`` attribute in our model just like +any other Python class. The trick is to tell Django how to handle saving and +loading such an object. + +In order to use the ``Hand`` class in our models, we **do not** have to change +this class at all. This is ideal, because it means you can easily write +model support for existing classes where you cannot change the source code. + +.. note:: + You might only be wanting to take advantage of custom database column + types and deal with the data as standard Python types in your models; + strings, or floats, for example. This case is similar to our ``Hand`` + example and we'll note any differences as we go along. + +Background theory +================= + +Database storage +---------------- + +Let's start with model fields. If you break it down, a model field provides a +way to take a normal Python object -- string, boolean, ``datetime``, or +something more complex like ``Hand`` -- and convert it to and from a format +that is useful when dealing with the database. (Such a format is also useful +for serialization, but as we'll see later, that is easier once you have the +database side under control). + +Fields in a model must somehow be converted to fit into an existing database +column type. Different databases provide different sets of valid column types, +but the rule is still the same: those are the only types you have to work +with. Anything you want to store in the database must fit into one of +those types. + +Normally, you're either writing a Django field to match a particular database +column type, or you will need a way to convert your data to, say, a string. + +For our ``Hand`` example, we could convert the card data to a string of 104 +characters by concatenating all the cards together in a predetermined order -- +say, all the *north* cards first, then the *east*, *south* and *west* cards. So +``Hand`` objects can be saved to text or character columns in the database. + +What does a field class do? +--------------------------- + +All of Django's fields (and when we say *fields* in this document, we always +mean model fields and not :doc:`form fields `) are subclasses +of :class:`django.db.models.Field`. Most of the information that Django records +about a field is common to all fields -- name, help text, uniqueness and so +forth. Storing all that information is handled by ``Field``. We'll get into the +precise details of what ``Field`` can do later on; for now, suffice it to say +that everything descends from ``Field`` and then customizes key pieces of the +class behavior. + +It's important to realize that a Django field class is not what is stored in +your model attributes. The model attributes contain normal Python objects. The +field classes you define in a model are actually stored in the ``Meta`` class +when the model class is created (the precise details of how this is done are +unimportant here). This is because the field classes aren't necessary when +you're just creating and modifying attributes. Instead, they provide the +machinery for converting between the attribute value and what is stored in the +database or sent to the :doc:`serializer `. + +Keep this in mind when creating your own custom fields. The Django ``Field`` +subclass you write provides the machinery for converting between your Python +instances and the database/serializer values in various ways (there are +differences between storing a value and using a value for lookups, for +example). If this sounds a bit tricky, don't worry -- it will become clearer in +the examples below. Just remember that you will often end up creating two +classes when you want a custom field: + +* The first class is the Python object that your users will manipulate. + They will assign it to the model attribute, they will read from it for + displaying purposes, things like that. This is the ``Hand`` class in our + example. + +* The second class is the ``Field`` subclass. This is the class that knows + how to convert your first class back and forth between its permanent + storage form and the Python form. + +Writing a field subclass +======================== + +When planning your :class:`~django.db.models.Field` subclass, first give some +thought to which existing :class:`~django.db.models.Field` class your new field +is most similar to. Can you subclass an existing Django field and save yourself +some work? If not, you should subclass the :class:`~django.db.models.Field` +class, from which everything is descended. + +Initializing your new field is a matter of separating out any arguments that are +specific to your case from the common arguments and passing the latter to the +``__init__()`` method of :class:`~django.db.models.Field` (or your parent +class). + +In our example, we'll call our field ``HandField``. (It's a good idea to call +your :class:`~django.db.models.Field` subclass ``Field``, so it's +easily identifiable as a :class:`~django.db.models.Field` subclass.) It doesn't +behave like any existing field, so we'll subclass directly from +:class:`~django.db.models.Field`:: + + from django.db import models + + + class HandField(models.Field): + description = "A hand of cards (bridge style)" + + def __init__(self, *args, **kwargs): + kwargs["max_length"] = 104 + super().__init__(*args, **kwargs) + +Our ``HandField`` accepts most of the standard field options (see the list +below), but we ensure it has a fixed length, since it only needs to hold 52 +card values plus their suits; 104 characters in total. + +.. note:: + + Many of Django's model fields accept options that they don't do anything + with. For example, you can pass both + :attr:`~django.db.models.Field.editable` and + :attr:`~django.db.models.DateField.auto_now` to a + :class:`django.db.models.DateField` and it will ignore the + :attr:`~django.db.models.Field.editable` parameter + (:attr:`~django.db.models.DateField.auto_now` being set implies + ``editable=False``). No error is raised in this case. + + This behavior simplifies the field classes, because they don't need to + check for options that aren't necessary. They pass all the options to + the parent class and then don't use them later on. It's up to you whether + you want your fields to be more strict about the options they select, or to + use the more permissive behavior of the current fields. + +The ``Field.__init__()`` method takes the following parameters: + +* :attr:`~django.db.models.Field.verbose_name` +* ``name`` +* :attr:`~django.db.models.Field.primary_key` +* :attr:`~django.db.models.CharField.max_length` +* :attr:`~django.db.models.Field.unique` +* :attr:`~django.db.models.Field.blank` +* :attr:`~django.db.models.Field.null` +* :attr:`~django.db.models.Field.db_index` +* ``rel``: Used for related fields (like :class:`ForeignKey`). For advanced + use only. +* :attr:`~django.db.models.Field.default` +* :attr:`~django.db.models.Field.editable` +* ``serialize``: If ``False``, the field will not be serialized when the model + is passed to Django's :doc:`serializers `. Defaults to + ``True``. +* :attr:`~django.db.models.Field.unique_for_date` +* :attr:`~django.db.models.Field.unique_for_month` +* :attr:`~django.db.models.Field.unique_for_year` +* :attr:`~django.db.models.Field.choices` +* :attr:`~django.db.models.Field.help_text` +* :attr:`~django.db.models.Field.db_column` +* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the + backend supports :doc:`tablespaces `. You can usually + ignore this option. +* :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was + automatically created, as for the :class:`~django.db.models.OneToOneField` + used by model inheritance. For advanced use only. + +All of the options without an explanation in the above list have the same +meaning they do for normal Django fields. See the :doc:`field documentation +` for examples and details. + +.. _custom-field-deconstruct-method: + +Field deconstruction +-------------------- + +The counterpoint to writing your ``__init__()`` method is writing the +:meth:`~.Field.deconstruct` method. It's used during :doc:`model migrations +` to tell Django how to take an instance of your new field +and reduce it to a serialized form - in particular, what arguments to pass to +``__init__()`` to recreate it. + +If you haven't added any extra options on top of the field you inherited from, +then there's no need to write a new ``deconstruct()`` method. If, however, +you're changing the arguments passed in ``__init__()`` (like we are in +``HandField``), you'll need to supplement the values being passed. + +``deconstruct()`` returns a tuple of four items: the field's attribute name, +the full import path of the field class, the positional arguments (as a list), +and the keyword arguments (as a dict). Note this is different from the +``deconstruct()`` method :ref:`for custom classes ` +which returns a tuple of three things. + +As a custom field author, you don't need to care about the first two values; +the base ``Field`` class has all the code to work out the field's attribute +name and import path. You do, however, have to care about the positional +and keyword arguments, as these are likely the things you are changing. + +For example, in our ``HandField`` class we're always forcibly setting +max_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field`` +class will see this and try to return it in the keyword arguments; thus, +we can drop it from the keyword arguments for readability:: + + from django.db import models + + + class HandField(models.Field): + def __init__(self, *args, **kwargs): + kwargs["max_length"] = 104 + super().__init__(*args, **kwargs) + + def deconstruct(self): + name, path, args, kwargs = super().deconstruct() + del kwargs["max_length"] + return name, path, args, kwargs + +If you add a new keyword argument, you need to write code in ``deconstruct()`` +that puts its value into ``kwargs`` yourself. You should also omit the value +from ``kwargs`` when it isn't necessary to reconstruct the state of the field, +such as when the default value is being used:: + + from django.db import models + + + class CommaSepField(models.Field): + "Implements comma-separated storage of lists" + + def __init__(self, separator=",", *args, **kwargs): + self.separator = separator + super().__init__(*args, **kwargs) + + def deconstruct(self): + name, path, args, kwargs = super().deconstruct() + # Only include kwarg if it's not the default + if self.separator != ",": + kwargs["separator"] = self.separator + return name, path, args, kwargs + +More complex examples are beyond the scope of this document, but remember - +for any configuration of your Field instance, ``deconstruct()`` must return +arguments that you can pass to ``__init__`` to reconstruct that state. + +Pay extra attention if you set new default values for arguments in the +``Field`` superclass; you want to make sure they're always included, rather +than disappearing if they take on the old default value. + +In addition, try to avoid returning values as positional arguments; where +possible, return values as keyword arguments for maximum future compatibility. +If you change the names of things more often than their position in the +constructor's argument list, you might prefer positional, but bear in mind that +people will be reconstructing your field from the serialized version for quite +a while (possibly years), depending how long your migrations live for. + +You can see the results of deconstruction by looking in migrations that include +the field, and you can test deconstruction in unit tests by deconstructing and +reconstructing the field:: + + name, path, args, kwargs = my_field_instance.deconstruct() + new_instance = MyField(*args, **kwargs) + self.assertEqual(my_field_instance.some_attribute, new_instance.some_attribute) + +.. _custom-field-non_db_attrs: + +Field attributes not affecting database column definition +--------------------------------------------------------- + +You can override ``Field.non_db_attrs`` to customize attributes of a field that +don't affect a column definition. It's used during model migrations to detect +no-op ``AlterField`` operations. + +For example:: + + class CommaSepField(models.Field): + @property + def non_db_attrs(self): + return super().non_db_attrs + ("separator",) + + +Changing a custom field's base class +------------------------------------ + +You can't change the base class of a custom field because Django won't detect +the change and make a migration for it. For example, if you start with:: + + class CustomCharField(models.CharField): + ... + +and then decide that you want to use ``TextField`` instead, you can't change +the subclass like this:: + + class CustomCharField(models.TextField): + ... + +Instead, you must create a new custom field class and update your models to +reference it:: + + class CustomCharField(models.CharField): + ... + + + class CustomTextField(models.TextField): + ... + +As discussed in :ref:`removing fields `, you +must retain the original ``CustomCharField`` class as long as you have +migrations that reference it. + +Documenting your custom field +----------------------------- + +As always, you should document your field type, so users will know what it is. +In addition to providing a docstring for it, which is useful for developers, +you can also allow users of the admin app to see a short description of the +field type via the :doc:`django.contrib.admindocs +` application. To do this provide descriptive +text in a :attr:`~Field.description` class attribute of your custom field. In +the above example, the description displayed by the ``admindocs`` application +for a ``HandField`` will be 'A hand of cards (bridge style)'. + +In the :mod:`django.contrib.admindocs` display, the field description is +interpolated with ``field.__dict__`` which allows the description to +incorporate arguments of the field. For example, the description for +:class:`~django.db.models.CharField` is:: + + description = _("String (up to %(max_length)s)") + +Useful methods +-------------- + +Once you've created your :class:`~django.db.models.Field` subclass, you might +consider overriding a few standard methods, depending on your field's behavior. +The list of methods below is in approximately decreasing order of importance, +so start from the top. + +.. _custom-database-types: + +Custom database types +~~~~~~~~~~~~~~~~~~~~~ + +Say you've created a PostgreSQL custom type called ``mytype``. You can +subclass ``Field`` and implement the :meth:`~Field.db_type` method, like so:: + + from django.db import models + + + class MytypeField(models.Field): + def db_type(self, connection): + return "mytype" + +Once you have ``MytypeField``, you can use it in any model, just like any other +``Field`` type:: + + class Person(models.Model): + name = models.CharField(max_length=80) + something_else = MytypeField() + +If you aim to build a database-agnostic application, you should account for +differences in database column types. For example, the date/time column type +in PostgreSQL is called ``timestamp``, while the same column in MySQL is called +``datetime``. You can handle this in a :meth:`~Field.db_type` method by +checking the ``connection.vendor`` attribute. Current built-in vendor names +are: ``sqlite``, ``postgresql``, ``mysql``, and ``oracle``. + +For example:: + + class MyDateField(models.Field): + def db_type(self, connection): + if connection.vendor == "mysql": + return "datetime" + else: + return "timestamp" + +The :meth:`~Field.db_type` and :meth:`~Field.rel_db_type` methods are called by +Django when the framework constructs the ``CREATE TABLE`` statements for your +application -- that is, when you first create your tables. The methods are also +called when constructing a ``WHERE`` clause that includes the model field -- +that is, when you retrieve data using QuerySet methods like ``get()``, +``filter()``, and ``exclude()`` and have the model field as an argument. They +are not called at any other time, so it can afford to execute slightly complex +code, such as the ``connection.settings_dict`` check in the above example. + +Some database column types accept parameters, such as ``CHAR(25)``, where the +parameter ``25`` represents the maximum column length. In cases like these, +it's more flexible if the parameter is specified in the model rather than being +hard-coded in the ``db_type()`` method. For example, it wouldn't make much +sense to have a ``CharMaxlength25Field``, shown here:: + + # This is a silly example of hard-coded parameters. + class CharMaxlength25Field(models.Field): + def db_type(self, connection): + return "char(25)" + + + # In the model: + class MyModel(models.Model): + # ... + my_field = CharMaxlength25Field() + +The better way of doing this would be to make the parameter specifiable at run +time -- i.e., when the class is instantiated. To do that, implement +``Field.__init__()``, like so:: + + # This is a much more flexible example. + class BetterCharField(models.Field): + def __init__(self, max_length, *args, **kwargs): + self.max_length = max_length + super().__init__(*args, **kwargs) + + def db_type(self, connection): + return "char(%s)" % self.max_length + + + # In the model: + class MyModel(models.Model): + # ... + my_field = BetterCharField(25) + +Finally, if your column requires truly complex SQL setup, return ``None`` from +:meth:`.db_type`. This will cause Django's SQL creation code to skip +over this field. You are then responsible for creating the column in the right +table in some other way, but this gives you a way to tell Django to get out of +the way. + +The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey`` +and ``OneToOneField`` that point to another field to determine their database +column data types. For example, if you have an ``UnsignedAutoField``, you also +need the foreign keys that point to that field to use the same data type:: + + # MySQL unsigned integer (range 0 to 4294967295). + class UnsignedAutoField(models.AutoField): + def db_type(self, connection): + return "integer UNSIGNED AUTO_INCREMENT" + + def rel_db_type(self, connection): + return "integer UNSIGNED" + +.. _converting-values-to-python-objects: + +Converting values to Python objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your custom :class:`~Field` class deals with data structures that are more +complex than strings, dates, integers, or floats, then you may need to override +:meth:`~Field.from_db_value` and :meth:`~Field.to_python`. + +If present for the field subclass, ``from_db_value()`` will be called in all +circumstances when the data is loaded from the database, including in +aggregates and :meth:`~django.db.models.query.QuerySet.values` calls. + +``to_python()`` is called by deserialization and during the +:meth:`~django.db.models.Model.clean` method used from forms. + +As a general rule, ``to_python()`` should deal gracefully with any of the +following arguments: + +* An instance of the correct type (e.g., ``Hand`` in our ongoing example). + +* A string + +* ``None`` (if the field allows ``null=True``) + +In our ``HandField`` class, we're storing the data as a ``VARCHAR`` field in +the database, so we need to be able to process strings and ``None`` in the +``from_db_value()``. In ``to_python()``, we need to also handle ``Hand`` +instances:: + + import re + + from django.core.exceptions import ValidationError + from django.db import models + from django.utils.translation import gettext_lazy as _ + + + def parse_hand(hand_string): + """Takes a string of cards and splits into a full hand.""" + p1 = re.compile(".{26}") + p2 = re.compile("..") + args = [p2.findall(x) for x in p1.findall(hand_string)] + if len(args) != 4: + raise ValidationError(_("Invalid input for a Hand instance")) + return Hand(*args) + + + class HandField(models.Field): + # ... + + def from_db_value(self, value, expression, connection): + if value is None: + return value + return parse_hand(value) + + def to_python(self, value): + if isinstance(value, Hand): + return value + + if value is None: + return value + + return parse_hand(value) + +Notice that we always return a ``Hand`` instance from these methods. That's the +Python object type we want to store in the model's attribute. + +For ``to_python()``, if anything goes wrong during value conversion, you should +raise a :exc:`~django.core.exceptions.ValidationError` exception. + +.. _converting-python-objects-to-query-values: + +Converting Python objects to query values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since using a database requires conversion in both ways, if you override +:meth:`~Field.from_db_value` you also have to override +:meth:`~Field.get_prep_value` to convert Python objects back to query values. + +For example:: + + class HandField(models.Field): + # ... + + def get_prep_value(self, value): + return "".join( + ["".join(l) for l in (value.north, value.east, value.south, value.west)] + ) + +.. warning:: + + If your custom field uses the ``CHAR``, ``VARCHAR`` or ``TEXT`` + types for MySQL, you must make sure that :meth:`.get_prep_value` + always returns a string type. MySQL performs flexible and unexpected + matching when a query is performed on these types and the provided + value is an integer, which can cause queries to include unexpected + objects in their results. This problem cannot occur if you always + return a string type from :meth:`.get_prep_value`. + +.. _converting-query-values-to-database-values: + +Converting query values to database values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Some data types (for example, dates) need to be in a specific format +before they can be used by a database backend. +:meth:`~Field.get_db_prep_value` is the method where those conversions should +be made. The specific connection that will be used for the query is +passed as the ``connection`` parameter. This allows you to use +backend-specific conversion logic if it is required. + +For example, Django uses the following method for its +:class:`BinaryField`:: + + def get_db_prep_value(self, value, connection, prepared=False): + value = super().get_db_prep_value(value, connection, prepared) + if value is not None: + return connection.Database.Binary(value) + return value + +In case your custom field needs a special conversion when being saved that is +not the same as the conversion used for normal query parameters, you can +override :meth:`~Field.get_db_prep_save`. + +.. _preprocessing-values-before-saving: + +Preprocessing values before saving +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you want to preprocess the value just before saving, you can use +:meth:`~Field.pre_save`. For example, Django's +:class:`~django.db.models.DateTimeField` uses this method to set the attribute +correctly in the case of :attr:`~django.db.models.DateField.auto_now` or +:attr:`~django.db.models.DateField.auto_now_add`. + +If you do override this method, you must return the value of the attribute at +the end. You should also update the model's attribute if you make any changes +to the value so that code holding references to the model will always see the +correct value. + +.. _specifying-form-field-for-model-field: + +Specifying the form field for a model field +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To customize the form field used by :class:`~django.forms.ModelForm`, you can +override :meth:`~Field.formfield`. + +The form field class can be specified via the ``form_class`` and +``choices_form_class`` arguments; the latter is used if the field has choices +specified, the former otherwise. If these arguments are not provided, +:class:`~django.forms.CharField` or :class:`~django.forms.TypedChoiceField` +will be used. + +All of the ``kwargs`` dictionary is passed directly to the form field's +``__init__()`` method. Normally, all you need to do is set up a good default +for the ``form_class`` (and maybe ``choices_form_class``) argument and then +delegate further handling to the parent class. This might require you to write +a custom form field (and even a form widget). See the :doc:`forms documentation +` for information about this. + +Continuing our ongoing example, we can write the :meth:`~Field.formfield` method +as:: + + class HandField(models.Field): + # ... + + def formfield(self, **kwargs): + # This is a fairly standard way to set up some defaults + # while letting the caller override them. + defaults = {"form_class": MyFormField} + defaults.update(kwargs) + return super().formfield(**defaults) + +This assumes we've imported a ``MyFormField`` field class (which has its own +default widget). This document doesn't cover the details of writing custom form +fields. + +.. _helper functions: ../forms/#generating-forms-for-models +.. _forms documentation: ../forms/ + +.. _emulating-built-in-field-types: + +Emulating built-in field types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you have created a :meth:`.db_type` method, you don't need to worry about +:meth:`.get_internal_type` -- it won't be used much. Sometimes, though, your +database storage is similar in type to some other field, so you can use that +other field's logic to create the right column. + +For example:: + + class HandField(models.Field): + # ... + + def get_internal_type(self): + return "CharField" + +No matter which database backend we are using, this will mean that +:djadmin:`migrate` and other SQL commands create the right column type for +storing a string. + +If :meth:`.get_internal_type` returns a string that is not known to Django for +the database backend you are using -- that is, it doesn't appear in +``django.db.backends..base.DatabaseWrapper.data_types`` -- the string +will still be used by the serializer, but the default :meth:`~Field.db_type` +method will return ``None``. See the documentation of :meth:`~Field.db_type` +for reasons why this might be useful. Putting a descriptive string in as the +type of the field for the serializer is a useful idea if you're ever going to +be using the serializer output in some other place, outside of Django. + +.. _converting-model-field-to-serialization: + +Converting field data for serialization +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To customize how the values are serialized by a serializer, you can override +:meth:`~Field.value_to_string`. Using :meth:`~Field.value_from_object` is the +best way to get the field's value prior to serialization. For example, since +``HandField`` uses strings for its data storage anyway, we can reuse some +existing conversion code:: + + class HandField(models.Field): + # ... + + def value_to_string(self, obj): + value = self.value_from_object(obj) + return self.get_prep_value(value) + +Some general advice +------------------- + +Writing a custom field can be a tricky process, particularly if you're doing +complex conversions between your Python types and your database and +serialization formats. Here are a couple of tips to make things go more +smoothly: + +#. Look at the existing Django fields (in + :source:`django/db/models/fields/__init__.py`) for inspiration. Try to find + a field that's similar to what you want and extend it a little bit, + instead of creating an entirely new field from scratch. + +#. Put a ``__str__()`` method on the class you're wrapping up as a field. There + are a lot of places where the default behavior of the field code is to call + ``str()`` on the value. (In our examples in this document, ``value`` would + be a ``Hand`` instance, not a ``HandField``). So if your ``__str__()`` + method automatically converts to the string form of your Python object, you + can save yourself a lot of work. + +Writing a ``FileField`` subclass +================================ + +In addition to the above methods, fields that deal with files have a few other +special requirements which must be taken into account. The majority of the +mechanics provided by ``FileField``, such as controlling database storage and +retrieval, can remain unchanged, leaving subclasses to deal with the challenge +of supporting a particular type of file. + +Django provides a ``File`` class, which is used as a proxy to the file's +contents and operations. This can be subclassed to customize how the file is +accessed, and what methods are available. It lives at +``django.db.models.fields.files``, and its default behavior is explained in the +:doc:`file documentation `. + +Once a subclass of ``File`` is created, the new ``FileField`` subclass must be +told to use it. To do so, assign the new ``File`` subclass to the special +``attr_class`` attribute of the ``FileField`` subclass. + +A few suggestions +----------------- + +In addition to the above details, there are a few guidelines which can greatly +improve the efficiency and readability of the field's code. + +#. The source for Django's own ``ImageField`` (in + :source:`django/db/models/fields/files.py`) is a great example of how to + subclass ``FileField`` to support a particular type of file, as it + incorporates all of the techniques described above. + +#. Cache file attributes wherever possible. Since files may be stored in + remote storage systems, retrieving them may cost extra time, or even + money, that isn't always necessary. Once a file is retrieved to obtain + some data about its content, cache as much of that data as possible to + reduce the number of times the file must be retrieved on subsequent + calls for that information. diff --git a/testbed/django__django/docs/howto/custom-template-backend.txt b/testbed/django__django/docs/howto/custom-template-backend.txt new file mode 100644 index 0000000000000000000000000000000000000000..85e8591cbd16063c82d5ede7765eef3e5f58183c --- /dev/null +++ b/testbed/django__django/docs/howto/custom-template-backend.txt @@ -0,0 +1,171 @@ +========================================== +How to implement a custom template backend +========================================== + +Custom backends +--------------- + +Here's how to implement a custom template backend in order to use another +template system. A template backend is a class that inherits +``django.template.backends.base.BaseEngine``. It must implement +``get_template()`` and optionally ``from_string()``. Here's an example for a +fictional ``foobar`` template library:: + + from django.template import TemplateDoesNotExist, TemplateSyntaxError + from django.template.backends.base import BaseEngine + from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy + + import foobar + + + class FooBar(BaseEngine): + # Name of the subdirectory containing the templates for this engine + # inside an installed application. + app_dirname = "foobar" + + def __init__(self, params): + params = params.copy() + options = params.pop("OPTIONS").copy() + super().__init__(params) + + self.engine = foobar.Engine(**options) + + def from_string(self, template_code): + try: + return Template(self.engine.from_string(template_code)) + except foobar.TemplateCompilationFailed as exc: + raise TemplateSyntaxError(exc.args) + + def get_template(self, template_name): + try: + return Template(self.engine.get_template(template_name)) + except foobar.TemplateNotFound as exc: + raise TemplateDoesNotExist(exc.args, backend=self) + except foobar.TemplateCompilationFailed as exc: + raise TemplateSyntaxError(exc.args) + + + class Template: + def __init__(self, template): + self.template = template + + def render(self, context=None, request=None): + if context is None: + context = {} + if request is not None: + context["request"] = request + context["csrf_input"] = csrf_input_lazy(request) + context["csrf_token"] = csrf_token_lazy(request) + return self.template.render(context) + +See `DEP 182`_ for more information. + +.. _template-debug-integration: + +Debug integration for custom engines +------------------------------------ + +The Django debug page has hooks to provide detailed information when a template +error arises. Custom template engines can use these hooks to enhance the +traceback information that appears to users. The following hooks are available: + +.. _template-postmortem: + +Template postmortem +~~~~~~~~~~~~~~~~~~~ + +The postmortem appears when :exc:`~django.template.TemplateDoesNotExist` is +raised. It lists the template engines and loaders that were used when trying to +find a given template. For example, if two Django engines are configured, the +postmortem will appear like: + +.. image:: _images/postmortem.png + +Custom engines can populate the postmortem by passing the ``backend`` and +``tried`` arguments when raising :exc:`~django.template.TemplateDoesNotExist`. +Backends that use the postmortem :ref:`should specify an origin +` on the template object. + +Contextual line information +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If an error happens during template parsing or rendering, Django can display +the line the error happened on. For example: + +.. image:: _images/template-lines.png + +Custom engines can populate this information by setting a ``template_debug`` +attribute on exceptions raised during parsing and rendering. This attribute is +a :class:`dict` with the following values: + +* ``'name'``: The name of the template in which the exception occurred. + +* ``'message'``: The exception message. + +* ``'source_lines'``: The lines before, after, and including the line the + exception occurred on. This is for context, so it shouldn't contain more than + 20 lines or so. + +* ``'line'``: The line number on which the exception occurred. + +* ``'before'``: The content on the error line before the token that raised the + error. + +* ``'during'``: The token that raised the error. + +* ``'after'``: The content on the error line after the token that raised the + error. + +* ``'total'``: The number of lines in ``source_lines``. + +* ``'top'``: The line number where ``source_lines`` starts. + +* ``'bottom'``: The line number where ``source_lines`` ends. + +Given the above template error, ``template_debug`` would look like:: + + { + "name": "/path/to/template.html", + "message": "Invalid block tag: 'syntax'", + "source_lines": [ + (1, "some\n"), + (2, "lines\n"), + (3, "before\n"), + (4, "Hello {% syntax error %} {{ world }}\n"), + (5, "some\n"), + (6, "lines\n"), + (7, "after\n"), + (8, ""), + ], + "line": 4, + "before": "Hello ", + "during": "{% syntax error %}", + "after": " {{ world }}\n", + "total": 9, + "bottom": 9, + "top": 1, + } + +.. _template-origin-api: + +Origin API and 3rd-party integration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Django templates have an :class:`~django.template.base.Origin` object available +through the ``template.origin`` attribute. This enables debug information to be +displayed in the :ref:`template postmortem `, as well as +in 3rd-party libraries, like the `Django Debug Toolbar`_. + +Custom engines can provide their own ``template.origin`` information by +creating an object that specifies the following attributes: + +* ``'name'``: The full path to the template. + +* ``'template_name'``: The relative path to the template as passed into the + template loading methods. + +* ``'loader_name'``: An optional string identifying the function or class used + to load the template, e.g. ``django.template.loaders.filesystem.Loader``. + +.. _DEP 182: https://github.com/django/deps/blob/main/final/0182-multiple-template-engines.rst +.. _Django Debug Toolbar: https://github.com/jazzband/django-debug-toolbar/ diff --git a/testbed/django__django/docs/howto/custom-template-tags.txt b/testbed/django__django/docs/howto/custom-template-tags.txt new file mode 100644 index 0000000000000000000000000000000000000000..c7909c8a4bbf57f07808b3d97f189b94b02d45ce --- /dev/null +++ b/testbed/django__django/docs/howto/custom-template-tags.txt @@ -0,0 +1,1177 @@ +============================================== +How to create custom template tags and filters +============================================== + +Django's template language comes with a wide variety of :doc:`built-in +tags and filters ` designed to address the +presentation logic needs of your application. Nevertheless, you may +find yourself needing functionality that is not covered by the core +set of template primitives. You can extend the template engine by +defining custom tags and filters using Python, and then make them +available to your templates using the :ttag:`{% load %}` tag. + +Code layout +=========== + +The most common place to specify custom template tags and filters is inside +a Django app. If they relate to an existing app, it makes sense to bundle them +there; otherwise, they can be added to a new app. When a Django app is added +to :setting:`INSTALLED_APPS`, any tags it defines in the conventional location +described below are automatically made available to load within templates. + +The app should contain a ``templatetags`` directory, at the same level as +``models.py``, ``views.py``, etc. If this doesn't already exist, create it - +don't forget the ``__init__.py`` file to ensure the directory is treated as a +Python package. + +.. admonition:: Development server won't automatically restart + + After adding the ``templatetags`` module, you will need to restart your + server before you can use the tags or filters in templates. + +Your custom tags and filters will live in a module inside the ``templatetags`` +directory. The name of the module file is the name you'll use to load the tags +later, so be careful to pick a name that won't clash with custom tags and +filters in another app. + +For example, if your custom tags/filters are in a file called +``poll_extras.py``, your app layout might look like this: + +.. code-block:: text + + polls/ + __init__.py + models.py + templatetags/ + __init__.py + poll_extras.py + views.py + +And in your template you would use the following: + +.. code-block:: html+django + + {% load poll_extras %} + +The app that contains the custom tags must be in :setting:`INSTALLED_APPS` in +order for the :ttag:`{% load %}` tag to work. This is a security feature: +It allows you to host Python code for many template libraries on a single host +machine without enabling access to all of them for every Django installation. + +There's no limit on how many modules you put in the ``templatetags`` package. +Just keep in mind that a :ttag:`{% load %}` statement will load +tags/filters for the given Python module name, not the name of the app. + +To be a valid tag library, the module must contain a module-level variable +named ``register`` that is a ``template.Library`` instance, in which all the +tags and filters are registered. So, near the top of your module, put the +following:: + + from django import template + + register = template.Library() + +Alternatively, template tag modules can be registered through the +``'libraries'`` argument to +:class:`~django.template.backends.django.DjangoTemplates`. This is useful if +you want to use a different label from the template tag module name when +loading template tags. It also enables you to register tags without installing +an application. + +.. admonition:: Behind the scenes + + For a ton of examples, read the source code for Django's default filters + and tags. They're in :source:`django/template/defaultfilters.py` and + :source:`django/template/defaulttags.py`, respectively. + + For more information on the :ttag:`load` tag, read its documentation. + +.. _howto-writing-custom-template-filters: + +Writing custom template filters +=============================== + +Custom filters are Python functions that take one or two arguments: + +* The value of the variable (input) -- not necessarily a string. +* The value of the argument -- this can have a default value, or be left + out altogether. + +For example, in the filter ``{{ var|foo:"bar" }}``, the filter ``foo`` would be +passed the variable ``var`` and the argument ``"bar"``. + +Since the template language doesn't provide exception handling, any exception +raised from a template filter will be exposed as a server error. Thus, filter +functions should avoid raising exceptions if there is a reasonable fallback +value to return. In case of input that represents a clear bug in a template, +raising an exception may still be better than silent failure which hides the +bug. + +Here's an example filter definition:: + + def cut(value, arg): + """Removes all values of arg from the given string""" + return value.replace(arg, "") + +And here's an example of how that filter would be used: + +.. code-block:: html+django + + {{ somevariable|cut:"0" }} + +Most filters don't take arguments. In this case, leave the argument out of your +function:: + + def lower(value): # Only one argument. + """Converts a string into all lowercase""" + return value.lower() + +Registering custom filters +-------------------------- + +.. method:: django.template.Library.filter() + +Once you've written your filter definition, you need to register it with +your ``Library`` instance, to make it available to Django's template language:: + + register.filter("cut", cut) + register.filter("lower", lower) + +The ``Library.filter()`` method takes two arguments: + +1. The name of the filter -- a string. +2. The compilation function -- a Python function (not the name of the + function as a string). + +You can use ``register.filter()`` as a decorator instead:: + + @register.filter(name="cut") + def cut(value, arg): + return value.replace(arg, "") + + + @register.filter + def lower(value): + return value.lower() + +If you leave off the ``name`` argument, as in the second example above, Django +will use the function's name as the filter name. + +Finally, ``register.filter()`` also accepts three keyword arguments, +``is_safe``, ``needs_autoescape``, and ``expects_localtime``. These arguments +are described in :ref:`filters and auto-escaping ` and +:ref:`filters and time zones ` below. + +Template filters that expect strings +------------------------------------ + +.. method:: django.template.defaultfilters.stringfilter() + +If you're writing a template filter that only expects a string as the first +argument, you should use the decorator ``stringfilter``. This will +convert an object to its string value before being passed to your function:: + + from django import template + from django.template.defaultfilters import stringfilter + + register = template.Library() + + + @register.filter + @stringfilter + def lower(value): + return value.lower() + +This way, you'll be able to pass, say, an integer to this filter, and it +won't cause an ``AttributeError`` (because integers don't have ``lower()`` +methods). + +.. _filters-auto-escaping: + +Filters and auto-escaping +------------------------- + +When writing a custom filter, give some thought to how the filter will interact +with Django's auto-escaping behavior. Note that two types of strings can be +passed around inside the template code: + +* **Raw strings** are the native Python strings. On output, they're escaped if + auto-escaping is in effect and presented unchanged, otherwise. + +* **Safe strings** are strings that have been marked safe from further + escaping at output time. Any necessary escaping has already been done. + They're commonly used for output that contains raw HTML that is intended + to be interpreted as-is on the client side. + + Internally, these strings are of type + :class:`~django.utils.safestring.SafeString`. You can test for them + using code like:: + + from django.utils.safestring import SafeString + + if isinstance(value, SafeString): + # Do something with the "safe" string. + ... + +Template filter code falls into one of two situations: + +1. Your filter does not introduce any HTML-unsafe characters (``<``, ``>``, + ``'``, ``"`` or ``&``) into the result that were not already present. In + this case, you can let Django take care of all the auto-escaping + handling for you. All you need to do is set the ``is_safe`` flag to ``True`` + when you register your filter function, like so:: + + @register.filter(is_safe=True) + def myfilter(value): + return value + + This flag tells Django that if a "safe" string is passed into your + filter, the result will still be "safe" and if a non-safe string is + passed in, Django will automatically escape it, if necessary. + + You can think of this as meaning "this filter is safe -- it doesn't + introduce any possibility of unsafe HTML." + + The reason ``is_safe`` is necessary is because there are plenty of + normal string operations that will turn a ``SafeData`` object back into + a normal ``str`` object and, rather than try to catch them all, which would + be very difficult, Django repairs the damage after the filter has completed. + + For example, suppose you have a filter that adds the string ``xx`` to + the end of any input. Since this introduces no dangerous HTML characters + to the result (aside from any that were already present), you should + mark your filter with ``is_safe``:: + + @register.filter(is_safe=True) + def add_xx(value): + return "%sxx" % value + + When this filter is used in a template where auto-escaping is enabled, + Django will escape the output whenever the input is not already marked + as "safe". + + By default, ``is_safe`` is ``False``, and you can omit it from any filters + where it isn't required. + + Be careful when deciding if your filter really does leave safe strings + as safe. If you're *removing* characters, you might inadvertently leave + unbalanced HTML tags or entities in the result. For example, removing a + ``>`` from the input might turn ```` into ```. + +.. _howto-writing-custom-template-tags: + +Writing custom template tags +============================ + +Tags are more complex than filters, because tags can do anything. Django +provides a number of shortcuts that make writing most types of tags easier. +First we'll explore those shortcuts, then explain how to write a tag from +scratch for those cases when the shortcuts aren't powerful enough. + +.. _howto-custom-template-tags-simple-tags: + +Simple tags +----------- + +.. method:: django.template.Library.simple_tag() + +Many template tags take a number of arguments -- strings or template variables +-- and return a result after doing some processing based solely on +the input arguments and some external information. For example, a +``current_time`` tag might accept a format string and return the time as a +string formatted accordingly. + +To ease the creation of these types of tags, Django provides a helper function, +``simple_tag``. This function, which is a method of +``django.template.Library``, takes a function that accepts any number of +arguments, wraps it in a ``render`` function and the other necessary bits +mentioned above and registers it with the template system. + +Our ``current_time`` function could thus be written like this:: + + import datetime + from django import template + + register = template.Library() + + + @register.simple_tag + def current_time(format_string): + return datetime.datetime.now().strftime(format_string) + +A few things to note about the ``simple_tag`` helper function: + +* Checking for the required number of arguments, etc., has already been + done by the time our function is called, so we don't need to do that. +* The quotes around the argument (if any) have already been stripped away, + so we receive a plain string. +* If the argument was a template variable, our function is passed the + current value of the variable, not the variable itself. + +Unlike other tag utilities, ``simple_tag`` passes its output through +:func:`~django.utils.html.conditional_escape` if the template context is in +autoescape mode, to ensure correct HTML and protect you from XSS +vulnerabilities. + +If additional escaping is not desired, you will need to use +:func:`~django.utils.safestring.mark_safe` if you are absolutely sure that your +code does not contain XSS vulnerabilities. For building small HTML snippets, +use of :func:`~django.utils.html.format_html` instead of ``mark_safe()`` is +strongly recommended. + +If your template tag needs to access the current context, you can use the +``takes_context`` argument when registering your tag:: + + @register.simple_tag(takes_context=True) + def current_time(context, format_string): + timezone = context["timezone"] + return your_get_current_time_method(timezone, format_string) + +Note that the first argument *must* be called ``context``. + +For more information on how the ``takes_context`` option works, see the section +on :ref:`inclusion tags`. + +If you need to rename your tag, you can provide a custom name for it:: + + register.simple_tag(lambda x: x - 1, name="minusone") + + + @register.simple_tag(name="minustwo") + def some_function(value): + return value - 2 + +``simple_tag`` functions may accept any number of positional or keyword +arguments. For example:: + + @register.simple_tag + def my_tag(a, b, *args, **kwargs): + warning = kwargs["warning"] + profile = kwargs["profile"] + ... + return ... + +Then in the template any number of arguments, separated by spaces, may be +passed to the template tag. Like in Python, the values for keyword arguments +are set using the equal sign ("``=``") and must be provided after the +positional arguments. For example: + +.. code-block:: html+django + + {% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %} + +It's possible to store the tag results in a template variable rather than +directly outputting it. This is done by using the ``as`` argument followed by +the variable name. Doing so enables you to output the content yourself where +you see fit: + +.. code-block:: html+django + + {% current_time "%Y-%m-%d %I:%M %p" as the_time %} +

The time is {{ the_time }}.

+ +.. _howto-custom-template-tags-inclusion-tags: + +Inclusion tags +-------------- + +.. method:: django.template.Library.inclusion_tag() + +Another common type of template tag is the type that displays some data by +rendering *another* template. For example, Django's admin interface uses custom +template tags to display the buttons along the bottom of the "add/change" form +pages. Those buttons always look the same, but the link targets change +depending on the object being edited -- so they're a perfect case for using a +small template that is filled with details from the current object. (In the +admin's case, this is the ``submit_row`` tag.) + +These sorts of tags are called "inclusion tags". + +Writing inclusion tags is probably best demonstrated by example. Let's write a +tag that outputs a list of choices for a given ``Poll`` object, such as was +created in the :ref:`tutorials `. We'll use the tag like this: + +.. code-block:: html+django + + {% show_results poll %} + +...and the output will be something like this: + +.. code-block:: html + +
    +
  • First choice
  • +
  • Second choice
  • +
  • Third choice
  • +
+ +First, define the function that takes the argument and produces a dictionary of +data for the result. The important point here is we only need to return a +dictionary, not anything more complex. This will be used as a template context +for the template fragment. Example:: + + def show_results(poll): + choices = poll.choice_set.all() + return {"choices": choices} + +Next, create the template used to render the tag's output. This template is a +fixed feature of the tag: the tag writer specifies it, not the template +designer. Following our example, the template is very short: + +.. code-block:: html+django + +
    + {% for choice in choices %} +
  • {{ choice }}
  • + {% endfor %} +
+ +Now, create and register the inclusion tag by calling the ``inclusion_tag()`` +method on a ``Library`` object. Following our example, if the above template is +in a file called ``results.html`` in a directory that's searched by the +template loader, we'd register the tag like this:: + + # Here, register is a django.template.Library instance, as before + @register.inclusion_tag("results.html") + def show_results(poll): + ... + +Alternatively it is possible to register the inclusion tag using a +:class:`django.template.Template` instance:: + + from django.template.loader import get_template + + t = get_template("results.html") + register.inclusion_tag(t)(show_results) + +...when first creating the function. + +Sometimes, your inclusion tags might require a large number of arguments, +making it a pain for template authors to pass in all the arguments and remember +their order. To solve this, Django provides a ``takes_context`` option for +inclusion tags. If you specify ``takes_context`` in creating a template tag, +the tag will have no required arguments, and the underlying Python function +will have one argument -- the template context as of when the tag was called. + +For example, say you're writing an inclusion tag that will always be used in a +context that contains ``home_link`` and ``home_title`` variables that point +back to the main page. Here's what the Python function would look like:: + + @register.inclusion_tag("link.html", takes_context=True) + def jump_link(context): + return { + "link": context["home_link"], + "title": context["home_title"], + } + +Note that the first parameter to the function *must* be called ``context``. + +In that ``register.inclusion_tag()`` line, we specified ``takes_context=True`` +and the name of the template. Here's what the template ``link.html`` might look +like: + +.. code-block:: html+django + + Jump directly to
{{ title }}. + +Then, any time you want to use that custom tag, load its library and call it +without any arguments, like so: + +.. code-block:: html+django + + {% jump_link %} + +Note that when you're using ``takes_context=True``, there's no need to pass +arguments to the template tag. It automatically gets access to the context. + +The ``takes_context`` parameter defaults to ``False``. When it's set to +``True``, the tag is passed the context object, as in this example. That's the +only difference between this case and the previous ``inclusion_tag`` example. + +``inclusion_tag`` functions may accept any number of positional or keyword +arguments. For example:: + + @register.inclusion_tag("my_template.html") + def my_tag(a, b, *args, **kwargs): + warning = kwargs["warning"] + profile = kwargs["profile"] + ... + return ... + +Then in the template any number of arguments, separated by spaces, may be +passed to the template tag. Like in Python, the values for keyword arguments +are set using the equal sign ("``=``") and must be provided after the +positional arguments. For example: + +.. code-block:: html+django + + {% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %} + +Advanced custom template tags +----------------------------- + +Sometimes the basic features for custom template tag creation aren't enough. +Don't worry, Django gives you complete access to the internals required to build +a template tag from the ground up. + +A quick overview +---------------- + +The template system works in a two-step process: compiling and rendering. To +define a custom template tag, you specify how the compilation works and how +the rendering works. + +When Django compiles a template, it splits the raw template text into +''nodes''. Each node is an instance of ``django.template.Node`` and has +a ``render()`` method. A compiled template is a list of ``Node`` objects. When +you call ``render()`` on a compiled template object, the template calls +``render()`` on each ``Node`` in its node list, with the given context. The +results are all concatenated together to form the output of the template. + +Thus, to define a custom template tag, you specify how the raw template tag is +converted into a ``Node`` (the compilation function), and what the node's +``render()`` method does. + +Writing the compilation function +-------------------------------- + +For each template tag the template parser encounters, it calls a Python +function with the tag contents and the parser object itself. This function is +responsible for returning a ``Node`` instance based on the contents of the tag. + +For example, let's write a full implementation of our template tag, +``{% current_time %}``, that displays the current date/time, formatted according +to a parameter given in the tag, in :func:`~time.strftime` syntax. It's a good +idea to decide the tag syntax before anything else. In our case, let's say the +tag should be used like this: + +.. code-block:: html+django + +

The time is {% current_time "%Y-%m-%d %I:%M %p" %}.

+ +The parser for this function should grab the parameter and create a ``Node`` +object:: + + from django import template + + + def do_current_time(parser, token): + try: + # split_contents() knows not to split quoted strings. + tag_name, format_string = token.split_contents() + except ValueError: + raise template.TemplateSyntaxError( + "%r tag requires a single argument" % token.contents.split()[0] + ) + if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): + raise template.TemplateSyntaxError( + "%r tag's argument should be in quotes" % tag_name + ) + return CurrentTimeNode(format_string[1:-1]) + +Notes: + +* ``parser`` is the template parser object. We don't need it in this + example. + +* ``token.contents`` is a string of the raw contents of the tag. In our + example, it's ``'current_time "%Y-%m-%d %I:%M %p"'``. + +* The ``token.split_contents()`` method separates the arguments on spaces + while keeping quoted strings together. The more straightforward + ``token.contents.split()`` wouldn't be as robust, as it would naively + split on *all* spaces, including those within quoted strings. It's a good + idea to always use ``token.split_contents()``. + +* This function is responsible for raising + ``django.template.TemplateSyntaxError``, with helpful messages, for + any syntax error. + +* The ``TemplateSyntaxError`` exceptions use the ``tag_name`` variable. + Don't hard-code the tag's name in your error messages, because that + couples the tag's name to your function. ``token.contents.split()[0]`` + will ''always'' be the name of your tag -- even when the tag has no + arguments. + +* The function returns a ``CurrentTimeNode`` with everything the node needs + to know about this tag. In this case, it passes the argument -- + ``"%Y-%m-%d %I:%M %p"``. The leading and trailing quotes from the + template tag are removed in ``format_string[1:-1]``. + +* The parsing is very low-level. The Django developers have experimented + with writing small frameworks on top of this parsing system, using + techniques such as EBNF grammars, but those experiments made the template + engine too slow. It's low-level because that's fastest. + +Writing the renderer +-------------------- + +The second step in writing custom tags is to define a ``Node`` subclass that +has a ``render()`` method. + +Continuing the above example, we need to define ``CurrentTimeNode``:: + + import datetime + from django import template + + + class CurrentTimeNode(template.Node): + def __init__(self, format_string): + self.format_string = format_string + + def render(self, context): + return datetime.datetime.now().strftime(self.format_string) + +Notes: + +* ``__init__()`` gets the ``format_string`` from ``do_current_time()``. + Always pass any options/parameters/arguments to a ``Node`` via its + ``__init__()``. + +* The ``render()`` method is where the work actually happens. + +* ``render()`` should generally fail silently, particularly in a production + environment. In some cases however, particularly if + ``context.template.engine.debug`` is ``True``, this method may raise an + exception to make debugging easier. For example, several core tags raise + ``django.template.TemplateSyntaxError`` if they receive the wrong number or + type of arguments. + +Ultimately, this decoupling of compilation and rendering results in an +efficient template system, because a template can render multiple contexts +without having to be parsed multiple times. + +.. _tags-auto-escaping: + +Auto-escaping considerations +---------------------------- + +The output from template tags is **not** automatically run through the +auto-escaping filters (with the exception of +:meth:`~django.template.Library.simple_tag` as described above). However, there +are still a couple of things you should keep in mind when writing a template +tag. + +If the ``render()`` method of your template tag stores the result in a context +variable (rather than returning the result in a string), it should take care +to call ``mark_safe()`` if appropriate. When the variable is ultimately +rendered, it will be affected by the auto-escape setting in effect at the +time, so content that should be safe from further escaping needs to be marked +as such. + +Also, if your template tag creates a new context for performing some +sub-rendering, set the auto-escape attribute to the current context's value. +The ``__init__`` method for the ``Context`` class takes a parameter called +``autoescape`` that you can use for this purpose. For example:: + + from django.template import Context + + + def render(self, context): + # ... + new_context = Context({"var": obj}, autoescape=context.autoescape) + # ... Do something with new_context ... + +This is not a very common situation, but it's useful if you're rendering a +template yourself. For example:: + + def render(self, context): + t = context.template.engine.get_template("small_fragment.html") + return t.render(Context({"var": obj}, autoescape=context.autoescape)) + +If we had neglected to pass in the current ``context.autoescape`` value to our +new ``Context`` in this example, the results would have *always* been +automatically escaped, which may not be the desired behavior if the template +tag is used inside a :ttag:`{% autoescape off %}` block. + +.. _template_tag_thread_safety: + +Thread-safety considerations +---------------------------- + +Once a node is parsed, its ``render`` method may be called any number of times. +Since Django is sometimes run in multi-threaded environments, a single node may +be simultaneously rendering with different contexts in response to two separate +requests. Therefore, it's important to make sure your template tags are thread +safe. + +To make sure your template tags are thread safe, you should never store state +information on the node itself. For example, Django provides a builtin +:ttag:`cycle` template tag that cycles among a list of given strings each time +it's rendered: + +.. code-block:: html+django + + {% for o in some_list %} + + ... + + {% endfor %} + +A naive implementation of ``CycleNode`` might look something like this:: + + import itertools + from django import template + + + class CycleNode(template.Node): + def __init__(self, cyclevars): + self.cycle_iter = itertools.cycle(cyclevars) + + def render(self, context): + return next(self.cycle_iter) + +But, suppose we have two templates rendering the template snippet from above at +the same time: + +#. Thread 1 performs its first loop iteration, ``CycleNode.render()`` + returns 'row1' +#. Thread 2 performs its first loop iteration, ``CycleNode.render()`` + returns 'row2' +#. Thread 1 performs its second loop iteration, ``CycleNode.render()`` + returns 'row1' +#. Thread 2 performs its second loop iteration, ``CycleNode.render()`` + returns 'row2' + +The CycleNode is iterating, but it's iterating globally. As far as Thread 1 +and Thread 2 are concerned, it's always returning the same value. This is +not what we want! + +To address this problem, Django provides a ``render_context`` that's associated +with the ``context`` of the template that is currently being rendered. The +``render_context`` behaves like a Python dictionary, and should be used to +store ``Node`` state between invocations of the ``render`` method. + +Let's refactor our ``CycleNode`` implementation to use the ``render_context``:: + + class CycleNode(template.Node): + def __init__(self, cyclevars): + self.cyclevars = cyclevars + + def render(self, context): + if self not in context.render_context: + context.render_context[self] = itertools.cycle(self.cyclevars) + cycle_iter = context.render_context[self] + return next(cycle_iter) + +Note that it's perfectly safe to store global information that will not change +throughout the life of the ``Node`` as an attribute. In the case of +``CycleNode``, the ``cyclevars`` argument doesn't change after the ``Node`` is +instantiated, so we don't need to put it in the ``render_context``. But state +information that is specific to the template that is currently being rendered, +like the current iteration of the ``CycleNode``, should be stored in the +``render_context``. + +.. note:: + Notice how we used ``self`` to scope the ``CycleNode`` specific information + within the ``render_context``. There may be multiple ``CycleNodes`` in a + given template, so we need to be careful not to clobber another node's + state information. The easiest way to do this is to always use ``self`` as + the key into ``render_context``. If you're keeping track of several state + variables, make ``render_context[self]`` a dictionary. + +Registering the tag +------------------- + +Finally, register the tag with your module's ``Library`` instance, as explained +in :ref:`writing custom template tags` +above. Example:: + + register.tag("current_time", do_current_time) + +The ``tag()`` method takes two arguments: + +1. The name of the template tag -- a string. If this is left out, the + name of the compilation function will be used. +2. The compilation function -- a Python function (not the name of the + function as a string). + +As with filter registration, it is also possible to use this as a decorator:: + + @register.tag(name="current_time") + def do_current_time(parser, token): + ... + + + @register.tag + def shout(parser, token): + ... + +If you leave off the ``name`` argument, as in the second example above, Django +will use the function's name as the tag name. + +Passing template variables to the tag +------------------------------------- + +Although you can pass any number of arguments to a template tag using +``token.split_contents()``, the arguments are all unpacked as +string literals. A little more work is required in order to pass dynamic +content (a template variable) to a template tag as an argument. + +While the previous examples have formatted the current time into a string and +returned the string, suppose you wanted to pass in a +:class:`~django.db.models.DateTimeField` from an object and have the template +tag format that date-time: + +.. code-block:: html+django + +

This post was last updated at {% format_time blog_entry.date_updated "%Y-%m-%d %I:%M %p" %}.

+ +Initially, ``token.split_contents()`` will return three values: + +1. The tag name ``format_time``. +2. The string ``'blog_entry.date_updated'`` (without the surrounding + quotes). +3. The formatting string ``'"%Y-%m-%d %I:%M %p"'``. The return value from + ``split_contents()`` will include the leading and trailing quotes for + string literals like this. + +Now your tag should begin to look like this:: + + from django import template + + + def do_format_time(parser, token): + try: + # split_contents() knows not to split quoted strings. + tag_name, date_to_be_formatted, format_string = token.split_contents() + except ValueError: + raise template.TemplateSyntaxError( + "%r tag requires exactly two arguments" % token.contents.split()[0] + ) + if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): + raise template.TemplateSyntaxError( + "%r tag's argument should be in quotes" % tag_name + ) + return FormatTimeNode(date_to_be_formatted, format_string[1:-1]) + +You also have to change the renderer to retrieve the actual contents of the +``date_updated`` property of the ``blog_entry`` object. This can be +accomplished by using the ``Variable()`` class in ``django.template``. + +To use the ``Variable`` class, instantiate it with the name of the variable to +be resolved, and then call ``variable.resolve(context)``. So, for example:: + + class FormatTimeNode(template.Node): + def __init__(self, date_to_be_formatted, format_string): + self.date_to_be_formatted = template.Variable(date_to_be_formatted) + self.format_string = format_string + + def render(self, context): + try: + actual_date = self.date_to_be_formatted.resolve(context) + return actual_date.strftime(self.format_string) + except template.VariableDoesNotExist: + return "" + +Variable resolution will throw a ``VariableDoesNotExist`` exception if it +cannot resolve the string passed to it in the current context of the page. + +Setting a variable in the context +--------------------------------- + +The above examples output a value. Generally, it's more flexible if your +template tags set template variables instead of outputting values. That way, +template authors can reuse the values that your template tags create. + +To set a variable in the context, use dictionary assignment on the context +object in the ``render()`` method. Here's an updated version of +``CurrentTimeNode`` that sets a template variable ``current_time`` instead of +outputting it:: + + import datetime + from django import template + + + class CurrentTimeNode2(template.Node): + def __init__(self, format_string): + self.format_string = format_string + + def render(self, context): + context["current_time"] = datetime.datetime.now().strftime(self.format_string) + return "" + +Note that ``render()`` returns the empty string. ``render()`` should always +return string output. If all the template tag does is set a variable, +``render()`` should return the empty string. + +Here's how you'd use this new version of the tag: + +.. code-block:: html+django + + {% current_time "%Y-%m-%d %I:%M %p" %}

The time is {{ current_time }}.

+ +.. admonition:: Variable scope in context + + Any variable set in the context will only be available in the same + ``block`` of the template in which it was assigned. This behavior is + intentional; it provides a scope for variables so that they don't conflict + with context in other blocks. + +But, there's a problem with ``CurrentTimeNode2``: The variable name +``current_time`` is hard-coded. This means you'll need to make sure your +template doesn't use ``{{ current_time }}`` anywhere else, because the +``{% current_time %}`` will blindly overwrite that variable's value. A cleaner +solution is to make the template tag specify the name of the output variable, +like so: + +.. code-block:: html+django + + {% current_time "%Y-%m-%d %I:%M %p" as my_current_time %} +

The current time is {{ my_current_time }}.

+ +To do that, you'll need to refactor both the compilation function and ``Node`` +class, like so:: + + import re + + + class CurrentTimeNode3(template.Node): + def __init__(self, format_string, var_name): + self.format_string = format_string + self.var_name = var_name + + def render(self, context): + context[self.var_name] = datetime.datetime.now().strftime(self.format_string) + return "" + + + def do_current_time(parser, token): + # This version uses a regular expression to parse tag contents. + try: + # Splitting by None == splitting by spaces. + tag_name, arg = token.contents.split(None, 1) + except ValueError: + raise template.TemplateSyntaxError( + "%r tag requires arguments" % token.contents.split()[0] + ) + m = re.search(r"(.*?) as (\w+)", arg) + if not m: + raise template.TemplateSyntaxError("%r tag had invalid arguments" % tag_name) + format_string, var_name = m.groups() + if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): + raise template.TemplateSyntaxError( + "%r tag's argument should be in quotes" % tag_name + ) + return CurrentTimeNode3(format_string[1:-1], var_name) + +The difference here is that ``do_current_time()`` grabs the format string and +the variable name, passing both to ``CurrentTimeNode3``. + +Finally, if you only need to have a simple syntax for your custom +context-updating template tag, consider using the +:meth:`~django.template.Library.simple_tag` shortcut, which supports assigning +the tag results to a template variable. + +Parsing until another block tag +------------------------------- + +Template tags can work in tandem. For instance, the standard +:ttag:`{% comment %}` tag hides everything until ``{% endcomment %}``. +To create a template tag such as this, use ``parser.parse()`` in your +compilation function. + +Here's how a simplified ``{% comment %}`` tag might be implemented:: + + def do_comment(parser, token): + nodelist = parser.parse(("endcomment",)) + parser.delete_first_token() + return CommentNode() + + + class CommentNode(template.Node): + def render(self, context): + return "" + +.. note:: + The actual implementation of :ttag:`{% comment %}` is slightly + different in that it allows broken template tags to appear between + ``{% comment %}`` and ``{% endcomment %}``. It does so by calling + ``parser.skip_past('endcomment')`` instead of ``parser.parse(('endcomment',))`` + followed by ``parser.delete_first_token()``, thus avoiding the generation of a + node list. + +``parser.parse()`` takes a tuple of names of block tags ''to parse until''. It +returns an instance of ``django.template.NodeList``, which is a list of +all ``Node`` objects that the parser encountered ''before'' it encountered +any of the tags named in the tuple. + +In ``"nodelist = parser.parse(('endcomment',))"`` in the above example, +``nodelist`` is a list of all nodes between the ``{% comment %}`` and +``{% endcomment %}``, not counting ``{% comment %}`` and ``{% endcomment %}`` +themselves. + +After ``parser.parse()`` is called, the parser hasn't yet "consumed" the +``{% endcomment %}`` tag, so the code needs to explicitly call +``parser.delete_first_token()``. + +``CommentNode.render()`` returns an empty string. Anything between +``{% comment %}`` and ``{% endcomment %}`` is ignored. + +Parsing until another block tag, and saving contents +---------------------------------------------------- + +In the previous example, ``do_comment()`` discarded everything between +``{% comment %}`` and ``{% endcomment %}``. Instead of doing that, it's +possible to do something with the code between block tags. + +For example, here's a custom template tag, ``{% upper %}``, that capitalizes +everything between itself and ``{% endupper %}``. + +Usage: + +.. code-block:: html+django + + {% upper %}This will appear in uppercase, {{ your_name }}.{% endupper %} + +As in the previous example, we'll use ``parser.parse()``. But this time, we +pass the resulting ``nodelist`` to the ``Node``:: + + def do_upper(parser, token): + nodelist = parser.parse(("endupper",)) + parser.delete_first_token() + return UpperNode(nodelist) + + + class UpperNode(template.Node): + def __init__(self, nodelist): + self.nodelist = nodelist + + def render(self, context): + output = self.nodelist.render(context) + return output.upper() + +The only new concept here is the ``self.nodelist.render(context)`` in +``UpperNode.render()``. + +For more examples of complex rendering, see the source code of +:ttag:`{% for %}` in :source:`django/template/defaulttags.py` and +:ttag:`{% if %}` in :source:`django/template/smartif.py`. diff --git a/testbed/django__django/docs/howto/delete-app.txt b/testbed/django__django/docs/howto/delete-app.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1dac4f179399141cf05d40c7b3c95e1811b14db --- /dev/null +++ b/testbed/django__django/docs/howto/delete-app.txt @@ -0,0 +1,29 @@ +================================== +How to delete a Django application +================================== + +Django provides the ability to group sets of features into Python packages +called :doc:`applications`. When requirements change, apps +may become obsolete or unnecessary. The following steps will help you delete an +application safely. + +#. Remove all references to the app (imports, foreign keys etc.). + +#. Remove all models from the corresponding ``models.py`` file. + +#. Create relevant migrations by running :djadmin:`makemigrations`. This step + generates a migration that deletes tables for the removed models, and any + other required migration for updating relationships connected to those + models. + +#. :ref:`Squash ` out references to the app in other apps' + migrations. + +#. Apply migrations locally, runs tests, and verify the correctness of your + project. + +#. Deploy/release your updated Django project. + +#. Remove the app from :setting:`INSTALLED_APPS`. + +#. Finally, remove the app's directory. diff --git a/testbed/django__django/docs/howto/deployment/asgi/daphne.txt b/testbed/django__django/docs/howto/deployment/asgi/daphne.txt new file mode 100644 index 0000000000000000000000000000000000000000..a8867955f8e1204ef8ef40fa5524583b776cda4b --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/asgi/daphne.txt @@ -0,0 +1,52 @@ +============================= +How to use Django with Daphne +============================= + +:pypi:`Daphne ` is a pure-Python ASGI server for UNIX, maintained by +members of the Django project. It acts as the reference server for ASGI. + +Installing Daphne +=================== + +You can install Daphne with ``pip``: + +.. code-block:: shell + + python -m pip install daphne + +Running Django in Daphne +======================== + +When Daphne is installed, a ``daphne`` command is available which starts the +Daphne server process. At its simplest, Daphne needs to be called with the +location of a module containing an ASGI application object, followed by what +the application is called (separated by a colon). + +For a typical Django project, invoking Daphne would look like: + +.. code-block:: shell + + daphne myproject.asgi:application + +This will start one process listening on ``127.0.0.1:8000``. It requires that +your project be on the Python path; to ensure that run this command from the +same directory as your ``manage.py`` file. + +.. _daphne-runserver: + +Integration with ``runserver`` +============================== + +Daphne provides a :djadmin:`runserver` command to serve your site under ASGI +during development. + +This can be enabled by adding ``daphne`` to the start of your +:setting:`INSTALLED_APPS` and adding an ``ASGI_APPLICATION`` setting pointing +to your ASGI application object:: + + INSTALLED_APPS = [ + "daphne", + ..., + ] + + ASGI_APPLICATION = "myproject.asgi.application" diff --git a/testbed/django__django/docs/howto/deployment/asgi/hypercorn.txt b/testbed/django__django/docs/howto/deployment/asgi/hypercorn.txt new file mode 100644 index 0000000000000000000000000000000000000000..ea5ce3cc72c6fc5a3fb3c037ea0dafa8a0ee39d0 --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/asgi/hypercorn.txt @@ -0,0 +1,38 @@ +================================ +How to use Django with Hypercorn +================================ + +Hypercorn_ is an ASGI server that supports HTTP/1, HTTP/2, and HTTP/3 +with an emphasis on protocol support. + +Installing Hypercorn +==================== + +You can install Hypercorn with ``pip``: + +.. code-block:: shell + + python -m pip install hypercorn + +Running Django in Hypercorn +=========================== + +When Hypercorn is installed, a ``hypercorn`` command is available +which runs ASGI applications. Hypercorn needs to be called with the +location of a module containing an ASGI application object, followed +by what the application is called (separated by a colon). + +For a typical Django project, invoking Hypercorn would look like: + +.. code-block:: shell + + hypercorn myproject.asgi:application + +This will start one process listening on ``127.0.0.1:8000``. It +requires that your project be on the Python path; to ensure that run +this command from the same directory as your ``manage.py`` file. + +For more advanced usage, please read the `Hypercorn documentation +`_. + +.. _Hypercorn: https://pgjones.gitlab.io/hypercorn/ diff --git a/testbed/django__django/docs/howto/deployment/asgi/index.txt b/testbed/django__django/docs/howto/deployment/asgi/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..6015554350cfb1f6929ce9123d9e3ffca30e86d9 --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/asgi/index.txt @@ -0,0 +1,73 @@ +======================= +How to deploy with ASGI +======================= + +As well as WSGI, Django also supports deploying on ASGI_, the emerging Python +standard for asynchronous web servers and applications. + +.. _ASGI: https://asgi.readthedocs.io/en/latest/ + +Django's :djadmin:`startproject` management command sets up a default ASGI +configuration for you, which you can tweak as needed for your project, and +direct any ASGI-compliant application server to use. + +Django includes getting-started documentation for the following ASGI servers: + +.. toctree:: + :maxdepth: 1 + + daphne + hypercorn + uvicorn + +The ``application`` object +========================== + +Like WSGI, ASGI has you supply an ``application`` callable which +the application server uses to communicate with your code. It's commonly +provided as an object named ``application`` in a Python module accessible to +the server. + +The :djadmin:`startproject` command creates a file +:file:`/asgi.py` that contains such an ``application`` callable. + +It's not used by the development server (``runserver``), but can be used by +any ASGI server either in development or in production. + +ASGI servers usually take the path to the application callable as a string; +for most Django projects, this will look like ``myproject.asgi:application``. + +.. warning:: + + While Django's default ASGI handler will run all your code in a synchronous + thread, if you choose to run your own async handler you must be aware of + async-safety. + + Do not call blocking synchronous functions or libraries in any async code. + Django prevents you from doing this with the parts of Django that are not + async-safe, but the same may not be true of third-party apps or Python + libraries. + +Configuring the settings module +=============================== + +When the ASGI server loads your application, Django needs to import the +settings module — that's where your entire application is defined. + +Django uses the :envvar:`DJANGO_SETTINGS_MODULE` environment variable to locate +the appropriate settings module. It must contain the dotted path to the +settings module. You can use a different value for development and production; +it all depends on how you organize your settings. + +If this variable isn't set, the default :file:`asgi.py` sets it to +``mysite.settings``, where ``mysite`` is the name of your project. + +Applying ASGI middleware +======================== + +To apply ASGI middleware, or to embed Django in another ASGI application, you +can wrap Django's ``application`` object in the ``asgi.py`` file. For example:: + + from some_asgi_library import AmazingMiddleware + + application = AmazingMiddleware(application) diff --git a/testbed/django__django/docs/howto/deployment/asgi/uvicorn.txt b/testbed/django__django/docs/howto/deployment/asgi/uvicorn.txt new file mode 100644 index 0000000000000000000000000000000000000000..cfce90fec1fcb59509debeaf1446a459e3d9a711 --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/asgi/uvicorn.txt @@ -0,0 +1,59 @@ +============================== +How to use Django with Uvicorn +============================== + +Uvicorn_ is an ASGI server based on ``uvloop`` and ``httptools``, with an +emphasis on speed. + +Installing Uvicorn +================== + +You can install Uvicorn with ``pip``: + +.. code-block:: shell + + python -m pip install uvicorn + +Running Django in Uvicorn +========================= + +When Uvicorn is installed, a ``uvicorn`` command is available which runs ASGI +applications. Uvicorn needs to be called with the location of a module +containing an ASGI application object, followed by what the application is +called (separated by a colon). + +For a typical Django project, invoking Uvicorn would look like: + +.. code-block:: shell + + python -m uvicorn myproject.asgi:application + +This will start one process listening on ``127.0.0.1:8000``. It requires that +your project be on the Python path; to ensure that run this command from the +same directory as your ``manage.py`` file. + +In development mode, you can add ``--reload`` to cause the server to reload any +time a file is changed on disk. + +For more advanced usage, please read the `Uvicorn documentation `_. + +Deploying Django using Uvicorn and Gunicorn +=========================================== + +Gunicorn_ is a robust web server that implements process monitoring and automatic +restarts. This can be useful when running Uvicorn in a production environment. + +To install Uvicorn and Gunicorn, use the following: + +.. code-block:: shell + + python -m pip install uvicorn gunicorn + +Then start Gunicorn using the Uvicorn worker class like this: + +.. code-block:: shell + + python -m gunicorn myproject.asgi:application -k uvicorn.workers.UvicornWorker + +.. _Uvicorn: https://www.uvicorn.org/ +.. _Gunicorn: https://gunicorn.org/ diff --git a/testbed/django__django/docs/howto/deployment/checklist.txt b/testbed/django__django/docs/howto/deployment/checklist.txt new file mode 100644 index 0000000000000000000000000000000000000000..75c9735e862efdd87e195200867a698a36a26c0c --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/checklist.txt @@ -0,0 +1,268 @@ +==================== +Deployment checklist +==================== + +The internet is a hostile environment. Before deploying your Django project, +you should take some time to review your settings, with security, performance, +and operations in mind. + +Django includes many :doc:`security features `. Some are +built-in and always enabled. Others are optional because they aren't always +appropriate, or because they're inconvenient for development. For example, +forcing HTTPS may not be suitable for all websites, and it's impractical for +local development. + +Performance optimizations are another category of trade-offs with convenience. +For instance, caching is useful in production, less so for local development. +Error reporting needs are also widely different. + +The following checklist includes settings that: + +- must be set properly for Django to provide the expected level of security; +- are expected to be different in each environment; +- enable optional security features; +- enable performance optimizations; +- provide error reporting. + +Many of these settings are sensitive and should be treated as confidential. If +you're releasing the source code for your project, a common practice is to +publish suitable settings for development, and to use a private settings +module for production. + +Run ``manage.py check --deploy`` +================================ + +Some of the checks described below can be automated using the :option:`check +--deploy` option. Be sure to run it against your production settings file as +described in the option's documentation. + +Critical settings +================= + +:setting:`SECRET_KEY` +--------------------- + +**The secret key must be a large random value and it must be kept secret.** + +Make sure that the key used in production isn't used anywhere else and avoid +committing it to source control. This reduces the number of vectors from which +an attacker may acquire the key. + +Instead of hardcoding the secret key in your settings module, consider loading +it from an environment variable:: + + import os + + SECRET_KEY = os.environ["SECRET_KEY"] + +or from a file:: + + with open("/etc/secret_key.txt") as f: + SECRET_KEY = f.read().strip() + +If rotating secret keys, you may use :setting:`SECRET_KEY_FALLBACKS`:: + + import os + + SECRET_KEY = os.environ["CURRENT_SECRET_KEY"] + SECRET_KEY_FALLBACKS = [ + os.environ["OLD_SECRET_KEY"], + ] + +Ensure that old secret keys are removed from ``SECRET_KEY_FALLBACKS`` in a +timely manner. + +:setting:`DEBUG` +---------------- + +**You must never enable debug in production.** + +You're certainly developing your project with :setting:`DEBUG = True `, +since this enables handy features like full tracebacks in your browser. + +For a production environment, though, this is a really bad idea, because it +leaks lots of information about your project: excerpts of your source code, +local variables, settings, libraries used, etc. + +Environment-specific settings +============================= + +:setting:`ALLOWED_HOSTS` +------------------------ + +When :setting:`DEBUG = False `, Django doesn't work at all without a +suitable value for :setting:`ALLOWED_HOSTS`. + +This setting is required to protect your site against some CSRF attacks. If +you use a wildcard, you must perform your own validation of the ``Host`` HTTP +header, or otherwise ensure that you aren't vulnerable to this category of +attacks. + +You should also configure the web server that sits in front of Django to +validate the host. It should respond with a static error page or ignore +requests for incorrect hosts instead of forwarding the request to Django. This +way you'll avoid spurious errors in your Django logs (or emails if you have +error reporting configured that way). For example, on nginx you might set up a +default server to return "444 No Response" on an unrecognized host: + +.. code-block:: nginx + + server { + listen 80 default_server; + return 444; + } + +:setting:`CACHES` +----------------- + +If you're using a cache, connection parameters may be different in development +and in production. Django defaults to per-process :ref:`local-memory caching +` which may not be desirable. + +Cache servers often have weak authentication. Make sure they only accept +connections from your application servers. + +:setting:`DATABASES` +-------------------- + +Database connection parameters are probably different in development and in +production. + +Database passwords are very sensitive. You should protect them exactly like +:setting:`SECRET_KEY`. + +For maximum security, make sure database servers only accept connections from +your application servers. + +If you haven't set up backups for your database, do it right now! + +:setting:`EMAIL_BACKEND` and related settings +--------------------------------------------- + +If your site sends emails, these values need to be set correctly. + +By default, Django sends email from webmaster@localhost and root@localhost. +However, some mail providers reject email from these addresses. To use +different sender addresses, modify the :setting:`DEFAULT_FROM_EMAIL` and +:setting:`SERVER_EMAIL` settings. + +:setting:`STATIC_ROOT` and :setting:`STATIC_URL` +------------------------------------------------ + +Static files are automatically served by the development server. In +production, you must define a :setting:`STATIC_ROOT` directory where +:djadmin:`collectstatic` will copy them. + +See :doc:`/howto/static-files/index` for more information. + +:setting:`MEDIA_ROOT` and :setting:`MEDIA_URL` +---------------------------------------------- + +Media files are uploaded by your users. They're untrusted! Make sure your web +server never attempts to interpret them. For instance, if a user uploads a +``.php`` file, the web server shouldn't execute it. + +Now is a good time to check your backup strategy for these files. + +HTTPS +===== + +Any website which allows users to log in should enforce site-wide HTTPS to +avoid transmitting access tokens in clear. In Django, access tokens include +the login/password, the session cookie, and password reset tokens. (You can't +do much to protect password reset tokens if you're sending them by email.) + +Protecting sensitive areas such as the user account or the admin isn't +sufficient, because the same session cookie is used for HTTP and HTTPS. Your +web server must redirect all HTTP traffic to HTTPS, and only transmit HTTPS +requests to Django. + +Once you've set up HTTPS, enable the following settings. + +:setting:`CSRF_COOKIE_SECURE` +----------------------------- + +Set this to ``True`` to avoid transmitting the CSRF cookie over HTTP +accidentally. + +:setting:`SESSION_COOKIE_SECURE` +-------------------------------- + +Set this to ``True`` to avoid transmitting the session cookie over HTTP +accidentally. + +Performance optimizations +========================= + +Setting :setting:`DEBUG = False ` disables several features that are +only useful in development. In addition, you can tune the following settings. + +Sessions +-------- + +Consider using :ref:`cached sessions ` to improve +performance. + +If using database-backed sessions, regularly :ref:`clear old sessions +` to avoid storing unnecessary data. + +:setting:`CONN_MAX_AGE` +----------------------- + +Enabling :ref:`persistent database connections +` can result in a nice speed-up when +connecting to the database accounts for a significant part of the request +processing time. + +This helps a lot on virtualized hosts with limited network performance. + +:setting:`TEMPLATES` +-------------------- + +Enabling the cached template loader often improves performance drastically, as +it avoids compiling each template every time it needs to be rendered. When +:setting:`DEBUG = False `, the cached template loader is enabled +automatically. See :class:`django.template.loaders.cached.Loader` for more +information. + +Error reporting +=============== + +By the time you push your code to production, it's hopefully robust, but you +can't rule out unexpected errors. Thankfully, Django can capture errors and +notify you accordingly. + +:setting:`LOGGING` +------------------ + +Review your logging configuration before putting your website in production, +and check that it works as expected as soon as you have received some traffic. + +See :doc:`/topics/logging` for details on logging. + +:setting:`ADMINS` and :setting:`MANAGERS` +----------------------------------------- + +:setting:`ADMINS` will be notified of 500 errors by email. + +:setting:`MANAGERS` will be notified of 404 errors. +:setting:`IGNORABLE_404_URLS` can help filter out spurious reports. + +See :doc:`/howto/error-reporting` for details on error reporting by email. + +.. admonition:: Error reporting by email doesn't scale very well + + Consider using an error monitoring system such as Sentry_ before your + inbox is flooded by reports. Sentry can also aggregate logs. + + .. _Sentry: https://docs.sentry.io/ + +Customize the default error views +--------------------------------- + +Django includes default views and templates for several HTTP error codes. You +may want to override the default templates by creating the following templates +in your root template directory: ``404.html``, ``500.html``, ``403.html``, and +``400.html``. The :ref:`default error views ` that use these +templates should suffice for 99% of web applications, but you can +:ref:`customize them ` as well. diff --git a/testbed/django__django/docs/howto/deployment/index.txt b/testbed/django__django/docs/howto/deployment/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..e2fadba5b907e36a55844edbf78fe35913e3848f --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/index.txt @@ -0,0 +1,42 @@ +==================== +How to deploy Django +==================== + +Django is full of shortcuts to make web developers' lives easier, but all +those tools are of no use if you can't easily deploy your sites. Since Django's +inception, ease of deployment has been a major goal. + +There are many options for deploying your Django application, based on your +architecture or your particular business needs, but that discussion is outside +the scope of what Django can give you as guidance. + +Django, being a web framework, needs a web server in order to operate. And +since most web servers don't natively speak Python, we need an interface to +make that communication happen. + +Django currently supports two interfaces: WSGI and ASGI. + +* `WSGI`_ is the main Python standard for communicating between web servers and + applications, but it only supports synchronous code. + +* `ASGI`_ is the new, asynchronous-friendly standard that will allow your + Django site to use asynchronous Python features, and asynchronous Django + features as they are developed. + +You should also consider how you will handle :doc:`static files +` for your application, and how to handle +:doc:`error reporting`. + +Finally, before you deploy your application to production, you should run +through our :doc:`deployment checklist` to ensure that your +configurations are suitable. + +.. _WSGI: https://wsgi.readthedocs.io/en/latest/ +.. _ASGI: https://asgi.readthedocs.io/en/latest/ + +.. toctree:: + :maxdepth: 2 + + wsgi/index + asgi/index + checklist diff --git a/testbed/django__django/docs/howto/deployment/wsgi/apache-auth.txt b/testbed/django__django/docs/howto/deployment/wsgi/apache-auth.txt new file mode 100644 index 0000000000000000000000000000000000000000..0629b785c5872707276bec584a695ca105029464 --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/wsgi/apache-auth.txt @@ -0,0 +1,138 @@ +============================================================== +How to authenticate against Django's user database from Apache +============================================================== + +Since keeping multiple authentication databases in sync is a common problem when +dealing with Apache, you can configure Apache to authenticate against Django's +:doc:`authentication system ` directly. This requires Apache +version >= 2.2 and mod_wsgi >= 2.0. For example, you could: + +* Serve static/media files directly from Apache only to authenticated users. + +* Authenticate access to a Subversion_ repository against Django users with + a certain permission. + +* Allow certain users to connect to a WebDAV share created with mod_dav_. + +.. note:: + If you have installed a :ref:`custom user model ` and + want to use this default auth handler, it must support an ``is_active`` + attribute. If you want to use group based authorization, your custom user + must have a relation named 'groups', referring to a related object that has + a 'name' field. You can also specify your own custom mod_wsgi + auth handler if your custom cannot conform to these requirements. + +.. _Subversion: https://subversion.apache.org/ +.. _mod_dav: https://httpd.apache.org/docs/2.2/mod/mod_dav.html + +Authentication with ``mod_wsgi`` +================================ + +.. note:: + + The use of ``WSGIApplicationGroup %{GLOBAL}`` in the configurations below + presumes that your Apache instance is running only one Django application. + If you are running more than one Django application, please refer to the + `Defining Application Groups`_ section of the mod_wsgi docs for more + information about this setting. + +Make sure that mod_wsgi is installed and activated and that you have +followed the steps to set up :doc:`Apache with mod_wsgi +`. + +Next, edit your Apache configuration to add a location that you want +only authenticated users to be able to view: + +.. code-block:: apache + + WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py + WSGIPythonPath /path/to/mysite.com + + WSGIProcessGroup %{GLOBAL} + WSGIApplicationGroup %{GLOBAL} + + + AuthType Basic + AuthName "Top Secret" + Require valid-user + AuthBasicProvider wsgi + WSGIAuthUserScript /path/to/mysite.com/mysite/wsgi.py + + +The ``WSGIAuthUserScript`` directive tells mod_wsgi to execute the +``check_password`` function in specified wsgi script, passing the user name and +password that it receives from the prompt. In this example, the +``WSGIAuthUserScript`` is the same as the ``WSGIScriptAlias`` that defines your +application :doc:`that is created by django-admin startproject +`. + +.. admonition:: Using Apache 2.2 with authentication + + Make sure that ``mod_auth_basic`` and ``mod_authz_user`` are loaded. + + These might be compiled statically into Apache, or you might need to use + LoadModule to load them dynamically in your ``httpd.conf``: + + .. code-block:: apache + + LoadModule auth_basic_module modules/mod_auth_basic.so + LoadModule authz_user_module modules/mod_authz_user.so + +Finally, edit your WSGI script ``mysite.wsgi`` to tie Apache's authentication +to your site's authentication mechanisms by importing the ``check_password`` +function:: + + import os + + os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" + + from django.contrib.auth.handlers.modwsgi import check_password + + from django.core.handlers.wsgi import WSGIHandler + + application = WSGIHandler() + + +Requests beginning with ``/secret/`` will now require a user to authenticate. + +The mod_wsgi `access control mechanisms documentation`_ provides additional +details and information about alternative methods of authentication. + +.. _Defining Application Groups: https://modwsgi.readthedocs.io/en/develop/user-guides/configuration-guidelines.html#defining-application-groups +.. _access control mechanisms documentation: https://modwsgi.readthedocs.io/en/develop/user-guides/access-control-mechanisms.html + +Authorization with ``mod_wsgi`` and Django groups +------------------------------------------------- + +mod_wsgi also provides functionality to restrict a particular location to +members of a group. + +In this case, the Apache configuration should look like this: + +.. code-block:: apache + + WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py + + WSGIProcessGroup %{GLOBAL} + WSGIApplicationGroup %{GLOBAL} + + + AuthType Basic + AuthName "Top Secret" + AuthBasicProvider wsgi + WSGIAuthUserScript /path/to/mysite.com/mysite/wsgi.py + WSGIAuthGroupScript /path/to/mysite.com/mysite/wsgi.py + Require group secret-agents + Require valid-user + + +To support the ``WSGIAuthGroupScript`` directive, the same WSGI script +``mysite.wsgi`` must also import the ``groups_for_user`` function which +returns a list groups the given user belongs to. + +.. code-block:: python + + from django.contrib.auth.handlers.modwsgi import check_password, groups_for_user + +Requests for ``/secret/`` will now also require user to be a member of the +"secret-agents" group. diff --git a/testbed/django__django/docs/howto/deployment/wsgi/gunicorn.txt b/testbed/django__django/docs/howto/deployment/wsgi/gunicorn.txt new file mode 100644 index 0000000000000000000000000000000000000000..60d6620ea34d23de671fb28e6aac0bbcde5f6718 --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/wsgi/gunicorn.txt @@ -0,0 +1,36 @@ +=============================== +How to use Django with Gunicorn +=============================== + +Gunicorn_ ('Green Unicorn') is a pure-Python WSGI server for UNIX. It has no +dependencies and can be installed using ``pip``. + +.. _Gunicorn: https://gunicorn.org/ + +Installing Gunicorn +=================== + +Install gunicorn by running ``python -m pip install gunicorn``. For more +details, see the `gunicorn documentation`_. + +.. _gunicorn documentation: https://docs.gunicorn.org/en/latest/install.html + +Running Django in Gunicorn as a generic WSGI application +======================================================== + +When Gunicorn is installed, a ``gunicorn`` command is available which starts +the Gunicorn server process. The simplest invocation of gunicorn is to pass the +location of a module containing a WSGI application object named +``application``, which for a typical Django project would look like: + +.. code-block:: shell + + gunicorn myproject.wsgi + +This will start one process running one thread listening on ``127.0.0.1:8000``. +It requires that your project be on the Python path; the simplest way to ensure +that is to run this command from the same directory as your ``manage.py`` file. + +See Gunicorn's `deployment documentation`_ for additional tips. + +.. _deployment documentation: https://docs.gunicorn.org/en/latest/deploy.html diff --git a/testbed/django__django/docs/howto/deployment/wsgi/index.txt b/testbed/django__django/docs/howto/deployment/wsgi/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..502a25386628b0cecb881c8440684ce0e01301b5 --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/wsgi/index.txt @@ -0,0 +1,84 @@ +======================= +How to deploy with WSGI +======================= + +Django's primary deployment platform is WSGI_, the Python standard for web +servers and applications. + +.. _WSGI: https://wsgi.readthedocs.io/en/latest/ + +Django's :djadmin:`startproject` management command sets up a minimal default +WSGI configuration for you, which you can tweak as needed for your project, +and direct any WSGI-compliant application server to use. + +Django includes getting-started documentation for the following WSGI servers: + +.. toctree:: + :maxdepth: 1 + + gunicorn + uwsgi + modwsgi + apache-auth + +The ``application`` object +========================== + +The key concept of deploying with WSGI is the ``application`` callable which +the application server uses to communicate with your code. It's commonly +provided as an object named ``application`` in a Python module accessible to +the server. + +The :djadmin:`startproject` command creates a file +:file:`/wsgi.py` that contains such an ``application`` callable. + +It's used both by Django's development server and in production WSGI +deployments. + +WSGI servers obtain the path to the ``application`` callable from their +configuration. Django's built-in server, namely the :djadmin:`runserver` +command, reads it from the :setting:`WSGI_APPLICATION` setting. By default, it's +set to ``.wsgi.application``, which points to the ``application`` +callable in :file:`/wsgi.py`. + +Configuring the settings module +=============================== + +When the WSGI server loads your application, Django needs to import the +settings module — that's where your entire application is defined. + +Django uses the :envvar:`DJANGO_SETTINGS_MODULE` environment variable to +locate the appropriate settings module. It must contain the dotted path to the +settings module. You can use a different value for development and production; +it all depends on how you organize your settings. + +If this variable isn't set, the default :file:`wsgi.py` sets it to +``mysite.settings``, where ``mysite`` is the name of your project. That's how +:djadmin:`runserver` discovers the default settings file by default. + +.. note:: + + Since environment variables are process-wide, this doesn't work when you + run multiple Django sites in the same process. This happens with mod_wsgi. + + To avoid this problem, use mod_wsgi's daemon mode with each site in its + own daemon process, or override the value from the environment by + enforcing ``os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"`` in + your :file:`wsgi.py`. + + +Applying WSGI middleware +======================== + +To apply :pep:`WSGI middleware +<3333#middleware-components-that-play-both-sides>` you can wrap the application +object. For instance you could add these lines at the bottom of +:file:`wsgi.py`:: + + from helloworld.wsgi import HelloWorldApplication + + application = HelloWorldApplication(application) + +You could also replace the Django WSGI application with a custom WSGI +application that later delegates to the Django WSGI application, if you want +to combine a Django application with a WSGI application of another framework. diff --git a/testbed/django__django/docs/howto/deployment/wsgi/modwsgi.txt b/testbed/django__django/docs/howto/deployment/wsgi/modwsgi.txt new file mode 100644 index 0000000000000000000000000000000000000000..c81b3df48a9ebc672c053b5e1255cf6e1733bd3c --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/wsgi/modwsgi.txt @@ -0,0 +1,230 @@ +============================================== +How to use Django with Apache and ``mod_wsgi`` +============================================== + +Deploying Django with Apache_ and `mod_wsgi`_ is a tried and tested way to get +Django into production. + +.. _Apache: https://httpd.apache.org/ +.. _mod_wsgi: https://modwsgi.readthedocs.io/en/develop/ + +mod_wsgi is an Apache module which can host any Python WSGI_ application, +including Django. Django will work with any version of Apache which supports +mod_wsgi. + +.. _WSGI: https://wsgi.readthedocs.io/en/latest/ + +The `official mod_wsgi documentation`_ is your source for all the details about +how to use mod_wsgi. You'll probably want to start with the `installation and +configuration documentation`_. + +.. _official mod_wsgi documentation: https://modwsgi.readthedocs.io/ +.. _installation and configuration documentation: https://modwsgi.readthedocs.io/en/develop/installation.html + +Basic configuration +=================== + +Once you've got mod_wsgi installed and activated, edit your Apache server's +`httpd.conf`_ file and add the following. + +.. _httpd.conf: https://cwiki.apache.org/confluence/display/httpd/DistrosDefaultLayout + +.. code-block:: apache + + WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py + WSGIPythonHome /path/to/venv + WSGIPythonPath /path/to/mysite.com + + + + Require all granted + + + +The first bit in the ``WSGIScriptAlias`` line is the base URL path you want to +serve your application at (``/`` indicates the root url), and the second is the +location of a "WSGI file" -- see below -- on your system, usually inside of +your project package (``mysite`` in this example). This tells Apache to serve +any request below the given URL using the WSGI application defined in that +file. + +If you install your project's Python dependencies inside a :mod:`virtual +environment `, add the path using ``WSGIPythonHome``. See the `mod_wsgi +virtual environment guide`_ for more details. + +The ``WSGIPythonPath`` line ensures that your project package is available for +import on the Python path; in other words, that ``import mysite`` works. + +The ```` piece ensures that Apache can access your :file:`wsgi.py` +file. + +Next we'll need to ensure this :file:`wsgi.py` with a WSGI application object +exists. As of Django version 1.4, :djadmin:`startproject` will have created one +for you; otherwise, you'll need to create it. See the :doc:`WSGI overview +documentation` for the default contents you +should put in this file, and what else you can add to it. + +.. _mod_wsgi virtual environment guide: https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html + +.. warning:: + + If multiple Django sites are run in a single mod_wsgi process, all of them + will use the settings of whichever one happens to run first. This can be + solved by changing:: + + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") + + in ``wsgi.py``, to:: + + os.environ["DJANGO_SETTINGS_MODULE"] = "{{ project_name }}.settings" + + or by :ref:`using mod_wsgi daemon mode` and ensuring that each + site runs in its own daemon process. + +.. admonition:: Fixing ``UnicodeEncodeError`` for file uploads + + If you get a ``UnicodeEncodeError`` when uploading or writing files with + file names or content that contains non-ASCII characters, make sure Apache + is configured to support UTF-8 encoding: + + .. code-block:: shell + + export LANG='en_US.UTF-8' + export LC_ALL='en_US.UTF-8' + + A common location to put this configuration is ``/etc/apache2/envvars``. + + Alternatively, if you are :ref:`using mod_wsgi daemon mode` + you can add ``lang`` and ``locale`` options to the ``WSGIDaemonProcess`` + directive: + + .. code-block:: text + + WSGIDaemonProcess example.com lang='en_US.UTF-8' locale='en_US.UTF-8' + + See the :ref:`unicode-files` section of the Unicode reference guide for + details. + +.. _daemon-mode: + +Using ``mod_wsgi`` daemon mode +============================== + +"Daemon mode" is the recommended mode for running mod_wsgi (on non-Windows +platforms). To create the required daemon process group and delegate the +Django instance to run in it, you will need to add appropriate +``WSGIDaemonProcess`` and ``WSGIProcessGroup`` directives. A further change +required to the above configuration if you use daemon mode is that you can't +use ``WSGIPythonPath``; instead you should use the ``python-path`` option to +``WSGIDaemonProcess``, for example: + +.. code-block:: apache + + WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com + WSGIProcessGroup example.com + +If you want to serve your project in a subdirectory +(``https://example.com/mysite`` in this example), you can add ``WSGIScriptAlias`` +to the configuration above: + +.. code-block:: apache + + WSGIScriptAlias /mysite /path/to/mysite.com/mysite/wsgi.py process-group=example.com + +See the official mod_wsgi documentation for `details on setting up daemon +mode`_. + +.. _details on setting up daemon mode: https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html#delegation-to-daemon-process + +.. _serving-files: + +Serving files +============= + +Django doesn't serve files itself; it leaves that job to whichever web +server you choose. + +We recommend using a separate web server -- i.e., one that's not also running +Django -- for serving media. Here are some good choices: + +* Nginx_ +* A stripped-down version of Apache_ + +If, however, you have no option but to serve media files on the same Apache +``VirtualHost`` as Django, you can set up Apache to serve some URLs as +static media, and others using the mod_wsgi interface to Django. + +This example sets up Django at the site root, but serves ``robots.txt``, +``favicon.ico``, and anything in the ``/static/`` and ``/media/`` URL space as +a static file. All other URLs will be served using mod_wsgi: + +.. code-block:: apache + + Alias /robots.txt /path/to/mysite.com/static/robots.txt + Alias /favicon.ico /path/to/mysite.com/static/favicon.ico + + Alias /media/ /path/to/mysite.com/media/ + Alias /static/ /path/to/mysite.com/static/ + + + Require all granted + + + + Require all granted + + + WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py + + + + Require all granted + + + +.. _Nginx: https://nginx.org/en/ +.. _Apache: https://httpd.apache.org/ + +.. More details on configuring a mod_wsgi site to serve static files can be found +.. in the mod_wsgi documentation on `hosting static files`_. + +.. _hosting static files: https://modwsgi.readthedocs.io/en/develop/user-guides/configuration-guidelines.html#hosting-of-static-files + +.. _serving-the-admin-files: + +Serving the admin files +======================= + +When :mod:`django.contrib.staticfiles` is in :setting:`INSTALLED_APPS`, the +Django development server automatically serves the static files of the +admin app (and any other installed apps). This is however not the case when you +use any other server arrangement. You're responsible for setting up Apache, or +whichever web server you're using, to serve the admin files. + +The admin files live in (:source:`django/contrib/admin/static/admin`) of the +Django distribution. + +We **strongly** recommend using :mod:`django.contrib.staticfiles` to handle the +admin files (along with a web server as outlined in the previous section; this +means using the :djadmin:`collectstatic` management command to collect the +static files in :setting:`STATIC_ROOT`, and then configuring your web server to +serve :setting:`STATIC_ROOT` at :setting:`STATIC_URL`), but here are three +other approaches: + +1. Create a symbolic link to the admin static files from within your + document root (this may require ``+FollowSymLinks`` in your Apache + configuration). + +2. Use an ``Alias`` directive, as demonstrated above, to alias the appropriate + URL (probably :setting:`STATIC_URL` + ``admin/``) to the actual location of + the admin files. + +3. Copy the admin static files so that they live within your Apache + document root. + +Authenticating against Django's user database from Apache +========================================================= + +Django provides a handler to allow Apache to authenticate users directly +against Django's authentication backends. See the :doc:`mod_wsgi authentication +documentation `. diff --git a/testbed/django__django/docs/howto/deployment/wsgi/uwsgi.txt b/testbed/django__django/docs/howto/deployment/wsgi/uwsgi.txt new file mode 100644 index 0000000000000000000000000000000000000000..2bb49b285c61b932b6294030e4e790b03b415399 --- /dev/null +++ b/testbed/django__django/docs/howto/deployment/wsgi/uwsgi.txt @@ -0,0 +1,118 @@ +============================ +How to use Django with uWSGI +============================ + +uWSGI_ is a fast, self-healing and developer/sysadmin-friendly application +container server coded in pure C. + +.. _uWSGI: https://uwsgi-docs.readthedocs.io/ + +.. seealso:: + + The uWSGI docs offer a `tutorial`_ covering Django, nginx, and uWSGI (one + possible deployment setup of many). The docs below are focused on how to + integrate Django with uWSGI. + + .. _tutorial: https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html + +Prerequisite: uWSGI +=================== + +The uWSGI wiki describes several `installation procedures`_. Using pip, the +Python package manager, you can install any uWSGI version with a single +command. For example: + +.. code-block:: console + + # Install current stable version. + $ python -m pip install uwsgi + + # Or install LTS (long term support). + $ python -m pip install https://projects.unbit.it/downloads/uwsgi-lts.tar.gz + +.. _installation procedures: https://uwsgi-docs.readthedocs.io/en/latest/Install.html + +uWSGI model +----------- + +uWSGI operates on a client-server model. Your web server (e.g., nginx, Apache) +communicates with a ``django-uwsgi`` "worker" process to serve dynamic content. + +Configuring and starting the uWSGI server for Django +---------------------------------------------------- + +uWSGI supports multiple ways to configure the process. See uWSGI's +`configuration documentation`_. + +.. _configuration documentation: https://uwsgi.readthedocs.io/en/latest/Configuration.html + +Here's an example command to start a uWSGI server: + +.. code-block:: shell + + uwsgi --chdir=/path/to/your/project \ + --module=mysite.wsgi:application \ + --env DJANGO_SETTINGS_MODULE=mysite.settings \ + --master --pidfile=/tmp/project-master.pid \ + --socket=127.0.0.1:49152 \ # can also be a file + --processes=5 \ # number of worker processes + --uid=1000 --gid=2000 \ # if root, uwsgi can drop privileges + --harakiri=20 \ # respawn processes taking more than 20 seconds + --max-requests=5000 \ # respawn processes after serving 5000 requests + --vacuum \ # clear environment on exit + --home=/path/to/virtual/env \ # optional path to a virtual environment + --daemonize=/var/log/uwsgi/yourproject.log # background the process + +This assumes you have a top-level project package named ``mysite``, and +within it a module :file:`mysite/wsgi.py` that contains a WSGI ``application`` +object. This is the layout you'll have if you ran ``django-admin +startproject mysite`` (using your own project name in place of ``mysite``) with +a recent version of Django. If this file doesn't exist, you'll need to create +it. See the :doc:`/howto/deployment/wsgi/index` documentation for the default +contents you should put in this file and what else you can add to it. + +The Django-specific options here are: + +* ``chdir``: The path to the directory that needs to be on Python's import + path -- i.e., the directory containing the ``mysite`` package. +* ``module``: The WSGI module to use -- probably the ``mysite.wsgi`` module + that :djadmin:`startproject` creates. +* ``env``: Should probably contain at least :envvar:`DJANGO_SETTINGS_MODULE`. +* ``home``: Optional path to your project virtual environment. + +Example ini configuration file: + +.. code-block:: ini + + [uwsgi] + chdir=/path/to/your/project + module=mysite.wsgi:application + master=True + pidfile=/tmp/project-master.pid + vacuum=True + max-requests=5000 + daemonize=/var/log/uwsgi/yourproject.log + +Example ini configuration file usage: + +.. code-block:: shell + + uwsgi --ini uwsgi.ini + +.. admonition:: Fixing ``UnicodeEncodeError`` for file uploads + + If you get a ``UnicodeEncodeError`` when uploading files with file names + that contain non-ASCII characters, make sure uWSGI is configured to accept + non-ASCII file names by adding this to your ``uwsgi.ini``: + + .. code-block:: ini + + env = LANG=en_US.UTF-8 + + See the :ref:`unicode-files` section of the Unicode reference guide for + details. + +See the uWSGI docs on `managing the uWSGI process`_ for information on +starting, stopping and reloading the uWSGI workers. + +.. _managing the uWSGI process: https://uwsgi-docs.readthedocs.io/en/latest/Management.html diff --git a/testbed/django__django/docs/howto/error-reporting.txt b/testbed/django__django/docs/howto/error-reporting.txt new file mode 100644 index 0000000000000000000000000000000000000000..875e56a51d87363175f6d593b31e5522facba00c --- /dev/null +++ b/testbed/django__django/docs/howto/error-reporting.txt @@ -0,0 +1,405 @@ +============================= +How to manage error reporting +============================= + +When you're running a public site you should always turn off the +:setting:`DEBUG` setting. That will make your server run much faster, and will +also prevent malicious users from seeing details of your application that can be +revealed by the error pages. + +However, running with :setting:`DEBUG` set to ``False`` means you'll never see +errors generated by your site -- everyone will instead see your public error +pages. You need to keep track of errors that occur in deployed sites, so Django +can be configured to create reports with details about those errors. + +Email reports +============= + +Server errors +------------- + +When :setting:`DEBUG` is ``False``, Django will email the users listed in the +:setting:`ADMINS` setting whenever your code raises an unhandled exception and +results in an internal server error (strictly speaking, for any response with +an HTTP status code of 500 or greater). This gives the administrators immediate +notification of any errors. The :setting:`ADMINS` will get a description of the +error, a complete Python traceback, and details about the HTTP request that +caused the error. + +.. note:: + + In order to send email, Django requires a few settings telling it + how to connect to your mail server. At the very least, you'll need + to specify :setting:`EMAIL_HOST` and possibly + :setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD`, + though other settings may be also required depending on your mail + server's configuration. Consult :doc:`the Django settings + documentation ` for a full list of email-related + settings. + +By default, Django will send email from root@localhost. However, some mail +providers reject all email from this address. To use a different sender +address, modify the :setting:`SERVER_EMAIL` setting. + +To activate this behavior, put the email addresses of the recipients in the +:setting:`ADMINS` setting. + +.. seealso:: + + Server error emails are sent using the logging framework, so you can + customize this behavior by :doc:`customizing your logging configuration + `. + +404 errors +---------- + +Django can also be configured to email errors about broken links (404 "page +not found" errors). Django sends emails about 404 errors when: + +* :setting:`DEBUG` is ``False``; + +* Your :setting:`MIDDLEWARE` setting includes + :class:`django.middleware.common.BrokenLinkEmailsMiddleware`. + +If those conditions are met, Django will email the users listed in the +:setting:`MANAGERS` setting whenever your code raises a 404 and the request has +a referer. It doesn't bother to email for 404s that don't have a referer -- +those are usually people typing in broken URLs or broken web bots. It also +ignores 404s when the referer is equal to the requested URL, since this +behavior is from broken web bots too. + +.. note:: + + :class:`~django.middleware.common.BrokenLinkEmailsMiddleware` must appear + before other middleware that intercepts 404 errors, such as + :class:`~django.middleware.locale.LocaleMiddleware` or + :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`. + Put it toward the top of your :setting:`MIDDLEWARE` setting. + +You can tell Django to stop reporting particular 404s by tweaking the +:setting:`IGNORABLE_404_URLS` setting. It should be a list of compiled +regular expression objects. For example:: + + import re + + IGNORABLE_404_URLS = [ + re.compile(r"\.(php|cgi)$"), + re.compile(r"^/phpmyadmin/"), + ] + +In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be +reported. Neither will any URL starting with ``/phpmyadmin/``. + +The following example shows how to exclude some conventional URLs that browsers and +crawlers often request:: + + import re + + IGNORABLE_404_URLS = [ + re.compile(r"^/apple-touch-icon.*\.png$"), + re.compile(r"^/favicon\.ico$"), + re.compile(r"^/robots\.txt$"), + ] + +(Note that these are regular expressions, so we put a backslash in front of +periods to escape them.) + +If you'd like to customize the behavior of +:class:`django.middleware.common.BrokenLinkEmailsMiddleware` further (for +example to ignore requests coming from web crawlers), you should subclass it +and override its methods. + +.. seealso:: + + 404 errors are logged using the logging framework. By default, these log + records are ignored, but you can use them for error reporting by writing a + handler and :doc:`configuring logging ` appropriately. + +.. _filtering-error-reports: + +Filtering error reports +======================= + +.. warning:: + + Filtering sensitive data is a hard problem, and it's nearly impossible to + guarantee that sensitive data won't leak into an error report. Therefore, + error reports should only be available to trusted team members and you + should avoid transmitting error reports unencrypted over the internet + (such as through email). + +Filtering sensitive information +------------------------------- + +.. currentmodule:: django.views.decorators.debug + +Error reports are really helpful for debugging errors, so it is generally +useful to record as much relevant information about those errors as possible. +For example, by default Django records the `full traceback`_ for the +exception raised, each `traceback frame`_’s local variables, and the +:class:`~django.http.HttpRequest`’s :ref:`attributes`. + +However, sometimes certain types of information may be too sensitive and thus +may not be appropriate to be kept track of, for example a user's password or +credit card number. So in addition to filtering out settings that appear to be +sensitive as described in the :setting:`DEBUG` documentation, Django offers a +set of function decorators to help you control which information should be +filtered out of error reports in a production environment (that is, where +:setting:`DEBUG` is set to ``False``): :func:`sensitive_variables` and +:func:`sensitive_post_parameters`. + +.. _`full traceback`: https://en.wikipedia.org/wiki/Stack_trace +.. _`traceback frame`: https://en.wikipedia.org/wiki/Stack_frame + +.. function:: 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(): + ... + + .. admonition:: 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): + ... + + .. warning:: + + Due to the machinery needed to cross the sync/async boundary, + :func:`~asgiref.sync.sync_to_async` and + :func:`~asgiref.sync.async_to_sync` are **not** compatible with + ``sensitive_variables()``. + + If using these adapters with sensitive variables, ensure to audit + exception reporting, and consider implementing a :ref:`custom filter + ` if necessary. + + .. versionchanged:: 5.0 + + Support for wrapping ``async`` functions was added. + +.. function:: sensitive_post_parameters(*parameters) + + If one of your views receives an :class:`~django.http.HttpRequest` object + with :attr:`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 :mod:`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. + + .. versionchanged:: 5.0 + + Support for wrapping ``async`` functions was added. + +.. _custom-error-reports: + +Custom error reports +-------------------- + +All :func:`sensitive_variables` and :func:`sensitive_post_parameters` do is, +respectively, annotate the decorated function with the names of sensitive +variables and annotate the ``HttpRequest`` object with the names of sensitive +POST parameters, so that this sensitive information can later be filtered out +of reports when an error occurs. The actual filtering is done by Django's +default error reporter filter: +:class:`django.views.debug.SafeExceptionReporterFilter`. This filter uses the +decorators' annotations to replace the corresponding values with stars +(``**********``) when the error reports are produced. If you wish to +override or customize this default behavior for your entire site, you need to +define your own filter class and tell Django to use it via the +:setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` setting:: + + DEFAULT_EXCEPTION_REPORTER_FILTER = "path.to.your.CustomExceptionReporterFilter" + +You may also control in a more granular way which filter to use within any +given view by setting the ``HttpRequest``’s ``exception_reporter_filter`` +attribute:: + + def my_view(request): + if request.user.is_authenticated: + request.exception_reporter_filter = CustomExceptionReporterFilter() + ... + +.. currentmodule:: django.views.debug + +Your custom filter class needs to inherit from +:class:`django.views.debug.SafeExceptionReporterFilter` and may override the +following attributes and methods: + +.. class:: SafeExceptionReporterFilter + + .. attribute:: cleansed_substitute + + The string value to replace sensitive value with. By default it + replaces the values of sensitive variables with stars + (``**********``). + + .. attribute:: 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|HTTP_COOKIE", flags=re.IGNORECASE) + + .. versionchanged:: 4.2 + + ``HTTP_COOKIE`` was added. + + .. method:: is_active(request) + + Returns ``True`` to activate the filtering in + :meth:`get_post_parameters` and :meth:`get_traceback_frame_variables`. + By default the filter is active if :setting:`DEBUG` is ``False``. Note + that sensitive ``request.META`` values are always filtered along with + sensitive setting values, as described in the :setting:`DEBUG` + documentation. + + .. method:: get_post_parameters(request) + + Returns the filtered dictionary of POST parameters. Sensitive values + are replaced with :attr:`cleansed_substitute`. + + .. method:: get_traceback_frame_variables(request, tb_frame) + + Returns the filtered dictionary of local variables for the given + traceback frame. Sensitive values are replaced with + :attr:`cleansed_substitute`. + +If you need to customize error reports beyond filtering you may specify a +custom error reporter class by defining the +:setting:`DEFAULT_EXCEPTION_REPORTER` setting:: + + DEFAULT_EXCEPTION_REPORTER = "path.to.your.CustomExceptionReporter" + +The exception reporter is responsible for compiling the exception report data, +and formatting it as text or HTML appropriately. (The exception reporter uses +:setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` when preparing the exception +report data.) + +Your custom reporter class needs to inherit from +:class:`django.views.debug.ExceptionReporter`. + +.. class:: ExceptionReporter + + .. attribute:: html_template_path + + Property that returns a :class:`pathlib.Path` representing the absolute + filesystem path to a template for rendering the HTML representation of + the exception. Defaults to the Django provided template. + + .. attribute:: text_template_path + + Property that returns a :class:`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. + + .. method:: 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 + + .. method:: get_traceback_html() + + Return HTML version of exception report. + + Used for HTML version of debug 500 HTTP error page. + + .. method:: get_traceback_text() + + Return plain text version of exception report. + + Used for plain text version of debug 500 HTTP error page and email + reports. + +As with the filter class, you may control which exception reporter class to use +within any given view by setting the ``HttpRequest``’s +``exception_reporter_class`` attribute:: + + def my_view(request): + if request.user.is_authenticated: + request.exception_reporter_class = CustomExceptionReporter() + ... + +.. seealso:: + + You can also set up custom error reporting by writing a custom piece of + :ref:`exception middleware `. If you do write custom + error handling, it's a good idea to emulate Django's built-in error handling + and only report/log errors if :setting:`DEBUG` is ``False``. diff --git a/testbed/django__django/docs/howto/index.txt b/testbed/django__django/docs/howto/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..0034032ce25e799e71f4a0755bbefde79d983969 --- /dev/null +++ b/testbed/django__django/docs/howto/index.txt @@ -0,0 +1,42 @@ +=============== +"How-to" guides +=============== + +Here you'll find short answers to "How do I....?" types of questions. These +how-to guides don't cover topics in depth -- you'll find that material in the +:doc:`/topics/index` and the :doc:`/ref/index`. However, these guides will help +you quickly accomplish common tasks. + +.. toctree:: + :maxdepth: 1 + + auth-remote-user + csrf + custom-management-commands + custom-model-fields + custom-lookups + custom-template-backend + custom-template-tags + custom-file-storage + deployment/index + upgrade-version + error-reporting + initial-data + legacy-databases + logging + outputting-csv + outputting-pdf + overriding-templates + static-files/index + static-files/deployment + windows + writing-migrations + delete-app + +.. seealso:: + + The `Django community aggregator`_, where we aggregate content from the + global Django community. Many writers in the aggregator write this sort of + how-to material. + + .. _django community aggregator: https://www.djangoproject.com/community/ diff --git a/testbed/django__django/docs/howto/initial-data.txt b/testbed/django__django/docs/howto/initial-data.txt new file mode 100644 index 0000000000000000000000000000000000000000..af2852cc7b86ffe44fa07ccff67b99c784d0e2c8 --- /dev/null +++ b/testbed/django__django/docs/howto/initial-data.txt @@ -0,0 +1,111 @@ +====================================== +How to provide initial data for models +====================================== + +It's sometimes useful to prepopulate your database with hard-coded data when +you're first setting up an app. You can provide initial data with migrations or +fixtures. + +Provide initial data with migrations +==================================== + +To automatically load initial data for an app, create a +:ref:`data migration `. Migrations are run when setting up the +test database, so the data will be available there, subject to :ref:`some +limitations `. + +.. _initial-data-via-fixtures: + +Provide data with fixtures +========================== + +You can also provide data using :ref:`fixtures `, +however, this data isn't loaded automatically, except if you use +:attr:`.TransactionTestCase.fixtures`. + +A fixture is a collection of data that Django knows how to import into a +database. The most straightforward way of creating a fixture if you've already +got some data is to use the :djadmin:`manage.py dumpdata ` command. +Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML +(with PyYAML_ installed) documents. The :doc:`serialization documentation +` has more details about each of these supported +:ref:`serialization formats `. + +.. _PyYAML: https://pyyaml.org/ + +As an example, though, here's what a fixture for a ``Person`` model might look +like in JSON: + +.. code-block:: js + + [ + { + "model": "myapp.person", + "pk": 1, + "fields": { + "first_name": "John", + "last_name": "Lennon" + } + }, + { + "model": "myapp.person", + "pk": 2, + "fields": { + "first_name": "Paul", + "last_name": "McCartney" + } + } + ] + +And here's that same fixture as YAML: + +.. code-block:: yaml + + - model: myapp.person + pk: 1 + fields: + first_name: John + last_name: Lennon + - model: myapp.person + pk: 2 + fields: + first_name: Paul + last_name: McCartney + +You'll store this data in a ``fixtures`` directory inside your app. + +You can load data by calling :djadmin:`manage.py loaddata ` +````, where ```` is the name of the fixture file +you've created. Each time you run :djadmin:`loaddata`, the data will be read +from the fixture and reloaded into the database. Note this means that if you +change one of the rows created by a fixture and then run :djadmin:`loaddata` +again, you'll wipe out any changes you've made. + +Tell Django where to look for fixture files +------------------------------------------- + +By default, Django looks for fixtures in the ``fixtures`` directory inside each +app for, so the command ``loaddata sample`` will find the file +``my_app/fixtures/sample.json``. This works with relative paths as well, so +``loaddata my_app/sample`` will find the file +``my_app/fixtures/my_app/sample.json``. + +Django also looks for fixtures in the list of directories provided in the +:setting:`FIXTURE_DIRS` setting. + +To completely prevent default search form happening, use an absolute path to +specify the location of your fixture file, e.g. ``loaddata /path/to/sample``. + +.. admonition:: Namespace your fixture files + + Django will use the first fixture file it finds whose name matches, so if + you have fixture files with the same name in different applications, you + will be unable to distinguish between them in your ``loaddata`` commands. + The easiest way to avoid this problem is by *namespacing* your fixture + files. That is, by putting them inside a directory named for their + application, as in the relative path example above. + +.. seealso:: + + Fixtures are also used by the :ref:`testing framework + ` to help set up a consistent test environment. diff --git a/testbed/django__django/docs/howto/legacy-databases.txt b/testbed/django__django/docs/howto/legacy-databases.txt new file mode 100644 index 0000000000000000000000000000000000000000..5730a8a0593f869af73aed3f41b838bf5aa39e03 --- /dev/null +++ b/testbed/django__django/docs/howto/legacy-databases.txt @@ -0,0 +1,86 @@ +============================================== +How to integrate Django with a legacy database +============================================== + +While Django is best suited for developing new applications, it's quite +possible to integrate it into legacy databases. Django includes a couple of +utilities to automate as much of this process as possible. + +This document assumes you know the Django basics, as covered in the +:doc:`tutorial `. + +Once you've got Django set up, you'll follow this general process to integrate +with an existing database. + +Give Django your database parameters +==================================== + +You'll need to tell Django what your database connection parameters are, and +what the name of the database is. Do that by editing the :setting:`DATABASES` +setting and assigning values to the following keys for the ``'default'`` +connection: + +* :setting:`NAME` +* :setting:`ENGINE ` +* :setting:`USER` +* :setting:`PASSWORD` +* :setting:`HOST` +* :setting:`PORT` + +Auto-generate the models +======================== + +Django comes with a utility called :djadmin:`inspectdb` that can create models +by introspecting an existing database. You can view the output by running this +command: + +.. code-block:: shell + + $ python manage.py inspectdb + +Save this as a file by using standard Unix output redirection: + +.. code-block:: shell + + $ python manage.py inspectdb > models.py + +This feature is meant as a shortcut, not as definitive model generation. See the +:djadmin:`documentation of inspectdb ` for more information. + +Once you've cleaned up your models, name the file ``models.py`` and put it in +the Python package that holds your app. Then add the app to your +:setting:`INSTALLED_APPS` setting. + +By default, :djadmin:`inspectdb` creates unmanaged models. That is, +``managed = False`` in the model's ``Meta`` class tells Django not to manage +each table's creation, modification, and deletion:: + + class Person(models.Model): + id = models.IntegerField(primary_key=True) + first_name = models.CharField(max_length=70) + + class Meta: + managed = False + db_table = "CENSUS_PERSONS" + +If you do want to allow Django to manage the table's lifecycle, you'll need to +change the :attr:`~django.db.models.Options.managed` option above to ``True`` +(or remove it because ``True`` is its default value). + +Install the core Django tables +============================== + +Next, run the :djadmin:`migrate` command to install any extra needed database +records such as admin permissions and content types: + +.. code-block:: shell + + $ python manage.py migrate + +Test and tweak +============== + +Those are the basic steps -- from here you'll want to tweak the models Django +generated until they work the way you'd like. Try accessing your data via the +Django database API, and try editing objects via Django's admin site, and edit +the models file accordingly. diff --git a/testbed/django__django/docs/howto/logging.txt b/testbed/django__django/docs/howto/logging.txt new file mode 100644 index 0000000000000000000000000000000000000000..149b8bb83be3cd6dc581f9eb362c6ff98a4f6120 --- /dev/null +++ b/testbed/django__django/docs/howto/logging.txt @@ -0,0 +1,339 @@ +.. _logging-how-to: + +================================ +How to configure and use logging +================================ + +.. seealso:: + + * :ref:`Django logging reference ` + * :ref:`Django logging overview ` + +Django provides a working :ref:`default logging configuration +` that is readily extended. + +Make a basic logging call +========================= + +To send a log message from within your code, you place a logging call into it. + +.. admonition:: Don't be tempted to use logging calls in ``settings.py``. + + The way that Django logging is configured as part of the ``setup()`` + function means that logging calls placed in ``settings.py`` may not work as + expected, because *logging will not be set up at that point*. To explore + logging, use a view function as suggested in the example below. + +First, import the Python logging library, and then obtain a logger instance +with :py:func:`logging.getLogger`. Provide the ``getLogger()`` method with a +name to identify it and the records it emits. A good option is to use +``__name__`` (see :ref:`naming-loggers` below for more on this) which will +provide the name of the current Python module as a dotted path:: + + import logging + + logger = logging.getLogger(__name__) + +It's a good convention to perform this declaration at module level. + +And then in a function, for example in a view, send a record to the logger:: + + def some_view(request): + ... + if some_risky_state: + logger.warning("Platform is running at risk") + +When this code is executed, a :py:class:`~logging.LogRecord` containing that +message will be sent to the logger. If you're using Django's default logging +configuration, the message will appear in the console. + +The ``WARNING`` level used in the example above is one of several +:ref:`logging severity levels `: ``DEBUG``, +``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``. So, another example might be:: + + logger.critical("Payment system is not responding") + +.. important:: + + Records with a level lower than ``WARNING`` will not appear in the console + by default. Changing this behavior requires additional configuration. + +Customize logging configuration +=============================== + +Although Django's logging configuration works out of the box, you can control +exactly how your logs are sent to various destinations - to log files, external +services, email and so on - with some additional configuration. + +You can configure: + +* logger mappings, to determine which records are sent to which handlers +* handlers, to determine what they do with the records they receive +* filters, to provide additional control over the transfer of records, and + even modify records in-place +* formatters, to convert :class:`~logging.LogRecord` objects to a string or + other form for consumption by human beings or another system + +There are various ways of configuring logging. In Django, the +:setting:`LOGGING` setting is most commonly used. The setting uses the +:ref:`dictConfig format `, and extends the +:ref:`default logging configuration `. + +See :ref:`configuring-logging` for an explanation of how your custom settings +are merged with Django's defaults. + +See the :mod:`Python logging documentation ` for +details of other ways of configuring logging. For the sake of simplicity, this +documentation will only consider configuration via the ``LOGGING`` setting. + +.. _basic-logger-configuration: + +Basic logging configuration +--------------------------- + +When configuring logging, it makes sense to + +Create a ``LOGGING`` dictionary +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In your ``settings.py``:: + + LOGGING = { + "version": 1, # the dictConfig format version + "disable_existing_loggers": False, # retain the default loggers + } + +It nearly always makes sense to retain and extend the default logging +configuration by setting ``disable_existing_loggers`` to ``False``. + +Configure a handler +~~~~~~~~~~~~~~~~~~~ + +This example configures a single handler named ``file``, that uses Python's +:class:`~logging.FileHandler` to save logs of level ``DEBUG`` and higher to the +file ``general.log`` (at the project root): + +.. code-block:: python + :emphasize-lines: 3-8 + + LOGGING = { + # ... + "handlers": { + "file": { + "class": "logging.FileHandler", + "filename": "general.log", + }, + }, + } + +Different handler classes take different configuration options. For more +information on available handler classes, see the +:class:`~django.utils.log.AdminEmailHandler` provided by Django and the various +:py:mod:`handler classes ` provided by Python. + +Logging levels can also be set on the handlers (by default, they accept log +messages of all levels). Using the example above, adding: + +.. code-block:: python + :emphasize-lines: 4 + + { + "class": "logging.FileHandler", + "filename": "general.log", + "level": "DEBUG", + } + +would define a handler configuration that only accepts records of level +``DEBUG`` and higher. + +Configure a logger mapping +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To send records to this handler, configure a logger mapping to use it for +example: + +.. code-block:: python + :emphasize-lines: 3-8 + + LOGGING = { + # ... + "loggers": { + "": { + "level": "DEBUG", + "handlers": ["file"], + }, + }, + } + +The mapping's name determines which log records it will process. This +configuration (``''``) is *unnamed*. That means that it will process records +from *all* loggers (see :ref:`naming-loggers` below on how to use the mapping +name to determine the loggers for which it will process records). + +It will forward messages of levels ``DEBUG`` and higher to the handler named +``file``. + +Note that a logger can forward messages to multiple handlers, so the relation +between loggers and handlers is many-to-many. + +If you execute:: + + logger.debug("Attempting to connect to API") + +in your code, you will find that message in the file ``general.log`` in the +root of the project. + +Configure a formatter +~~~~~~~~~~~~~~~~~~~~~ + +By default, the final log output contains the message part of each :class:`log +record `. Use a formatter if you want to include additional +data. First name and define your formatters - this example defines +formatters named ``verbose`` and ``simple``: + +.. code-block:: python + :emphasize-lines: 3-12 + + LOGGING = { + # ... + "formatters": { + "verbose": { + "format": "{name} {levelname} {asctime} {module} {process:d} {thread:d} {message}", + "style": "{", + }, + "simple": { + "format": "{levelname} {message}", + "style": "{", + }, + }, + } + +The ``style`` keyword allows you to specify ``{`` for :meth:`str.format` or +``$`` for :class:`string.Template` formatting; the default is ``$``. + +See :ref:`logrecord-attributes` for the :class:`~logging.LogRecord` attributes +you can include. + +To apply a formatter to a handler, add a ``formatter`` entry to the handler's +dictionary referring to the formatter by name, for example: + +.. code-block:: python + :emphasize-lines: 5 + + "handlers": { + "file": { + "class": "logging.FileHandler", + "filename": "general.log", + "formatter": "verbose", + }, + } + +.. _naming-loggers: + +Use logger namespacing +~~~~~~~~~~~~~~~~~~~~~~ + +The unnamed logging configuration ``''`` captures logs from any Python +application. A named logging configuration will capture logs only from loggers +with matching names. + +The namespace of a logger instance is defined using +:py:func:`~logging.getLogger`. For example in ``views.py`` of ``my_app``:: + + logger = logging.getLogger(__name__) + +will create a logger in the ``my_app.views`` namespace. ``__name__`` allows you +to organize log messages according to their provenance within your project's +applications automatically. It also ensures that you will not experience name +collisions. + +A logger mapping named ``my_app.views`` will capture records from this logger: + +.. code-block:: python + :emphasize-lines: 4 + + LOGGING = { + # ... + "loggers": { + "my_app.views": {...}, + }, + } + +A logger mapping named ``my_app`` will be more permissive, capturing records +from loggers anywhere within the ``my_app`` namespace (including +``my_app.views``, ``my_app.utils``, and so on): + +.. code-block:: python + :emphasize-lines: 4 + + LOGGING = { + # ... + "loggers": { + "my_app": {...}, + }, + } + +You can also define logger namespacing explicitly:: + + logger = logging.getLogger("project.payment") + +and set up logger mappings accordingly. + +.. _naming-loggers-hierarchy: + +Using logger hierarchies and propagation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Logger naming is *hierarchical*. ``my_app`` is the parent of ``my_app.views``, +which is the parent of ``my_app.views.private``. Unless specified otherwise, +logger mappings will propagate the records they process to their parents - a +record from a logger in the ``my_app.views.private`` namespace will be handled +by a mapping for both ``my_app`` and ``my_app.views``. + +To manage this behavior, set the propagation key on the mappings you define:: + + LOGGING = { + # ... + "loggers": { + "my_app": { + # ... + }, + "my_app.views": { + # ... + }, + "my_app.views.private": { + # ... + "propagate": False, + }, + }, + } + +``propagate`` defaults to ``True``. In this example, the logs from +``my_app.views.private`` will not be handled by the parent, but logs from +``my_app.views`` will. + +Configure responsive logging +---------------------------- + +Logging is most useful when it contains as much information as possible, but +not information that you don't need - and how much you need depends upon what +you're doing. When you're debugging, you need a level of information that would +be excessive and unhelpful if you had to deal with it in production. + +You can configure logging to provide you with the level of detail you need, +when you need it. Rather than manually change configuration to achieve this, a +better way is to apply configuration automatically according to the +environment. + +For example, you could set an environment variable ``DJANGO_LOG_LEVEL`` +appropriately in your development and staging environments, and make use of it +in a logger mapping thus:: + + "level": os.getenv("DJANGO_LOG_LEVEL", "WARNING") + +\- so that unless the environment specifies a lower log level, this +configuration will only forward records of severity ``WARNING`` and above to +its handler. + +Other options in the configuration (such as the ``level`` or ``formatter`` +option of handlers) can be similarly managed. diff --git a/testbed/django__django/docs/howto/outputting-csv.txt b/testbed/django__django/docs/howto/outputting-csv.txt new file mode 100644 index 0000000000000000000000000000000000000000..8e4bd8108c7dfd9856a73739b07ad0dea0ee26e8 --- /dev/null +++ b/testbed/django__django/docs/howto/outputting-csv.txt @@ -0,0 +1,157 @@ +======================== +How to create CSV output +======================== + +This document explains how to output CSV (Comma Separated Values) dynamically +using Django views. To do this, you can either use the Python CSV library or the +Django template system. + +Using the Python CSV library +============================ + +Python comes with a CSV library, :mod:`csv`. The key to using it with Django is +that the :mod:`csv` module's CSV-creation capability acts on file-like objects, +and Django's :class:`~django.http.HttpResponse` objects are file-like objects. + +Here's an example:: + + import csv + from django.http import HttpResponse + + + def some_view(request): + # Create the HttpResponse object with the appropriate CSV header. + response = HttpResponse( + content_type="text/csv", + headers={"Content-Disposition": 'attachment; filename="somefilename.csv"'}, + ) + + writer = csv.writer(response) + writer.writerow(["First row", "Foo", "Bar", "Baz"]) + writer.writerow(["Second row", "A", "B", "C", '"Testing"', "Here's a quote"]) + + return response + +The code and comments should be self-explanatory, but a few things deserve a +mention: + +* The response gets a special MIME type, :mimetype:`text/csv`. This tells + browsers that the document is a CSV file, rather than an HTML file. If + you leave this off, browsers will probably interpret the output as HTML, + which will result in ugly, scary gobbledygook in the browser window. + +* The response gets an additional ``Content-Disposition`` header, which + contains the name of the CSV file. This filename is arbitrary; call it + whatever you want. It'll be used by browsers in the "Save as..." dialog, etc. + +* You can hook into the CSV-generation API by passing ``response`` as the first + argument to ``csv.writer``. The ``csv.writer`` function expects a file-like + object, and :class:`~django.http.HttpResponse` objects fit the bill. + +* For each row in your CSV file, call ``writer.writerow``, passing it an + :term:`iterable`. + +* The CSV module takes care of quoting for you, so you don't have to worry + about escaping strings with quotes or commas in them. Pass ``writerow()`` + your raw strings, and it'll do the right thing. + +.. _streaming-csv-files: + +Streaming large CSV files +------------------------- + +When dealing with views that generate very large responses, you might want to +consider using Django's :class:`~django.http.StreamingHttpResponse` instead. +For example, by streaming a file that takes a long time to generate you can +avoid a load balancer dropping a connection that might have otherwise timed out +while the server was generating the response. + +In this example, we make full use of Python generators to efficiently handle +the assembly and transmission of a large CSV file:: + + import csv + + from django.http import StreamingHttpResponse + + + class Echo: + """An object that implements just the write method of the file-like + interface. + """ + + def write(self, value): + """Write the value by returning it, instead of storing in a buffer.""" + return value + + + def some_streaming_csv_view(request): + """A view that streams a large CSV file.""" + # Generate a sequence of rows. The range is based on the maximum number of + # rows that can be handled by a single sheet in most spreadsheet + # applications. + rows = (["Row {}".format(idx), str(idx)] for idx in range(65536)) + pseudo_buffer = Echo() + writer = csv.writer(pseudo_buffer) + return StreamingHttpResponse( + (writer.writerow(row) for row in rows), + content_type="text/csv", + headers={"Content-Disposition": 'attachment; filename="somefilename.csv"'}, + ) + +Using the template system +========================= + +Alternatively, you can use the :doc:`Django template system ` +to generate CSV. This is lower-level than using the convenient Python :mod:`csv` +module, but the solution is presented here for completeness. + +The idea here is to pass a list of items to your template, and have the +template output the commas in a :ttag:`for` loop. + +Here's an example, which generates the same CSV file as above:: + + from django.http import HttpResponse + from django.template import loader + + + def some_view(request): + # Create the HttpResponse object with the appropriate CSV header. + response = HttpResponse( + content_type="text/csv", + headers={"Content-Disposition": 'attachment; filename="somefilename.csv"'}, + ) + + # The data is hard-coded here, but you could load it from a database or + # some other source. + csv_data = ( + ("First row", "Foo", "Bar", "Baz"), + ("Second row", "A", "B", "C", '"Testing"', "Here's a quote"), + ) + + t = loader.get_template("my_template_name.txt") + c = {"data": csv_data} + response.write(t.render(c)) + return response + +The only difference between this example and the previous example is that this +one uses template loading instead of the CSV module. The rest of the code -- +such as the ``content_type='text/csv'`` -- is the same. + +Then, create the template ``my_template_name.txt``, with this template code: + +.. code-block:: html+django + + {% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes }}" + {% endfor %} + +This short template iterates over the given data and displays a line of CSV for +each row. It uses the :tfilter:`addslashes` template filter to ensure there +aren't any problems with quotes. + +Other text-based formats +======================== + +Notice that there isn't very much specific to CSV here -- just the specific +output format. You can use either of these techniques to output any text-based +format you can dream of. You can also use a similar technique to generate +arbitrary binary data; see :doc:`/howto/outputting-pdf` for an example. diff --git a/testbed/django__django/docs/howto/outputting-pdf.txt b/testbed/django__django/docs/howto/outputting-pdf.txt new file mode 100644 index 0000000000000000000000000000000000000000..bcdfa6acc49ce1eec0275f0a936b7032723bd619 --- /dev/null +++ b/testbed/django__django/docs/howto/outputting-pdf.txt @@ -0,0 +1,122 @@ +======================= +How to create PDF files +======================= + +This document explains how to output PDF files dynamically using Django views. +This is made possible by the excellent, open-source ReportLab_ Python PDF +library. + +The advantage of generating PDF files dynamically is that you can create +customized PDFs for different purposes -- say, for different users or different +pieces of content. + +For example, Django was used at kusports.com_ to generate customized, +printer-friendly NCAA tournament brackets, as PDF files, for people +participating in a March Madness contest. + +.. _ReportLab: https://docs.reportlab.com/ +.. _kusports.com: http://www2.kusports.com/ + +Install ReportLab +================= + +The ReportLab library is :pypi:`available on PyPI `. A `user guide`_ +(not coincidentally, a PDF file) is also available for download. +You can install ReportLab with ``pip``: + +.. console:: + + $ python -m pip install reportlab + +Test your installation by importing it in the Python interactive interpreter: + +.. code-block:: pycon + + >>> import reportlab + +If that command doesn't raise any errors, the installation worked. + +.. _user guide: https://www.reportlab.com/docs/reportlab-userguide.pdf + +Write your view +=============== + +The key to generating PDFs dynamically with Django is that the ReportLab API +acts on file-like objects, and Django's :class:`~django.http.FileResponse` +objects accept file-like objects. + +Here's a "Hello World" example:: + + import io + from django.http import FileResponse + from reportlab.pdfgen import canvas + + + def some_view(request): + # Create a file-like buffer to receive PDF data. + buffer = io.BytesIO() + + # Create the PDF object, using the buffer as its "file." + p = canvas.Canvas(buffer) + + # Draw things on the PDF. Here's where the PDF generation happens. + # See the ReportLab documentation for the full list of functionality. + p.drawString(100, 100, "Hello world.") + + # Close the PDF object cleanly, and we're done. + p.showPage() + p.save() + + # FileResponse sets the Content-Disposition header so that browsers + # present the option to save the file. + buffer.seek(0) + return FileResponse(buffer, as_attachment=True, filename="hello.pdf") + +The code and comments should be self-explanatory, but a few things deserve a +mention: + +* The response will automatically set the MIME type :mimetype:`application/pdf` + based on the filename extension. This tells browsers that the document is a + PDF file, rather than an HTML file or a generic + :mimetype:`application/octet-stream` binary content. + +* When ``as_attachment=True`` is passed to ``FileResponse``, it sets the + appropriate ``Content-Disposition`` header and that tells web browsers to + pop-up a dialog box prompting/confirming how to handle the document even if a + default is set on the machine. If the ``as_attachment`` parameter is omitted, + browsers will handle the PDF using whatever program/plugin they've been + configured to use for PDFs. + +* You can provide an arbitrary ``filename`` parameter. It'll be used by browsers + in the "Save as..." dialog. + +* You can hook into the ReportLab API: The same buffer passed as the first + argument to ``canvas.Canvas`` can be fed to the + :class:`~django.http.FileResponse` class. + +* Note that all subsequent PDF-generation methods are called on the PDF + object (in this case, ``p``) -- not on ``buffer``. + +* Finally, it's important to call ``showPage()`` and ``save()`` on the PDF + file. + +.. note:: + + ReportLab is not thread-safe. Some of our users have reported odd issues + with building PDF-generating Django views that are accessed by many people + at the same time. + +Other formats +============= + +Notice that there isn't a lot in these examples that's PDF-specific -- just the +bits using ``reportlab``. You can use a similar technique to generate any +arbitrary format that you can find a Python library for. Also see +:doc:`/howto/outputting-csv` for another example and some techniques you can use +when generated text-based formats. + +.. seealso:: + + Django Packages provides a `comparison of packages + `_ that help generate PDF files + from Django. diff --git a/testbed/django__django/docs/howto/overriding-templates.txt b/testbed/django__django/docs/howto/overriding-templates.txt new file mode 100644 index 0000000000000000000000000000000000000000..f636948a201d05131f95fad187c5801056f6af68 --- /dev/null +++ b/testbed/django__django/docs/howto/overriding-templates.txt @@ -0,0 +1,139 @@ +========================= +How to override templates +========================= + +In your project, you might want to override a template in another Django +application, whether it be a third-party application or a contrib application +such as ``django.contrib.admin``. You can either put template overrides in your +project's templates directory or in an application's templates directory. + +If you have app and project templates directories that both contain overrides, +the default Django template loader will try to load the template from the +project-level directory first. In other words, :setting:`DIRS ` +is searched before :setting:`APP_DIRS `. + +.. seealso:: + + Read :ref:`overriding-built-in-widget-templates` if you're looking to + do that. + +Overriding from the project's templates directory +================================================= + +First, we'll explore overriding templates by creating replacement templates in +your project's templates directory. + +Let's say you're trying to override the templates for a third-party application +called ``blog``, which provides the templates ``blog/post.html`` and +``blog/list.html``. The relevant settings for your project would look like:: + + from pathlib import Path + + BASE_DIR = Path(__file__).resolve().parent.parent + + INSTALLED_APPS = [ + ..., + "blog", + ..., + ] + + TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [BASE_DIR / "templates"], + "APP_DIRS": True, + # ... + }, + ] + +The :setting:`TEMPLATES` setting and ``BASE_DIR`` will already exist if you +created your project using the default project template. The setting that needs +to be modified is :setting:`DIRS`. + +These settings assume you have a ``templates`` directory in the root of your +project. To override the templates for the ``blog`` app, create a folder +in the ``templates`` directory, and add the template files to that folder: + +.. code-block:: none + + templates/ + blog/ + list.html + post.html + +The template loader first looks for templates in the ``DIRS`` directory. When +the views in the ``blog`` app ask for the ``blog/post.html`` and +``blog/list.html`` templates, the loader will return the files you just created. + +Overriding from an app's template directory +=========================================== + +Since you're overriding templates located outside of one of your project's +apps, it's more common to use the first method and put template overrides in a +project's templates folder. If you prefer, however, it's also possible to put +the overrides in an app's template directory. + +First, make sure your template settings are checking inside app directories:: + + TEMPLATES = [ + { + # ... + "APP_DIRS": True, + # ... + }, + ] + +If you want to put the template overrides in an app called ``myapp`` and the +templates to override are named ``blog/list.html`` and ``blog/post.html``, +then your directory structure will look like: + +.. code-block:: none + + myapp/ + templates/ + blog/ + list.html + post.html + +With :setting:`APP_DIRS` set to ``True``, the template +loader will look in the app's templates directory and find the templates. + +.. _extending_an_overridden_template: + +Extending an overridden template +================================ + +With your template loaders configured, you can extend a template using the +:ttag:`{% extends %}` template tag whilst at the same time overriding +it. This can allow you to make small customizations without needing to +reimplement the entire template. + +For example, you can use this technique to add a custom logo to the +``admin/base_site.html`` template: + + .. code-block:: html+django + :caption: ``templates/admin/base_site.html`` + + {% extends "admin/base_site.html" %} + + {% block branding %} + logo + {{ block.super }} + {% endblock %} + +Key points to note: + +* The example creates a file at ``templates/admin/base_site.html`` that uses + the configured project-level ``templates`` directory to override + ``admin/base_site.html``. +* The new template extends ``admin/base_site.html``, which is the same template + as is being overridden. +* The template replaces just the ``branding`` block, adding a custom logo, and + using ``block.super`` to retain the prior content. +* The rest of the template is inherited unchanged from + ``admin/base_site.html``. + +This technique works because the template loader does not consider the already +loaded override template (at ``templates/admin/base_site.html``) when +resolving the ``extends`` tag. Combined with ``block.super`` it is a powerful +technique to make small customizations. diff --git a/testbed/django__django/docs/howto/static-files/deployment.txt b/testbed/django__django/docs/howto/static-files/deployment.txt new file mode 100644 index 0000000000000000000000000000000000000000..67ecf59a71a871e10efe5e2c146f026d98517552 --- /dev/null +++ b/testbed/django__django/docs/howto/static-files/deployment.txt @@ -0,0 +1,118 @@ +========================== +How to deploy static files +========================== + +.. seealso:: + + For an introduction to the use of :mod:`django.contrib.staticfiles`, see + :doc:`/howto/static-files/index`. + +.. _staticfiles-production: + +Serving static files in production +================================== + +The basic outline of putting static files into production consists of two +steps: run the :djadmin:`collectstatic` command when static files change, then +arrange for the collected static files directory (:setting:`STATIC_ROOT`) to be +moved to the static file server and served. Depending the ``staticfiles`` +:setting:`STORAGES` alias, files may need to be moved to a new location +manually or the :func:`post_process +` method of +the ``Storage`` class might take care of that. + +As with all deployment tasks, the devil's in the details. Every production +setup will be a bit different, so you'll need to adapt the basic outline to fit +your needs. Below are a few common patterns that might help. + +Serving the site and your static files from the same server +----------------------------------------------------------- + +If you want to serve your static files from the same server that's already +serving your site, the process may look something like: + +* Push your code up to the deployment server. +* On the server, run :djadmin:`collectstatic` to copy all the static files + into :setting:`STATIC_ROOT`. +* Configure your web server to serve the files in :setting:`STATIC_ROOT` + under the URL :setting:`STATIC_URL`. For example, here's + :ref:`how to do this with Apache and mod_wsgi `. + +You'll probably want to automate this process, especially if you've got +multiple web servers. + +Serving static files from a dedicated server +-------------------------------------------- + +Most larger Django sites use a separate web server -- i.e., one that's not also +running Django -- for serving static files. This server often runs a different +type of web server -- faster but less full-featured. Some common choices are: + +* Nginx_ +* A stripped-down version of Apache_ + +.. _Nginx: https://nginx.org/en/ +.. _Apache: https://httpd.apache.org/ + +Configuring these servers is out of scope of this document; check each +server's respective documentation for instructions. + +Since your static file server won't be running Django, you'll need to modify +the deployment strategy to look something like: + +* When your static files change, run :djadmin:`collectstatic` locally. + +* Push your local :setting:`STATIC_ROOT` up to the static file server into the + directory that's being served. `rsync `_ is a + common choice for this step since it only needs to transfer the bits of + static files that have changed. + +.. _staticfiles-from-cdn: + +Serving static files from a cloud service or CDN +------------------------------------------------ + +Another common tactic is to serve static files from a cloud storage provider +like Amazon's S3 and/or a CDN (content delivery network). This lets you +ignore the problems of serving static files and can often make for +faster-loading web pages (especially when using a CDN). + +When using these services, the basic workflow would look a bit like the above, +except that instead of using ``rsync`` to transfer your static files to the +server you'd need to transfer the static files to the storage provider or CDN. + +There's any number of ways you might do this, but if the provider has an API, +you can use a :doc:`custom file storage backend ` +to integrate the CDN with your Django project. If you've written or are using a +3rd party custom storage backend, you can tell :djadmin:`collectstatic` to use +it by setting ``staticfiles`` in :setting:`STORAGES`. + +For example, if you've written an S3 storage backend in +``myproject.storage.S3Storage`` you could use it with:: + + STORAGES = { + # ... + "staticfiles": {"BACKEND": "myproject.storage.S3Storage"} + } + +Once that's done, all you have to do is run :djadmin:`collectstatic` and your +static files would be pushed through your storage package up to S3. If you +later needed to switch to a different storage provider, you may only have to +change ``staticfiles`` in the :setting:`STORAGES` setting. + +For details on how you'd write one of these backends, see +:doc:`/howto/custom-file-storage`. There are 3rd party apps available that +provide storage backends for many common file storage APIs. A good starting +point is the `overview at djangopackages.org +`_. + +.. versionchanged:: 4.2 + + The :setting:`STORAGES` setting was added. + +Learn more +========== + +For complete details on all the settings, commands, template tags, and other +pieces included in :mod:`django.contrib.staticfiles`, see :doc:`the +staticfiles reference `. diff --git a/testbed/django__django/docs/howto/static-files/index.txt b/testbed/django__django/docs/howto/static-files/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..b4cfd03df7f95b1d1667e1cb8c897adcc7dbe044 --- /dev/null +++ b/testbed/django__django/docs/howto/static-files/index.txt @@ -0,0 +1,194 @@ +========================================================= +How to manage static files (e.g. images, JavaScript, CSS) +========================================================= + +Websites generally need to serve additional files such as images, JavaScript, +or CSS. In Django, we refer to these files as "static files". Django provides +:mod:`django.contrib.staticfiles` to help you manage them. + +This page describes how you can serve these static files. + +Configuring static files +======================== + +#. Make sure that ``django.contrib.staticfiles`` is included in your + :setting:`INSTALLED_APPS`. + +#. In your settings file, define :setting:`STATIC_URL`, for example:: + + STATIC_URL = "static/" + +#. In your templates, use the :ttag:`static` template tag to build the URL for + the given relative path using the configured ``staticfiles`` + :setting:`STORAGES` alias. + + .. _staticfiles-in-templates: + + .. code-block:: html+django + + {% load static %} + My image + +#. Store your static files in a folder called ``static`` in your app. For + example ``my_app/static/my_app/example.jpg``. + +.. admonition:: Serving the files + + In addition to these configuration steps, you'll also need to actually + serve the static files. + + During development, if you use :mod:`django.contrib.staticfiles`, this will + be done automatically by :djadmin:`runserver` when :setting:`DEBUG` is set + to ``True`` (see :func:`django.contrib.staticfiles.views.serve`). + + This method is **grossly inefficient** and probably **insecure**, + so it is **unsuitable for production**. + + See :doc:`/howto/static-files/deployment` for proper strategies to serve + static files in production environments. + +Your project will probably also have static assets that aren't tied to a +particular app. In addition to using a ``static/`` directory inside your apps, +you can define a list of directories (:setting:`STATICFILES_DIRS`) in your +settings file where Django will also look for static files. For example:: + + STATICFILES_DIRS = [ + BASE_DIR / "static", + "/var/www/static/", + ] + +See the documentation for the :setting:`STATICFILES_FINDERS` setting for +details on how ``staticfiles`` finds your files. + +.. admonition:: Static file namespacing + + Now we *might* be able to get away with putting our static files directly + in ``my_app/static/`` (rather than creating another ``my_app`` + subdirectory), but it would actually be a bad idea. Django will use the + first static file it finds whose name matches, and if you had a static file + with the same name in a *different* application, Django would be unable to + distinguish between them. We need to be able to point Django at the right + one, and the best way to ensure this is by *namespacing* them. That is, + by putting those static files inside *another* directory named for the + application itself. + + You can namespace static assets in :setting:`STATICFILES_DIRS` by + specifying :ref:`prefixes `. + +.. _serving-static-files-in-development: + +Serving static files during development +======================================= + +If you use :mod:`django.contrib.staticfiles` as explained above, +:djadmin:`runserver` will do this automatically when :setting:`DEBUG` is set +to ``True``. If you don't have ``django.contrib.staticfiles`` in +:setting:`INSTALLED_APPS`, you can still manually serve static files using the +:func:`django.views.static.serve` view. + +This is not suitable for production use! For some common deployment +strategies, see :doc:`/howto/static-files/deployment`. + +For example, if your :setting:`STATIC_URL` is defined as ``static/``, you can +do this by adding the following snippet to your ``urls.py``:: + + from django.conf import settings + from django.conf.urls.static import static + + urlpatterns = [ + # ... the rest of your URLconf goes here ... + ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + +.. note:: + + This helper function works only in debug mode and only if + the given prefix is local (e.g. ``static/``) and not a URL (e.g. + ``http://static.example.com/``). + + Also this helper function only serves the actual :setting:`STATIC_ROOT` + folder; it doesn't perform static files discovery like + :mod:`django.contrib.staticfiles`. + + Finally, static files are served via a wrapper at the WSGI application + layer. As a consequence, static files requests do not pass through the + normal :doc:`middleware chain `. + +.. _serving-uploaded-files-in-development: + +Serving files uploaded by a user during development +=================================================== + +During development, you can serve user-uploaded media files from +:setting:`MEDIA_ROOT` using the :func:`django.views.static.serve` view. + +This is not suitable for production use! For some common deployment +strategies, see :doc:`/howto/static-files/deployment`. + +For example, if your :setting:`MEDIA_URL` is defined as ``media/``, you can do +this by adding the following snippet to your :setting:`ROOT_URLCONF`:: + + from django.conf import settings + from django.conf.urls.static import static + + urlpatterns = [ + # ... the rest of your URLconf goes here ... + ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +.. note:: + + This helper function works only in debug mode and only if + the given prefix is local (e.g. ``media/``) and not a URL (e.g. + ``http://media.example.com/``). + +.. _staticfiles-testing-support: + +Testing +======= + +When running tests that use actual HTTP requests instead of the built-in +testing client (i.e. when using the built-in :class:`LiveServerTestCase +`) the static assets need to be served along +the rest of the content so the test environment reproduces the real one as +faithfully as possible, but ``LiveServerTestCase`` has only very basic static +file-serving functionality: It doesn't know about the finders feature of the +``staticfiles`` application and assumes the static content has already been +collected under :setting:`STATIC_ROOT`. + +Because of this, ``staticfiles`` ships its own +:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a subclass +of the built-in one that has the ability to transparently serve all the assets +during execution of these tests in a way very similar to what we get at +development time with ``DEBUG = True``, i.e. without having to collect them +using :djadmin:`collectstatic` first. + +Deployment +========== + +:mod:`django.contrib.staticfiles` provides a convenience management command +for gathering static files in a single directory so you can serve them easily. + +#. Set the :setting:`STATIC_ROOT` setting to the directory from which you'd + like to serve these files, for example:: + + STATIC_ROOT = "/var/www/example.com/static/" + +#. Run the :djadmin:`collectstatic` management command: + + .. code-block:: shell + + $ python manage.py collectstatic + + This will copy all files from your static folders into the + :setting:`STATIC_ROOT` directory. + +#. Use a web server of your choice to serve the + files. :doc:`/howto/static-files/deployment` covers some common deployment + strategies for static files. + +Learn more +========== + +This document has covered the basics and some common usage patterns. For +complete details on all the settings, commands, template tags, and other pieces +included in :mod:`django.contrib.staticfiles`, see :doc:`the staticfiles +reference `. diff --git a/testbed/django__django/docs/howto/upgrade-version.txt b/testbed/django__django/docs/howto/upgrade-version.txt new file mode 100644 index 0000000000000000000000000000000000000000..02e0cbf9a0b433dd4a8180f86d098f67716f181d --- /dev/null +++ b/testbed/django__django/docs/howto/upgrade-version.txt @@ -0,0 +1,132 @@ +======================================== +How to upgrade Django to a newer version +======================================== + +While it can be a complex process at times, upgrading to the latest Django +version has several benefits: + +* New features and improvements are added. +* Bugs are fixed. +* Older version of Django will eventually no longer receive security updates. + (see :ref:`supported-versions-policy`). +* Upgrading as each new Django release is available makes future upgrades less + painful by keeping your code base up to date. + +Here are some things to consider to help make your upgrade process as smooth as +possible. + +Required Reading +================ + +If it's your first time doing an upgrade, it is useful to read the :doc:`guide +on the different release processes `. + +Afterward, you should familiarize yourself with the changes that were made in +the new Django version(s): + +* Read the :doc:`release notes ` for each 'final' release from + the one after your current Django version, up to and including the version to + which you plan to upgrade. +* Look at the :doc:`deprecation timeline` for the + relevant versions. + +Pay particular attention to backwards incompatible changes to get a clear idea +of what will be needed for a successful upgrade. + +If you're upgrading through more than one feature version (e.g. 2.0 to 2.2), +it's usually easier to upgrade through each feature release incrementally +(2.0 to 2.1 to 2.2) rather than to make all the changes for each feature +release at once. For each feature release, use the latest patch release (e.g. +for 2.1, use 2.1.15). + +The same incremental upgrade approach is recommended when upgrading from one +LTS to the next. + +Dependencies +============ + +In most cases it will be necessary to upgrade to the latest version of your +Django-related dependencies as well. If the Django version was recently +released or if some of your dependencies are not well-maintained, some of your +dependencies may not yet support the new Django version. In these cases you may +have to wait until new versions of your dependencies are released. + +Resolving deprecation warnings +============================== + +Before upgrading, it's a good idea to resolve any deprecation warnings raised +by your project while using your current version of Django. Fixing these +warnings before upgrading ensures that you're informed about areas of the code +that need altering. + +In Python, deprecation warnings are silenced by default. You must turn them on +using the ``-Wa`` Python command line option or the :envvar:`PYTHONWARNINGS` +environment variable. For example, to show warnings while running tests: + +.. console:: + + $ python -Wa manage.py test + +If you're not using the Django test runner, you may need to also ensure that +any console output is not captured which would hide deprecation warnings. For +example, if you use `pytest `__: + +.. code-block:: console + + $ PYTHONWARNINGS=always pytest tests --capture=no + +Resolve any deprecation warnings with your current version of Django before +continuing the upgrade process. + +Third party applications might use deprecated APIs in order to support multiple +versions of Django, so deprecation warnings in packages you've installed don't +necessarily indicate a problem. If a package doesn't support the latest version +of Django, consider raising an issue or sending a pull request for it. + +Installation +============ + +Once you're ready, it is time to :doc:`install the new Django version +`. If you are using a :mod:`virtual environment ` and it +is a major upgrade, you might want to set up a new environment with all the +dependencies first. + +If you installed Django with pip_, you can use the ``--upgrade`` or ``-U`` flag: + +.. console:: + + $ python -m pip install -U Django + +.. _pip: https://pip.pypa.io/ + +Testing +======= + +When the new environment is set up, :doc:`run the full test suite +` for your application. Again, it's useful to turn +on deprecation warnings on so they're shown in the test output (you can also +use the flag if you test your app manually using ``manage.py runserver``): + +.. console:: + + $ python -Wa manage.py test + +After you have run the tests, fix any failures. While you have the release +notes fresh in your mind, it may also be a good time to take advantage of new +features in Django by refactoring your code to eliminate any deprecation +warnings. + +Deployment +========== + +When you are sufficiently confident your app works with the new version of +Django, you're ready to go ahead and :doc:`deploy ` +your upgraded Django project. + +If you are using caching provided by Django, you should consider clearing your +cache after upgrading. Otherwise you may run into problems, for example, if you +are caching pickled objects as these objects are not guaranteed to be +pickle-compatible across Django versions. A past instance of incompatibility +was caching pickled :class:`~django.http.HttpResponse` objects, either +directly or indirectly via the :func:`~django.views.decorators.cache.cache_page` +decorator. diff --git a/testbed/django__django/docs/howto/windows.txt b/testbed/django__django/docs/howto/windows.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbac82f967bf54d05b5376574758d91e608058f5 --- /dev/null +++ b/testbed/django__django/docs/howto/windows.txt @@ -0,0 +1,139 @@ +================================ +How to install Django on Windows +================================ + +This document will guide you through installing Python 3.11 and Django on +Windows. It also provides instructions for setting up a virtual environment, +which makes it easier to work on Python projects. This is meant as a beginner's +guide for users working on Django projects and does not reflect how Django +should be installed when developing patches for Django itself. + +The steps in this guide have been tested with Windows 10. In other +versions, the steps would be similar. You will need to be familiar with using +the Windows command prompt. + +.. _install_python_windows: + +Install Python +============== + +Django is a Python web framework, thus requiring Python to be installed on your +machine. At the time of writing, Python 3.11 is the latest version. + +To install Python on your machine go to https://www.python.org/downloads/. The +website should offer you a download button for the latest Python version. +Download the executable installer and run it. Check the boxes next to "Install +launcher for all users (recommended)" then click "Install Now". + +After installation, open the command prompt and check that the Python version +matches the version you installed by executing: + +.. code-block:: doscon + + ...\> py --version + +.. seealso:: + + For more details, see :doc:`python:using/windows` documentation. + +About ``pip`` +============= + +:pypi:`pip` is a package manager for Python and is included by default with the +Python installer. It helps to install and uninstall Python packages +(such as Django!). For the rest of the installation, we'll use ``pip`` to +install Python packages from the command line. + +.. _virtualenvironment: + +Setting up a virtual environment +================================ + +It is best practice to provide a dedicated environment for each Django project +you create. There are many options to manage environments and packages within +the Python ecosystem, some of which are recommended in the `Python +documentation `_. +Python itself comes with :doc:`venv ` for managing +environments which we will use for this guide. + +To create a virtual environment for your project, open a new command prompt, +navigate to the folder where you want to create your project and then enter the +following: + +.. code-block:: doscon + + ...\> py -m venv project-name + +This will create a folder called 'project-name' if it does not already exist +and set up the virtual environment. To activate the environment, run: + +.. code-block:: doscon + + ...\> project-name\Scripts\activate.bat + +The virtual environment will be activated and you'll see "(project-name)" next +to the command prompt to designate that. Each time you start a new command +prompt, you'll need to activate the environment again. + +Install Django +============== + +Django can be installed easily using ``pip`` within your virtual environment. + +In the command prompt, ensure your virtual environment is active, and execute +the following command: + +.. code-block:: doscon + + ...\> py -m pip install Django + +This will download and install the latest Django release. + +After the installation has completed, you can verify your Django installation +by executing ``django-admin --version`` in the command prompt. + +See :ref:`database-installation` for information on database installation +with Django. + +Colored terminal output +======================= + +A quality-of-life feature adds colored (rather than monochrome) output to the +terminal. In modern terminals this should work for both CMD and PowerShell. If +for some reason this needs to be disabled, set the environmental variable +:envvar:`DJANGO_COLORS` to ``nocolor``. + +On older Windows versions, or legacy terminals, :pypi:`colorama` must be +installed to enable syntax coloring: + +.. code-block:: doscon + + ...\> py -m pip install colorama + +See :ref:`syntax-coloring` for more information on color settings. + +Common pitfalls +=============== + +* If ``django-admin`` only displays the help text no matter what arguments + it is given, there is probably a problem with the file association in + Windows. Check if there is more than one environment variable set for + running Python scripts in ``PATH``. This usually occurs when there is more + than one Python version installed. + +* If you are connecting to the internet behind a proxy, there might be problems + in running the command ``py -m pip install Django``. Set the environment + variables for proxy configuration in the command prompt as follows: + + .. code-block:: doscon + + ...\> set http_proxy=http://username:password@proxyserver:proxyport + ...\> set https_proxy=https://username:password@proxyserver:proxyport + +* In general, Django assumes that ``UTF-8`` encoding is used for I/O. This may + cause problems if your system is set to use a different encoding. Recent + versions of Python allow setting the :envvar:`PYTHONUTF8` environment + variable in order to force a ``UTF-8`` encoding. Windows 10 also provides a + system-wide setting by checking ``Use Unicode UTF-8 for worldwide language + support`` in :menuselection:`Language --> Administrative Language Settings + --> Change system locale` in system settings. diff --git a/testbed/django__django/docs/howto/writing-migrations.txt b/testbed/django__django/docs/howto/writing-migrations.txt new file mode 100644 index 0000000000000000000000000000000000000000..2c52eccbad8b9c1fba993faa61d4394bad3f0095 --- /dev/null +++ b/testbed/django__django/docs/howto/writing-migrations.txt @@ -0,0 +1,420 @@ +================================= +How to create database migrations +================================= + +This document explains how to structure and write database migrations for +different scenarios you might encounter. For introductory material on +migrations, see :doc:`the topic guide `. + +.. _data-migrations-and-multiple-databases: + +Data migrations and multiple databases +====================================== + +When using multiple databases, you may need to figure out whether or not to +run a migration against a particular database. For example, you may want to +**only** run a migration on a particular database. + +In order to do that you can check the database connection's alias inside a +``RunPython`` operation by looking at the ``schema_editor.connection.alias`` +attribute:: + + from django.db import migrations + + + def forwards(apps, schema_editor): + if schema_editor.connection.alias != "default": + return + # Your migration code goes here + + + class Migration(migrations.Migration): + dependencies = [ + # Dependencies to other migrations + ] + + operations = [ + migrations.RunPython(forwards), + ] + +You can also provide hints that will be passed to the :meth:`allow_migrate()` +method of database routers as ``**hints``: + +.. code-block:: python + :caption: ``myapp/dbrouters.py`` + + class MyRouter: + def allow_migrate(self, db, app_label, model_name=None, **hints): + if "target_db" in hints: + return db == hints["target_db"] + return True + +Then, to leverage this in your migrations, do the following:: + + from django.db import migrations + + + def forwards(apps, schema_editor): + # Your migration code goes here + ... + + + class Migration(migrations.Migration): + dependencies = [ + # Dependencies to other migrations + ] + + operations = [ + migrations.RunPython(forwards, hints={"target_db": "default"}), + ] + +If your ``RunPython`` or ``RunSQL`` operation only affects one model, it's good +practice to pass ``model_name`` as a hint to make it as transparent as possible +to the router. This is especially important for reusable and third-party apps. + +Migrations that add unique fields +================================= + +Applying a "plain" migration that adds a unique non-nullable field to a table +with existing rows will raise an error because the value used to populate +existing rows is generated only once, thus breaking the unique constraint. + +Therefore, the following steps should be taken. In this example, we'll add a +non-nullable :class:`~django.db.models.UUIDField` with a default value. Modify +the respective field according to your needs. + +* Add the field on your model with ``default=uuid.uuid4`` and ``unique=True`` + arguments (choose an appropriate default for the type of the field you're + adding). + +* Run the :djadmin:`makemigrations` command. This should generate a migration + with an ``AddField`` operation. + +* Generate two empty migration files for the same app by running + ``makemigrations myapp --empty`` twice. We've renamed the migration files to + give them meaningful names in the examples below. + +* Copy the ``AddField`` operation from the auto-generated migration (the first + of the three new files) to the last migration, change ``AddField`` to + ``AlterField``, and add imports of ``uuid`` and ``models``. For example: + + .. code-block:: python + :caption: ``0006_remove_uuid_null.py`` + + # Generated by Django A.B on YYYY-MM-DD HH:MM + from django.db import migrations, models + import uuid + + + class Migration(migrations.Migration): + dependencies = [ + ("myapp", "0005_populate_uuid_values"), + ] + + operations = [ + migrations.AlterField( + model_name="mymodel", + name="uuid", + field=models.UUIDField(default=uuid.uuid4, unique=True), + ), + ] + +* Edit the first migration file. The generated migration class should look + similar to this: + + .. code-block:: python + :caption: ``0004_add_uuid_field.py`` + + class Migration(migrations.Migration): + dependencies = [ + ("myapp", "0003_auto_20150129_1705"), + ] + + operations = [ + migrations.AddField( + model_name="mymodel", + name="uuid", + field=models.UUIDField(default=uuid.uuid4, unique=True), + ), + ] + + Change ``unique=True`` to ``null=True`` -- this will create the intermediary + null field and defer creating the unique constraint until we've populated + unique values on all the rows. + +* In the first empty migration file, add a + :class:`~django.db.migrations.operations.RunPython` or + :class:`~django.db.migrations.operations.RunSQL` operation to generate a + unique value (UUID in the example) for each existing row. Also add an import + of ``uuid``. For example: + + .. code-block:: python + :caption: ``0005_populate_uuid_values.py`` + + # Generated by Django A.B on YYYY-MM-DD HH:MM + from django.db import migrations + import uuid + + + def gen_uuid(apps, schema_editor): + MyModel = apps.get_model("myapp", "MyModel") + for row in MyModel.objects.all(): + row.uuid = uuid.uuid4() + row.save(update_fields=["uuid"]) + + + class Migration(migrations.Migration): + dependencies = [ + ("myapp", "0004_add_uuid_field"), + ] + + operations = [ + # omit reverse_code=... if you don't want the migration to be reversible. + migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop), + ] + +* Now you can apply the migrations as usual with the :djadmin:`migrate` command. + + Note there is a race condition if you allow objects to be created while this + migration is running. Objects created after the ``AddField`` and before + ``RunPython`` will have their original ``uuid``’s overwritten. + +.. _non-atomic-migrations: + +Non-atomic migrations +~~~~~~~~~~~~~~~~~~~~~ + +On databases that support DDL transactions (SQLite and PostgreSQL), migrations +will run inside a transaction by default. For use cases such as performing data +migrations on large tables, you may want to prevent a migration from running in +a transaction by setting the ``atomic`` attribute to ``False``:: + + from django.db import migrations + + + class Migration(migrations.Migration): + atomic = False + +Within such a migration, all operations are run without a transaction. It's +possible to execute parts of the migration inside a transaction using +:func:`~django.db.transaction.atomic()` or by passing ``atomic=True`` to +``RunPython``. + +Here's an example of a non-atomic data migration that updates a large table in +smaller batches:: + + import uuid + + from django.db import migrations, transaction + + + def gen_uuid(apps, schema_editor): + MyModel = apps.get_model("myapp", "MyModel") + while MyModel.objects.filter(uuid__isnull=True).exists(): + with transaction.atomic(): + for row in MyModel.objects.filter(uuid__isnull=True)[:1000]: + row.uuid = uuid.uuid4() + row.save() + + + class Migration(migrations.Migration): + atomic = False + + operations = [ + migrations.RunPython(gen_uuid), + ] + +The ``atomic`` attribute doesn't have an effect on databases that don't support +DDL transactions (e.g. MySQL, Oracle). (MySQL's `atomic DDL statement support +`_ refers to individual +statements rather than multiple statements wrapped in a transaction that can be +rolled back.) + +Controlling the order of migrations +=================================== + +Django determines the order in which migrations should be applied not by the +filename of each migration, but by building a graph using two properties on the +``Migration`` class: ``dependencies`` and ``run_before``. + +If you've used the :djadmin:`makemigrations` command you've probably +already seen ``dependencies`` in action because auto-created +migrations have this defined as part of their creation process. + +The ``dependencies`` property is declared like this:: + + from django.db import migrations + + + class Migration(migrations.Migration): + dependencies = [ + ("myapp", "0123_the_previous_migration"), + ] + +Usually this will be enough, but from time to time you may need to +ensure that your migration runs *before* other migrations. This is +useful, for example, to make third-party apps' migrations run *after* +your :setting:`AUTH_USER_MODEL` replacement. + +To achieve this, place all migrations that should depend on yours in +the ``run_before`` attribute on your ``Migration`` class:: + + class Migration(migrations.Migration): + ... + + run_before = [ + ("third_party_app", "0001_do_awesome"), + ] + +Prefer using ``dependencies`` over ``run_before`` when possible. You should +only use ``run_before`` if it is undesirable or impractical to specify +``dependencies`` in the migration which you want to run after the one you are +writing. + +Migrating data between third-party apps +======================================= + +You can use a data migration to move data from one third-party application to +another. + +If you plan to remove the old app later, you'll need to set the ``dependencies`` +property based on whether or not the old app is installed. Otherwise, you'll +have missing dependencies once you uninstall the old app. Similarly, you'll +need to catch :exc:`LookupError` in the ``apps.get_model()`` call that +retrieves models from the old app. This approach allows you to deploy your +project anywhere without first installing and then uninstalling the old app. + +Here's a sample migration: + +.. code-block:: python + :caption: ``myapp/migrations/0124_move_old_app_to_new_app.py`` + + from django.apps import apps as global_apps + from django.db import migrations + + + def forwards(apps, schema_editor): + try: + OldModel = apps.get_model("old_app", "OldModel") + except LookupError: + # The old app isn't installed. + return + + NewModel = apps.get_model("new_app", "NewModel") + NewModel.objects.bulk_create( + NewModel(new_attribute=old_object.old_attribute) + for old_object in OldModel.objects.all() + ) + + + class Migration(migrations.Migration): + operations = [ + migrations.RunPython(forwards, migrations.RunPython.noop), + ] + dependencies = [ + ("myapp", "0123_the_previous_migration"), + ("new_app", "0001_initial"), + ] + + if global_apps.is_installed("old_app"): + dependencies.append(("old_app", "0001_initial")) + +Also consider what you want to happen when the migration is unapplied. You +could either do nothing (as in the example above) or remove some or all of the +data from the new application. Adjust the second argument of the +:mod:`~django.db.migrations.operations.RunPython` operation accordingly. + +.. _changing-a-manytomanyfield-to-use-a-through-model: + +Changing a ``ManyToManyField`` to use a ``through`` model +========================================================= + +If you change a :class:`~django.db.models.ManyToManyField` to use a ``through`` +model, the default migration will delete the existing table and create a new +one, losing the existing relations. To avoid this, you can use +:class:`.SeparateDatabaseAndState` to rename the existing table to the new +table name while telling the migration autodetector that the new model has +been created. You can check the existing table name through +:djadmin:`sqlmigrate` or :djadmin:`dbshell`. You can check the new table name +with the through model's ``_meta.db_table`` property. Your new ``through`` +model should use the same names for the ``ForeignKey``\s as Django did. Also if +it needs any extra fields, they should be added in operations after +:class:`.SeparateDatabaseAndState`. + +For example, if we had a ``Book`` model with a ``ManyToManyField`` linking to +``Author``, we could add a through model ``AuthorBook`` with a new field +``is_primary``, like so:: + + from django.db import migrations, models + import django.db.models.deletion + + + class Migration(migrations.Migration): + dependencies = [ + ("core", "0001_initial"), + ] + + operations = [ + migrations.SeparateDatabaseAndState( + database_operations=[ + # Old table name from checking with sqlmigrate, new table + # name from AuthorBook._meta.db_table. + migrations.RunSQL( + sql="ALTER TABLE core_book_authors RENAME TO core_authorbook", + reverse_sql="ALTER TABLE core_authorbook RENAME TO core_book_authors", + ), + ], + state_operations=[ + migrations.CreateModel( + name="AuthorBook", + fields=[ + ( + "id", + models.AutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "author", + models.ForeignKey( + on_delete=django.db.models.deletion.DO_NOTHING, + to="core.Author", + ), + ), + ( + "book", + models.ForeignKey( + on_delete=django.db.models.deletion.DO_NOTHING, + to="core.Book", + ), + ), + ], + ), + migrations.AlterField( + model_name="book", + name="authors", + field=models.ManyToManyField( + to="core.Author", + through="core.AuthorBook", + ), + ), + ], + ), + migrations.AddField( + model_name="authorbook", + name="is_primary", + field=models.BooleanField(default=False), + ), + ] + +Changing an unmanaged model to managed +====================================== + +If you want to change an unmanaged model (:attr:`managed=False +`) to managed, you must remove +``managed=False`` and generate a migration before making other schema-related +changes to the model, since schema changes that appear in the migration that +contains the operation to change ``Meta.managed`` may not be applied. diff --git a/testbed/django__django/docs/internals/_images/triage_process.pdf b/testbed/django__django/docs/internals/_images/triage_process.pdf new file mode 100644 index 0000000000000000000000000000000000000000..558553e2dd7c539f114c9436c43c9a8d627f6db6 Binary files /dev/null and b/testbed/django__django/docs/internals/_images/triage_process.pdf differ diff --git a/testbed/django__django/docs/internals/_images/triage_process.svg b/testbed/django__django/docs/internals/_images/triage_process.svg new file mode 100644 index 0000000000000000000000000000000000000000..2b5e0d3cedd3b3fe8c2fd8435b96d652a5a0179b --- /dev/null +++ b/testbed/django__django/docs/internals/_images/triage_process.svg @@ -0,0 +1,282 @@ + + + + + + + + + + + + + + + + + + + + + + + Canevas 1 + + + Calque 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Closed tickets + resolution + + + + + + + Open tickets + triage state + + + + + + + Ready for + Checkin + + + + + + + Accepted + + + + + + + Unreviewed + + + + + + + duplicate + + + + + + + fixed + + + + + + + invalid + + + + + + + needsinfo + + + + + + + worksforme + + + + + + + wontfix + + + + + + + + + + + + completed + + + + + + stopped + + + + + + in progress + + + + + + + + Ticket triagers + + + + + + + + Mergers + + + + + + status + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The ticket was already reported, was + already rejected, isn't a bug, doesn't contain + enough information, or can't be reproduced. + + + + + + + + + + + + + The ticket is a + bug and should + be fixed. + + + + + + + + + + + + + The ticket has a patch which applies cleanly and includes all + needed tests and docs. A merger can commit it as is. + + + + + + + + + + + + + + diff --git a/testbed/django__django/docs/internals/contributing/bugs-and-features.txt b/testbed/django__django/docs/internals/contributing/bugs-and-features.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6b3265ba6bf52bb4fbe58d75defbe69cb353371 --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/bugs-and-features.txt @@ -0,0 +1,166 @@ +====================================== +Reporting bugs and requesting features +====================================== + +.. Important:: + + Please report security issues **only** to + security@djangoproject.com. This is a private list only open to + long-time, highly trusted Django developers, and its archives are + not public. For further details, please see :doc:`our security + policies `. + +Otherwise, before reporting a bug or requesting a new feature on the +`ticket tracker `_, consider these points: + +* Check that someone hasn't already filed the bug or feature request by + `searching`_ or running `custom queries`_ in the ticket tracker. + +* Don't use the ticket system to ask support questions. Use the + |django-users| list or the `#django`_ IRC channel for that. + +* Don't reopen issues that have been marked "wontfix" without finding consensus + to do so on the `Django Forum`_ or |django-developers| list. + +* Don't use the ticket tracker for lengthy discussions, because they're + likely to get lost. If a particular ticket is controversial, please move the + discussion to the `Django Forum`_ or |django-developers| list. + +.. _reporting-bugs: + +Reporting bugs +============== + +Well-written bug reports are *incredibly* helpful. However, there's a certain +amount of overhead involved in working with any bug tracking system so your +help in keeping our ticket tracker as useful as possible is appreciated. In +particular: + +* **Do** read the :doc:`FAQ ` to see if your issue might + be a well-known question. + +* **Do** ask on |django-users| or `#django`_ *first* if you're not sure if + what you're seeing is a bug. + +* **Do** write complete, reproducible, specific bug reports. You must + include a clear, concise description of the problem, and a set of + instructions for replicating it. Add as much debug information as you can: + code snippets, test cases, exception backtraces, screenshots, etc. A nice + small test case is the best way to report a bug, as it gives us a + helpful way to confirm the bug quickly. + +* **Don't** post to |django-developers| only to announce that you have filed a + bug report. All the tickets are mailed to another list, |django-updates|, + which is tracked by developers and interested community members; we see them + as they are filed. + +To understand the lifecycle of your ticket once you have created it, refer to +:doc:`triaging-tickets`. + +Reporting user interface bugs and features +========================================== + +If your bug or feature request touches on anything visual in nature, there +are a few additional guidelines to follow: + +* Include screenshots in your ticket which are the visual equivalent of a + minimal test case. Show off the issue, not the crazy customizations + you've made to your browser. + +* If the issue is difficult to show off using a still image, consider + capturing a *brief* screencast. If your software permits it, capture only + the relevant area of the screen. + +* If you're offering a patch that changes the look or behavior of Django's + UI, you **must** attach before *and* after screenshots/screencasts. + Tickets lacking these are difficult for triagers to assess quickly. + +* Screenshots don't absolve you of other good reporting practices. Make sure + to include URLs, code snippets, and step-by-step instructions on how to + reproduce the behavior visible in the screenshots. + +* Make sure to set the UI/UX flag on the ticket so interested parties can + find your ticket. + +Requesting features +=================== + +We're always trying to make Django better, and your feature requests are a key +part of that. Here are some tips on how to make a request most effectively: + +* Make sure the feature actually requires changes in Django's core. If your + idea can be developed as an independent application or module — for + instance, you want to support another database engine — we'll probably + suggest that you develop it independently. Then, if your project gathers + sufficient community support, we may consider it for inclusion in Django. + +* First request the feature on the `Django Forum`_ or |django-developers| list, + not in the ticket tracker. It'll get read more closely if it's on the mailing + list. This is even more important for large-scale feature requests. We like + to discuss any big changes to Django's core before actually working on them. + +* Describe clearly and concisely what the missing feature is and how you'd + like to see it implemented. Include example code (non-functional is OK) + if possible. + +* Explain *why* you'd like the feature. Explaining a minimal use case will help + others understand where it fits in, and if there are already other ways of + achieving the same thing. + +If there's a consensus agreement on the feature, then it's appropriate to +create a ticket. Include a link to the discussion in the ticket description. + +As with most open-source projects, code talks. If you are willing to write the +code for the feature yourself or, even better, if you've already written it, +it's much more likely to be accepted. Fork Django on GitHub, create a feature +branch, and show us your work! + +See also: :ref:`documenting-new-features`. + +.. _how-we-make-decisions: + +How we make decisions +===================== + +Whenever possible, we strive for a rough consensus. To that end, we'll often +have informal votes on |django-developers| or the Django Forum about a feature. +In these votes we follow the voting style invented by Apache and used on Python +itself, where votes are given as +1, +0, -0, or -1. +Roughly translated, these votes mean: + +* +1: "I love the idea and I'm strongly committed to it." + +* +0: "Sounds OK to me." + +* -0: "I'm not thrilled, but I won't stand in the way." + +* -1: "I strongly disagree and would be very unhappy to see the idea turn + into reality." + +Although these votes are informal, they'll be taken very seriously. After a +suitable voting period, if an obvious consensus arises we'll follow the votes. + +However, consensus is not always possible. If consensus cannot be reached, or +if the discussion toward a consensus fizzles out without a concrete decision, +the decision may be deferred to the :ref:`steering council `. + +Internally, the steering council will use the same voting mechanism. A +proposition will be considered carried if: + +* There are at least three "+1" votes from members of the steering council. + +* There is no "-1" vote from any member of the steering council. + +Votes should be submitted within a week. + +Since this process allows any steering council member to veto a proposal, a +"-1" vote should be accompanied by an explanation of what it would take to +convert that "-1" into at least a "+0". + +Votes on technical matters should be announced and held in public on the +|django-developers| mailing list or on the `Django Forum`_. + +.. _searching: https://code.djangoproject.com/search +.. _custom queries: https://code.djangoproject.com/query +.. _#django: https://web.libera.chat/#django +.. _Django Forum: https://forum.djangoproject.com/ diff --git a/testbed/django__django/docs/internals/contributing/committing-code.txt b/testbed/django__django/docs/internals/contributing/committing-code.txt new file mode 100644 index 0000000000000000000000000000000000000000..91c6d21beb562267922d322870c453111c0d2d36 --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/committing-code.txt @@ -0,0 +1,252 @@ +=============== +Committing code +=============== + +This section is addressed to the mergers and to anyone interested in knowing +how code gets committed into Django. If you're a community member who wants to +contribute code to Django, look at :doc:`writing-code/working-with-git` instead. + +.. _handling-pull-requests: + +Handling pull requests +====================== + +Since Django is hosted on GitHub, patches are provided in the form of pull +requests. + +When committing a pull request, make sure each individual commit matches the +commit guidelines described below. Contributors are expected to provide the +best pull requests possible. In practice mergers - who will likely be more +familiar with the commit guidelines - may decide to bring a commit up to +standard themselves. + +You may want to have Jenkins or GitHub actions test the pull request with one +of the pull request builders that doesn't run automatically, such as Oracle or +Selenium. See the `CI wiki page`_ for instructions. + +.. _CI wiki page: https://code.djangoproject.com/wiki/CI + +If you find yourself checking out pull requests locally more often, this git +alias will be helpful: + +.. code-block:: ini + + [alias] + pr = !sh -c \"git fetch upstream pull/${1}/head:pr/${1} && git checkout pr/${1}\" + +Add it to your ``~/.gitconfig``, and set ``upstream`` to be ``django/django``. +Then you can run ``git pr ####`` to checkout the corresponding pull request. + +At this point, you can work on the code. Use ``git rebase -i`` and ``git +commit --amend`` to make sure the commits have the expected level of quality. +Once you're ready: + +.. console:: + + $ # Pull in the latest changes from main. + $ git checkout main + $ git pull upstream main + $ # Rebase the pull request on main. + $ git checkout pr/#### + $ git rebase main + $ git checkout main + $ # Merge the work as "fast-forward" to main to avoid a merge commit. + $ # (in practice, you can omit "--ff-only" since you just rebased) + $ git merge --ff-only pr/XXXX + $ # If you're not sure if you did things correctly, check that only the + $ # changes you expect will be pushed to upstream. + $ git push --dry-run upstream main + $ # Push! + $ git push upstream main + $ # Delete the pull request branch. + $ git branch -d pr/xxxx + +Force push to the branch after rebasing on main but before merging and pushing +to upstream. This allows the commit hashes on main and the branch to match +which automatically closes the pull request. + +If a pull request doesn't need to be merged as multiple commits, you can use +GitHub's "Squash and merge" button on the website. Edit the commit message as +needed to conform to :ref:`the guidelines ` and remove +the pull request number that's automatically appended to the message's first +line. + +When rewriting the commit history of a pull request, the goal is to make +Django's commit history as usable as possible: + +* If a patch contains back-and-forth commits, then rewrite those into one. + For example, if a commit adds some code and a second commit fixes stylistic + issues introduced in the first commit, those commits should be squashed + before merging. + +* Separate changes to different commits by logical grouping: if you do a + stylistic cleanup at the same time as you do other changes to a file, + separating the changes into two different commits will make reviewing + history easier. + +* Beware of merges of upstream branches in the pull requests. + +* Tests should pass and docs should build after each commit. Neither the + tests nor the docs should emit warnings. + +* Trivial and small patches usually are best done in one commit. Medium to + large work may be split into multiple commits if it makes sense. + +Practicality beats purity, so it is up to each merger to decide how much +history mangling to do for a pull request. The main points are engaging the +community, getting work done, and having a usable commit history. + +.. _committing-guidelines: + +Committing guidelines +===================== + +In addition, please follow the following guidelines when committing code to +Django's Git repository: + +* Never change the published history of ``django/django`` branches by force + pushing. If you absolutely must (for security reasons for example), first + discuss the situation with the team. + +* For any medium-to-big changes, where "medium-to-big" is according to + your judgment, please bring things up on the `Django Forum`_ or + |django-developers| mailing list before making the change. + + If you bring something up and nobody responds, please don't take that + to mean your idea is great and should be implemented immediately because + nobody contested it. Everyone doesn't always have a lot of time to read + mailing list discussions immediately, so you may have to wait a couple of + days before getting a response. + +* Write detailed commit messages in the past tense, not present tense. + + * Good: "Fixed Unicode bug in RSS API." + * Bad: "Fixes Unicode bug in RSS API." + * Bad: "Fixing Unicode bug in RSS API." + + The commit message should be in lines of 72 chars maximum. There should be + a subject line, separated by a blank line and then paragraphs of 72 char + lines. The limits are soft. For the subject line, shorter is better. In the + body of the commit message more detail is better than less: + + .. code-block:: none + + Fixed #18307 -- Added git workflow guidelines. + + Refactored the Django's documentation to remove mentions of SVN + specific tasks. Added guidelines of how to use Git, GitHub, and + how to use pull request together with Trac instead. + + Credit the contributors in the commit message: "Thanks A for the report and B + for review." Use git's `Co-Authored-By`_ as appropriate. + + .. _Co-Authored-By: https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors + +* For commits to a branch, prefix the commit message with the branch name. + For example: "[1.4.x] Fixed #xxxxx -- Added support for mind reading." + +* Limit commits to the most granular change that makes sense. This means, + use frequent small commits rather than infrequent large commits. For + example, if implementing feature X requires a small change to library Y, + first commit the change to library Y, then commit feature X in a separate + commit. This goes a *long way* in helping everyone follow your changes. + +* Separate bug fixes from feature changes. Bugfixes may need to be backported + to the stable branch, according to :ref:`supported-versions-policy`. + +* If your commit closes a ticket in the Django `ticket tracker`_, begin + your commit message with the text "Fixed #xxxxx", where "xxxxx" is the + number of the ticket your commit fixes. Example: "Fixed #123 -- Added + whizbang feature.". We've rigged Trac so that any commit message in that + format will automatically close the referenced ticket and post a comment + to it with the full commit message. + + For the curious, we're using a `Trac plugin`_ for this. + +.. note:: + + Note that the Trac integration doesn't know anything about pull requests. + So if you try to close a pull request with the phrase "closes #400" in your + commit message, GitHub will close the pull request, but the Trac plugin + will not close the same numbered ticket in Trac. + +.. _Trac plugin: https://github.com/trac-hacks/trac-github + +* If your commit references a ticket in the Django `ticket tracker`_ but + does *not* close the ticket, include the phrase "Refs #xxxxx", where "xxxxx" + is the number of the ticket your commit references. This will automatically + post a comment to the appropriate ticket. + +* Write commit messages for backports using this pattern: + + .. code-block:: none + + [] Fixed -- + + Backport of from . + + For example: + + .. code-block:: none + + [1.3.x] Fixed #17028 -- Changed diveintopython.org -> diveintopython.net. + + Backport of 80c0cbf1c97047daed2c5b41b296bbc56fe1d7e3 from main. + + There's a `script on the wiki + `_ to + automate this. + + If the commit fixes a regression, include this in the commit message: + + .. code-block:: none + + Regression in 6ecccad711b52f9273b1acb07a57d3f806e93928. + + (use the commit hash where the regression was introduced). + +Reverting commits +================= + +Nobody's perfect; mistakes will be committed. + +But try very hard to ensure that mistakes don't happen. Just because we have a +reversion policy doesn't relax your responsibility to aim for the highest +quality possible. Really: double-check your work, or have it checked by +another merger **before** you commit it in the first place! + +When a mistaken commit is discovered, please follow these guidelines: + +* If possible, have the original author revert their own commit. + +* Don't revert another author's changes without permission from the + original author. + +* Use git revert -- this will make a reverse commit, but the original + commit will still be part of the commit history. + +* If the original author can't be reached (within a reasonable amount + of time -- a day or so) and the problem is severe -- crashing bug, + major test failures, etc. -- then ask for objections on the `Django Forum`_ + or |django-developers| mailing list then revert if there are none. + +* If the problem is small (a feature commit after feature freeze, + say), wait it out. + +* If there's a disagreement between the merger and the reverter-to-be then try + to work it out on the `Django Forum`_ or |django-developers| mailing list. If + an agreement can't be reached then it should be put to a vote. + +* If the commit introduced a confirmed, disclosed security + vulnerability then the commit may be reverted immediately without + permission from anyone. + +* The release branch maintainer may back out commits to the release + branch without permission if the commit breaks the release branch. + +* If you mistakenly push a topic branch to ``django/django``, delete it. + For instance, if you did: ``git push upstream feature_antigravity``, + do a reverse push: ``git push upstream :feature_antigravity``. + +.. _ticket tracker: https://code.djangoproject.com/ +.. _Django Forum: https://forum.djangoproject.com/ diff --git a/testbed/django__django/docs/internals/contributing/index.txt b/testbed/django__django/docs/internals/contributing/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..57b45214625dc6db94ed1033628c93e27ac744dd --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/index.txt @@ -0,0 +1,88 @@ +====================== +Contributing to Django +====================== + +Django is a community that lives on its volunteers. As it keeps growing, we +always need more people to help others. You can contribute in many ways, either +on the framework itself or in the wider ecosystem. + +Work on the Django framework +============================ + +The work on Django itself falls into three major areas: + +**Writing code** 💻 + Fix a bug, or add a new feature. You can make a pull request and see **your + code** in the next version of Django! + + Start from the :doc:`writing-code/index` docs. + +**Writing documentation** ✍️ + Django's documentation is one of its key strengths. It's informative + and thorough. You can help to improve the documentation and keep it + relevant as the framework evolves. + + See :doc:`writing-documentation` for more. + +**Localizing Django** 🗺️ + Django is translated into over 100 languages - There's even some + translation for Klingon?! The i18n team is always looking for translators + to help maintain and increase language reach. + + See :doc:`localizing` to help translate Django. + +If you think working *with* Django is fun, wait until you start working *on* +it. Really, **ANYONE** can do something to help make Django better and greater! + +This contributing guide contains everything you need to know to help build the +Django web framework. Browse the following sections to find out how: + +.. toctree:: + :maxdepth: 2 + + new-contributors + bugs-and-features + triaging-tickets + writing-code/index + writing-documentation + localizing + committing-code + +Join the Django community ❤️ +============================ + +We're passionate about helping Django users make the jump to contributing +members of the community. There are several other ways you can help the +Django community and others to maintain a great ecosystem to work in: + +* Join the `Django forum`_. This forum is a place for discussing the Django + framework and applications and projects that use it. This is also a good + place to ask and answer any questions related to installing, using, or + contributing to Django. + +* Join the |django-users| mailing list and answer questions. This + mailing list has a huge audience, and we really want to maintain a + friendly and helpful atmosphere. If you're new to the Django community, + you should read the `posting guidelines`_. + +* Join the `Django Discord server`_ or the `#django IRC channel`_ on + Libera.Chat to discuss and answer questions. By explaining Django to other + users, you're going to learn a lot about the framework yourself. + +* Blog about Django. We syndicate all the Django blogs we know about on + the `community page`_; if you'd like to see your blog on that page you + can `register it here`_. + +* Contribute to open-source Django projects, write some documentation, or + release your own code as an open-source pluggable application. The + ecosystem of pluggable applications is a big strength of Django, help us + build it! + +We're looking forward to working with you. Welcome aboard! ⛵️ + +.. _posting guidelines: https://code.djangoproject.com/wiki/UsingTheMailingList +.. _#django IRC channel: https://web.libera.chat/#django +.. _community page: https://www.djangoproject.com/community/ +.. _Django Discord server: https://discord.gg/xcRH6mN4fa +.. _Django forum: https://forum.djangoproject.com/ +.. _register it here: https://www.djangoproject.com/community/add/blogs/ diff --git a/testbed/django__django/docs/internals/contributing/localizing.txt b/testbed/django__django/docs/internals/contributing/localizing.txt new file mode 100644 index 0000000000000000000000000000000000000000..296f61233273aef6bbdccbb96d9082cd84b9ee1d --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/localizing.txt @@ -0,0 +1,90 @@ +================= +Localizing Django +================= + +Various parts of Django, such as the admin site and validation error messages, +are internationalized. This means they display differently depending on each +user's language or country. For this, Django uses the same internationalization +and localization infrastructure available to Django applications, described in +the :doc:`i18n documentation `. + +Translations +============ + +Translations are contributed by Django users worldwide. The translation work is +coordinated at `Transifex`_. + +If you find an incorrect translation or want to discuss specific translations, +go to the `Django project page`_. If you would like to help out with +translating or adding a language that isn't yet translated, here's what to do: + +* Introduce yourself on the `Django internationalization forum`_. + +* Make sure you read the notes about :ref:`specialties-of-django-i18n`. + +* Sign up at `Transifex`_ and visit the `Django project page`_. + +* On the `Django project page`_, choose the language you want to work on, + **or** -- in case the language doesn't exist yet -- + request a new language team by clicking on the "Request language" link + and selecting the appropriate language. + +* Then, click the "Join this Team" button to become a member of this team. + Every team has at least one coordinator who is responsible to review + your membership request. You can also contact the team coordinator to clarify + procedural problems and handle the actual translation process. + +* Once you are a member of a team choose the translation resource you + want to update on the team page. For example, the "core" resource refers + to the translation catalog that contains all non-contrib translations. + Each of the contrib apps also has a resource (prefixed with "contrib"). + + .. note:: + For more information about how to use Transifex, read the + `Transifex User Guide`_. + +Translations from Transifex are only integrated into the Django repository at +the time of a new :term:`feature release `. We try to update +them a second time during one of the following :term:`patch release +`\s, but that depends on the translation manager's availability. +So don't miss the string freeze period (between the release candidate and the +feature release) to take the opportunity to complete and fix the translations +for your language! + +Formats +======= + +You can also review ``conf/locale//formats.py``. This file describes +the date, time and numbers formatting particularities of your locale. See +:doc:`/topics/i18n/formatting` for details. + +The format files aren't managed by the use of Transifex. To change them, you +must :doc:`create a patch` against the +Django source tree, as for any code change: + +* Create a diff against the current Git main branch. + +* Open a ticket in Django's ticket system, set its ``Component`` field to + ``Translations``, and attach the patch to it. + +.. _Transifex: https://www.transifex.com/ +.. _Django project page: https://app.transifex.com/django/django/ +.. _Django internationalization forum: https://forum.djangoproject.com/c/internals/i18n/14 +.. _Transifex User Guide: https://help.transifex.com/ + +.. _translating-documentation: + +Documentation +============= + +There is also an opportunity to translate the documentation, though this is a +huge undertaking to complete entirely (you have been warned!). We use the same +`Transifex tool `_. The +translations will appear at ``https://docs.djangoproject.com//`` +when at least the ``docs/intro/*`` files are fully translated in your language. + +Once translations are published, updated versions from Transifex will be +irregularly ported to the `django/django-docs-translations +`_ repository and to the +documentation website. Only translations for the latest stable Django release +are updated. diff --git a/testbed/django__django/docs/internals/contributing/new-contributors.txt b/testbed/django__django/docs/internals/contributing/new-contributors.txt new file mode 100644 index 0000000000000000000000000000000000000000..8e81031b32479f3fc946dad564c8facd804d728c --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/new-contributors.txt @@ -0,0 +1,157 @@ +=========================== +Advice for new contributors +=========================== + +New contributor and not sure what to do? Want to help but just don't know how +to get started? This is the section for you. + +.. admonition:: Get up and running! + + If you are new to contributing to Django, the :doc:`/intro/contributing` + tutorial will give you an introduction to the tools and the workflow. + +This page contains more general advice on ways you can contribute to Django, +and how to approach that. + +If you are looking for a reference on the details of making code contributions, +see the :doc:`/internals/contributing/writing-code/index` documentation. + +First steps +=========== + +Start with these steps to discover Django's development process. + +* **Triage tickets** + + If an `unreviewed ticket`_ reports a bug, try and reproduce it. If you + can reproduce it and it seems valid, make a note that you confirmed the bug + and accept the ticket. Make sure the ticket is filed under the correct + component area. Consider writing a patch that adds a test for the bug's + behavior, even if you don't fix the bug itself. See more at + :ref:`how-can-i-help-with-triaging` + +* **Look for tickets that are accepted and review patches to build familiarity + with the codebase and the process** + + Mark the appropriate flags if a patch needs docs or tests. Look through the + changes a patch makes, and keep an eye out for syntax that is incompatible + with older but still supported versions of Python. :doc:`Run the tests + ` and make sure they pass. + Where possible and relevant, try them out on a database other than SQLite. + Leave comments and feedback! + +* **Keep old patches up to date** + + Oftentimes the codebase will change between a patch being submitted and the + time it gets reviewed. Make sure it still applies cleanly and functions as + expected. Updating a patch is both useful and important! See more on + :doc:`writing-code/submitting-patches`. + +* **Write some documentation** + + Django's documentation is great but it can always be improved. Did you find + a typo? Do you think that something should be clarified? Go ahead and + suggest a documentation patch! See also the guide on + :doc:`writing-documentation`. + + .. note:: + + The `reports page`_ contains links to many useful Trac queries, including + several that are useful for triaging tickets and reviewing patches as + suggested above. + + .. _reports page: https://code.djangoproject.com/wiki/Reports + +* **Sign the Contributor License Agreement** + + The code that you write belongs to you or your employer. If your + contribution is more than one or two lines of code, you need to sign the + `CLA`_. See the `Contributor License Agreement FAQ`_ for a more thorough + explanation. + +.. _CLA: https://www.djangoproject.com/foundation/cla/ +.. _Contributor License Agreement FAQ: https://www.djangoproject.com/foundation/cla/faq/ +.. _unreviewed ticket: https://code.djangoproject.com/query?status=!closed&stage=Unreviewed + + +Guidelines +========== + +As a newcomer on a large project, it's easy to experience frustration. Here's +some advice to make your work on Django more useful and rewarding. + +* **Pick a subject area that you care about, that you are familiar with, or + that you want to learn about** + + You don't already have to be an expert on the area you want to work on; you + become an expert through your ongoing contributions to the code. + +* **Analyze tickets' context and history** + + Trac isn't an absolute; the context is just as important as the words. + When reading Trac, you need to take into account who says things, and when + they were said. Support for an idea two years ago doesn't necessarily mean + that the idea will still have support. You also need to pay attention to who + *hasn't* spoken -- for example, if an experienced contributor hasn't been + recently involved in a discussion, then a ticket may not have the support + required to get into Django. + +* **Start small** + + It's easier to get feedback on a little issue than on a big one. See the + `easy pickings`_. + +* **If you're going to engage in a big task, make sure that your idea has + support first** + + This means getting someone else to confirm that a bug is real before you fix + the issue, and ensuring that there's consensus on a proposed feature before + you go implementing it. + +* **Be bold! Leave feedback!** + + Sometimes it can be scary to put your opinion out to the world and say "this + ticket is correct" or "this patch needs work", but it's the only way the + project moves forward. The contributions of the broad Django community + ultimately have a much greater impact than that of any one person. We can't + do it without **you**! + +* **Err on the side of caution when marking things Ready For Check-in** + + If you're really not certain if a ticket is ready, don't mark it as + such. Leave a comment instead, letting others know your thoughts. If you're + mostly certain, but not completely certain, you might also try asking on IRC + to see if someone else can confirm your suspicions. + +* **Wait for feedback, and respond to feedback that you receive** + + Focus on one or two tickets, see them through from start to finish, and + repeat. The shotgun approach of taking on lots of tickets and letting some + fall by the wayside ends up doing more harm than good. + +* **Be rigorous** + + When we say ":pep:`8`, and must have docs and tests", we mean it. If a patch + doesn't have docs and tests, there had better be a good reason. Arguments + like "I couldn't find any existing tests of this feature" don't carry much + weight--while it may be true, that means you have the extra-important job of + writing the very first tests for that feature, not that you get a pass from + writing tests altogether. + +* **Be patient** + + It's not always easy for your ticket or your patch to be reviewed quickly. + This isn't personal. There are a lot of tickets and pull requests to get + through. + + Keeping your patch up to date is important. Review the ticket on Trac to + ensure that the *Needs tests*, *Needs documentation*, and *Patch needs + improvement* flags are unchecked once you've addressed all review comments. + + Remember that Django has an eight-month release cycle, so there's plenty of + time for your patch to be reviewed. + + Finally, a well-timed reminder can help. See :ref:`contributing code FAQ + ` for ideas here. + +.. _easy pickings: https://code.djangoproject.com/query?status=!closed&easy=1 diff --git a/testbed/django__django/docs/internals/contributing/triaging-tickets.txt b/testbed/django__django/docs/internals/contributing/triaging-tickets.txt new file mode 100644 index 0000000000000000000000000000000000000000..74734050077ac444bce1621e79ff8fa429008dec --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/triaging-tickets.txt @@ -0,0 +1,468 @@ +================ +Triaging tickets +================ + +Django uses Trac_ for managing the work on the code base. Trac is a +community-tended garden of the bugs people have found and the features people +would like to see added. As in any garden, sometimes there are weeds to be +pulled and sometimes there are flowers and vegetables that need picking. We need +your help to sort out one from the other, and in the end, we all benefit +together. + +Like all gardens, we can aspire to perfection, but in reality there's no such +thing. Even in the most pristine garden there are still snails and insects. +In a community garden there are also helpful people who -- with the best of +intentions -- fertilize the weeds and poison the roses. It's the job of the +community as a whole to self-manage, keep the problems to a minimum, and +educate those coming into the community so that they can become valuable +contributing members. + +Similarly, while we aim for Trac to be a perfect representation of the state of +Django's progress, we acknowledge that this will not happen. By distributing +the load of Trac maintenance to the community, we accept that there will be +mistakes. Trac is "mostly accurate", and we give allowances for the fact that +sometimes it will be wrong. That's okay. We're perfectionists with deadlines. + +We rely on the community to keep participating, keep tickets as accurate as +possible, and raise issues for discussion on our mailing lists when there is +confusion or disagreement. + +Django is a community project, and every contribution helps. We can't do this +without **you**! + +Triage workflow +=============== + +Unfortunately, not all bug reports and feature requests in the ticket tracker +provide all the :doc:`required details`. A number of +tickets have patches, but those patches don't meet all the requirements of a +:ref:`good patch`. + +One way to help out is to *triage* tickets that have been created by other +users. + +Most of the workflow is based around the concept of a ticket's +:ref:`triage stages `. Each stage describes where in its +lifetime a given ticket is at any time. Along with a handful of flags, this +attribute easily tells us what and who each ticket is waiting on. + +Since a picture is worth a thousand words, let's start there: + +.. image:: /internals/_images/triage_process.* + :height: 501 + :width: 400 + :alt: Django's ticket triage workflow + +We've got two roles in this diagram: + +* Mergers: people with commit access who are responsible for making the + final decision to merge a patch. + +* Ticket triagers: anyone in the Django community who chooses to + become involved in Django's development process. Our Trac installation + is intentionally left open to the public, and anyone can triage tickets. + Django is a community project, and we encourage :ref:`triage by the + community`. + +By way of example, here we see the lifecycle of an average ticket: + +* Alice creates a ticket and sends an incomplete pull request (no tests, + incorrect implementation). + +* Bob reviews the pull request, marks the ticket as "Accepted", "needs tests", + and "patch needs improvement", and leaves a comment telling Alice how the + patch could be improved. + +* Alice updates the pull request, adding tests (but not changing the + implementation). She removes the two flags. + +* Charlie reviews the pull request and resets the "patch needs improvement" + flag with another comment about improving the implementation. + +* Alice updates the pull request, fixing the implementation. She removes the + "patch needs improvement" flag. + +* Daisy reviews the pull request and marks the ticket as "Ready for checkin". + +* Jacob, a :ref:`merger `, reviews the pull request and merges + it. + +Some tickets require much less feedback than this, but then again some tickets +require much much more. + +.. _triage-stages: + +Triage stages +============= + +Below we describe in more detail the various stages that a ticket may flow +through during its lifetime. + +Unreviewed +---------- + +The ticket has not been reviewed by anyone who felt qualified to make a +judgment about whether the ticket contained a valid issue, a viable feature, +or ought to be closed for any of the various reasons. + +Accepted +-------- + +The big gray area! The absolute meaning of "accepted" is that the issue +described in the ticket is valid and is in some stage of being worked on. +Beyond that there are several considerations: + +* **Accepted + No Flags** + + The ticket is valid, but no one has submitted a patch for it yet. Often this + means you could safely start writing a patch for it. This is generally more + true for the case of accepted bugs than accepted features. A ticket for a bug + that has been accepted means that the issue has been verified by at least one + triager as a legitimate bug - and should probably be fixed if possible. An + accepted new feature may only mean that one triager thought the feature would + be good to have, but this alone does not represent a consensus view or imply + with any certainty that a patch will be accepted for that feature. Seek more + feedback before writing an extensive patch if you are in doubt. + +* **Accepted + Has Patch** + + The ticket is waiting for people to review the supplied patch. This means + downloading the patch and trying it out, verifying that it contains tests + and docs, running the test suite with the included patch, and leaving + feedback on the ticket. + +* **Accepted + Has Patch + Needs ...** + + This means the ticket has been reviewed, and has been found to need further + work. "Needs tests" and "Needs documentation" are self-explanatory. "Patch + needs improvement" will generally be accompanied by a comment on the ticket + explaining what is needed to improve the code. + +Ready For Checkin +----------------- + +The ticket was reviewed by any member of the community other than the person +who supplied the patch and found to meet all the requirements for a +commit-ready patch. A :ref:`merger ` now needs to give the patch +a final review prior to being committed. + +There are a lot of pull requests. It can take a while for your patch to get +reviewed. See the :ref:`contributing code FAQ` for some +ideas here. + +Someday/Maybe +------------- + +This stage isn't shown on the diagram. It's used sparingly to keep track of +high-level ideas or long-term feature requests. + +These tickets are uncommon and overall less useful since they don't describe +concrete actionable issues. They are enhancement requests that we might +consider adding someday to the framework if an excellent patch is submitted. +They are not a high priority. + +Other triage attributes +======================= + +A number of flags, appearing as checkboxes in Trac, can be set on a ticket: + +Has patch +--------- + +This means the ticket has an associated +:doc:`patch`. These will be reviewed +to see if the patch is "good". + +The following three fields (Needs documentation, Needs tests, +Patch needs improvement) apply only if a patch has been supplied. + +Needs documentation +------------------- + +This flag is used for tickets with patches that need associated +documentation. Complete documentation of features is a prerequisite +before we can check them into the codebase. + +Needs tests +----------- + +This flags the patch as needing associated unit tests. Again, this +is a required part of a valid patch. + +Patch needs improvement +----------------------- + +This flag means that although the ticket *has* a patch, it's not quite +ready for checkin. This could mean the patch no longer applies +cleanly, there is a flaw in the implementation, or that the code +doesn't meet our standards. + +Easy pickings +------------- + +Tickets that would require small, easy, patches. + +Type +---- + +Tickets should be categorized by *type* between: + +* New Feature + For adding something new. + +* Bug + For when an existing thing is broken or not behaving as expected. + +* Cleanup/optimization + For when nothing is broken but something could be made cleaner, + better, faster, stronger. + +Component +--------- + +Tickets should be classified into *components* indicating which area of +the Django codebase they belong to. This makes tickets better organized and +easier to find. + +Severity +-------- + +The *severity* attribute is used to identify blockers, that is, issues that +should get fixed before releasing the next version of Django. Typically those +issues are bugs causing regressions from earlier versions or potentially +causing severe data losses. This attribute is quite rarely used and the vast +majority of tickets have a severity of "Normal". + +Version +------- + +It is possible to use the *version* attribute to indicate in which +version the reported bug was identified. + +UI/UX +----- + +This flag is used for tickets that relate to User Interface and User +Experiences questions. For example, this flag would be appropriate for +user-facing features in forms or the admin interface. + +Cc +-- + +You may add your username or email address to this field to be notified when +new contributions are made to the ticket. + +Keywords +-------- + +With this field you may label a ticket with multiple keywords. This can be +useful, for example, to group several tickets on the same theme. Keywords can +either be comma or space separated. Keyword search finds the keyword string +anywhere in the keywords. For example, clicking on a ticket with the keyword +"form" will yield similar tickets tagged with keywords containing strings such +as "formset", "modelformset", and "ManagementForm". + +.. _closing-tickets: + +Closing Tickets +=============== + +When a ticket has completed its useful lifecycle, it's time for it to be +closed. Closing a ticket is a big responsibility, though. You have to be sure +that the issue is really resolved, and you need to keep in mind that the +reporter of the ticket may not be happy to have their ticket closed (unless +it's fixed!). If you're not certain about closing a ticket, leave a comment +with your thoughts instead. + +If you do close a ticket, you should always make sure of the following: + +* Be certain that the issue is resolved. + +* Leave a comment explaining the decision to close the ticket. + +* If there is a way they can improve the ticket to reopen it, let them know. + +* If the ticket is a duplicate, reference the original ticket. Also + cross-reference the closed ticket by leaving a comment in the original one + -- this allows to access more related information about the reported bug + or requested feature. + +* **Be polite.** No one likes having their ticket closed. It can be + frustrating or even discouraging. The best way to avoid turning people + off from contributing to Django is to be polite and friendly and to offer + suggestions for how they could improve this ticket and other tickets in + the future. + +A ticket can be resolved in a number of ways: + +* fixed + Used once a patch has been rolled into Django and the issue is fixed. + +* invalid + Used if the ticket is found to be incorrect. This means that the + issue in the ticket is actually the result of a user error, or + describes a problem with something other than Django, or isn't + a bug report or feature request at all (for example, some new users + submit support queries as tickets). + +* wontfix + Used when someone decides that the request isn't appropriate for + consideration in Django. Sometimes a ticket is closed as "wontfix" with a + request for the reporter to start a discussion on the `Django Forum`_ or + |django-developers| mailing list if they feel differently from the + rationale provided by the person who closed the ticket. Other times, a + discussion precedes the decision to close a ticket. Always use the forum + or mailing list to get a consensus before reopening tickets closed as + "wontfix". + +* duplicate + Used when another ticket covers the same issue. By closing duplicate + tickets, we keep all the discussion in one place, which helps + everyone. + +* worksforme + Used when the ticket doesn't contain enough detail to replicate + the original bug. + +* needsinfo + Used when the ticket does not contain enough information to replicate + the reported issue but is potentially still valid. The ticket + should be reopened when more information is supplied. + +If you believe that the ticket was closed in error -- because you're +still having the issue, or it's popped up somewhere else, or the triagers have +made a mistake -- please reopen the ticket and provide further information. +Again, please do not reopen tickets that have been marked as "wontfix" and +bring the issue to the `Django Forum`_ or |django-developers| instead. + +.. _how-can-i-help-with-triaging: + +How can I help with triaging? +============================= + +The triage process is primarily driven by community members. Really, +**ANYONE** can help. + +To get involved, start by `creating an account on Trac`_. If you have an +account but have forgotten your password, you can reset it using the `password +reset page`_. + +Then, you can help out by: + +* Closing "Unreviewed" tickets as "invalid", "worksforme", or "duplicate", or + "wontfix". + +* Closing "Unreviewed" tickets as "needsinfo" when the description is too + sparse to be actionable, or when they're feature requests requiring a + discussion on the `Django Forum`_ or |django-developers|. + +* Correcting the "Needs tests", "Needs documentation", or "Has patch" + flags for tickets where they are incorrectly set. + +* Setting the "`Easy pickings`_" flag for tickets that are small and + relatively straightforward. + +* Set the *type* of tickets that are still uncategorized. + +* Checking that old tickets are still valid. If a ticket hasn't seen + any activity in a long time, it's possible that the problem has been + fixed but the ticket hasn't yet been closed. + +* Identifying trends and themes in the tickets. If there are a lot of bug + reports about a particular part of Django, it may indicate we should + consider refactoring that part of the code. If a trend is emerging, + you should raise it for discussion (referencing the relevant tickets) + on the `Django Forum`_ or |django-developers|. + +* Verify if patches submitted by other users are correct. If they are correct + and also contain appropriate documentation and tests then move them to the + "Ready for Checkin" stage. If they are not correct then leave a comment to + explain why and set the corresponding flags ("Patch needs improvement", + "Needs tests" etc.). + +.. note:: + + The `Reports page`_ contains links to many useful Trac queries, including + several that are useful for triaging tickets and reviewing patches as + suggested above. + + You can also find more :doc:`new-contributors`. + + .. _Reports page: https://code.djangoproject.com/wiki/Reports + +However, we do ask the following of all general community members working in +the ticket database: + +* Please **don't** promote your own tickets to "Ready for checkin". You + may mark other people's tickets that you've reviewed as "Ready for + checkin", but you should get at minimum one other community member to + review a patch that you submit. + +* Please **don't** reverse a decision without posting a message to the + `Django Forum`_ or |django-developers| to find consensus. + +* If you're unsure if you should be making a change, don't make the + change but instead leave a comment with your concerns on the ticket, + or post a message to the `Django Forum`_ or |django-developers|. It's okay to + be unsure, but your input is still valuable. + +.. _Trac: https://code.djangoproject.com/ +.. _`easy pickings`: https://code.djangoproject.com/query?status=!closed&easy=1 +.. _`creating an account on Trac`: https://www.djangoproject.com/accounts/register/ +.. _password reset page: https://www.djangoproject.com/accounts/password/reset/ +.. _Django Forum: https://forum.djangoproject.com/ + +Bisecting a regression +====================== + +A regression is a bug that's present in some newer version of Django but not in +an older one. An extremely helpful piece of information is the commit that +introduced the regression. Knowing the commit that caused the change in +behavior helps identify if the change was intentional or if it was an +inadvertent side-effect. Here's how you can determine this. + +Begin by writing a regression test for Django's test suite for the issue. For +example, we'll pretend we're debugging a regression in migrations. After you've +written the test and confirmed that it fails on the latest main branch, put it +in a separate file that you can run standalone. For our example, we'll pretend +we created ``tests/migrations/test_regression.py``, which can be run with: + +.. code-block:: shell + + $ ./runtests.py migrations.test_regression + +Next, we mark the current point in history as being "bad" since the test fails: + +.. code-block:: shell + + $ git bisect bad + You need to start by "git bisect start" + Do you want me to do it for you [Y/n]? y + +Now, we need to find a point in git history before the regression was +introduced (i.e. a point where the test passes). Use something like +``git checkout HEAD~100`` to check out an earlier revision (100 commits earlier, +in this case). Check if the test fails. If so, mark that point as "bad" +(``git bisect bad``), then check out an earlier revision and recheck. Once you +find a revision where your test passes, mark it as "good": + +.. code-block:: shell + + $ git bisect good + Bisecting: X revisions left to test after this (roughly Y steps) + ... + +Now we're ready for the fun part: using ``git bisect run`` to automate the rest +of the process: + +.. code-block:: shell + + $ git bisect run tests/runtests.py migrations.test_regression + +You should see ``git bisect`` use a binary search to automatically checkout +revisions between the good and bad commits until it finds the first "bad" +commit where the test fails. + +Now, report your results on the Trac ticket, and please include the regression +test as an attachment. When someone writes a fix for the bug, they'll already +have your test as a starting point. diff --git a/testbed/django__django/docs/internals/contributing/writing-code/coding-style.txt b/testbed/django__django/docs/internals/contributing/writing-code/coding-style.txt new file mode 100644 index 0000000000000000000000000000000000000000..d227e04ba0feb09129725c3248dfb06a232c80d0 --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/writing-code/coding-style.txt @@ -0,0 +1,378 @@ +============ +Coding style +============ + +Please follow these coding standards when writing code for inclusion in Django. + +.. _coding-style-pre-commit: + +Pre-commit checks +================= + +`pre-commit `_ is a framework for managing pre-commit +hooks. These hooks help to identify simple issues before committing code for +review. By checking for these issues before code review it allows the reviewer +to focus on the change itself, and it can also help to reduce the number of CI +runs. + +To use the tool, first install ``pre-commit`` and then the git hooks: + +.. console:: + + $ python -m pip install pre-commit + $ pre-commit install + +On the first commit ``pre-commit`` will install the hooks, these are +installed in their own environments and will take a short while to +install on the first run. Subsequent checks will be significantly faster. +If an error is found an appropriate error message will be displayed. +If the error was with ``black`` or ``isort`` then the tool will go ahead and +fix them for you. Review the changes and re-stage for commit if you are happy +with them. + +.. _coding-style-python: + +Python style +============ + +* All files should be formatted using the `black`_ auto-formatter. This will be + run by ``pre-commit`` if that is configured. + +* The project repository includes an ``.editorconfig`` file. We recommend using + a text editor with `EditorConfig`_ support to avoid indentation and + whitespace issues. The Python files use 4 spaces for indentation and the HTML + files use 2 spaces. + +* Unless otherwise specified, follow :pep:`8`. + + Use :pypi:`flake8` to check for problems in this area. Note that our + ``setup.cfg`` file contains some excluded files (deprecated modules we don't + care about cleaning up and some third-party code that Django vendors) as well + as some excluded errors that we don't consider as gross violations. Remember + that :pep:`8` is only a guide, so respect the style of the surrounding code + as a primary goal. + + An exception to :pep:`8` is our rules on line lengths. Don't limit lines of + code to 79 characters if it means the code looks significantly uglier or is + harder to read. We allow up to 88 characters as this is the line length used + by ``black``. This check is included when you run ``flake8``. Documentation, + comments, and docstrings should be wrapped at 79 characters, even though + :pep:`8` suggests 72. + +* String variable interpolation may use + :py:ref:`%-formatting `, :py:ref:`f-strings + `, or :py:meth:`str.format` as appropriate, with the goal of + maximizing code readability. + + Final judgments of readability are left to the Merger's discretion. As a + guide, f-strings should use only plain variable and property access, with + prior local variable assignment for more complex cases:: + + # Allowed + f"hello {user}" + f"hello {user.name}" + f"hello {self.user.name}" + + # Disallowed + f"hello {get_user()}" + f"you are {user.age * 365.25} days old" + + # Allowed with local variable assignment + user = get_user() + f"hello {user}" + user_days_old = user.age * 365.25 + f"you are {user_days_old} days old" + + f-strings should not be used for any string that may require translation, + including error and logging messages. In general ``format()`` is more + verbose, so the other formatting methods are preferred. + + Don't waste time doing unrelated refactoring of existing code to adjust the + formatting method. + +* Avoid use of "we" in comments, e.g. "Loop over" rather than "We loop over". + +* Use underscores, not camelCase, for variable, function and method names + (i.e. ``poll.get_unique_voters()``, not ``poll.getUniqueVoters()``). + +* Use ``InitialCaps`` for class names (or for factory functions that + return classes). + +* In docstrings, follow the style of existing docstrings and :pep:`257`. + +* In tests, use + :meth:`~django.test.SimpleTestCase.assertRaisesMessage` and + :meth:`~django.test.SimpleTestCase.assertWarnsMessage` + instead of :meth:`~unittest.TestCase.assertRaises` and + :meth:`~unittest.TestCase.assertWarns` so you can check the + exception or warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex` + and :meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular + expression matching. + + Use :meth:`assertIs(…, True/False)` for testing + boolean values, rather than :meth:`~unittest.TestCase.assertTrue` and + :meth:`~unittest.TestCase.assertFalse`, so you can check the actual boolean + value, not the truthiness of the expression. + +* In test docstrings, state the expected behavior that each test demonstrates. + Don't include preambles such as "Tests that" or "Ensures that". + + Reserve ticket references for obscure issues where the ticket has additional + details that can't be easily described in docstrings or comments. Include the + ticket number at the end of a sentence like this:: + + def test_foo(): + """ + A test docstring looks like this (#123456). + """ + ... + +.. _coding-style-imports: + +Imports +======= + +* Use `isort `_ to automate import + sorting using the guidelines below. + + Quick start: + + .. console:: + + $ python -m pip install "isort >= 5.1.0" + $ isort . + + This runs ``isort`` recursively from your current directory, modifying any + files that don't conform to the guidelines. If you need to have imports out + of order (to avoid a circular import, for example) use a comment like this:: + + import module # isort:skip + +* Put imports in these groups: future, standard library, third-party libraries, + other Django components, local Django component, try/excepts. Sort lines in + each group alphabetically by the full module name. Place all ``import module`` + statements before ``from module import objects`` in each section. Use absolute + imports for other Django components and relative imports for local components. + +* On each line, alphabetize the items with the upper case items grouped before + the lowercase items. + +* Break long lines using parentheses and indent continuation lines by 4 spaces. + Include a trailing comma after the last import and put the closing + parenthesis on its own line. + + Use a single blank line between the last import and any module level code, + and use two blank lines above the first function or class. + + For example (comments are for explanatory purposes only): + + .. code-block:: python + :caption: ``django/contrib/admin/example.py`` + + # future + from __future__ import unicode_literals + + # standard library + import json + from itertools import chain + + # third-party + import bcrypt + + # Django + from django.http import Http404 + from django.http.response import ( + Http404, + HttpResponse, + HttpResponseNotAllowed, + StreamingHttpResponse, + cookie, + ) + + # local Django + from .models import LogEntry + + # try/except + try: + import yaml + except ImportError: + yaml = None + + CONSTANT = "foo" + + + class Example: + ... + +* Use convenience imports whenever available. For example, do this + :: + + from django.views import View + + instead of:: + + from django.views.generic.base import View + +Template style +============== + +* In Django template code, put one (and only one) space between the curly + brackets and the tag contents. + + Do this: + + .. code-block:: html+django + + {{ foo }} + + Don't do this: + + .. code-block:: html+django + + {{foo}} + +View style +========== + +* In Django views, the first parameter in a view function should be called + ``request``. + + Do this:: + + def my_view(request, foo): + ... + + Don't do this:: + + def my_view(req, foo): + ... + +Model style +=========== + +* Field names should be all lowercase, using underscores instead of + camelCase. + + Do this:: + + class Person(models.Model): + first_name = models.CharField(max_length=20) + last_name = models.CharField(max_length=40) + + Don't do this:: + + class Person(models.Model): + FirstName = models.CharField(max_length=20) + Last_Name = models.CharField(max_length=40) + +* The ``class Meta`` should appear *after* the fields are defined, with + a single blank line separating the fields and the class definition. + + Do this:: + + class Person(models.Model): + first_name = models.CharField(max_length=20) + last_name = models.CharField(max_length=40) + + class Meta: + verbose_name_plural = "people" + + Don't do this:: + + class Person(models.Model): + class Meta: + verbose_name_plural = "people" + + first_name = models.CharField(max_length=20) + last_name = models.CharField(max_length=40) + +* The order of model inner classes and standard methods should be as + follows (noting that these are not all required): + + * All database fields + * Custom manager attributes + * ``class Meta`` + * ``def __str__()`` + * ``def save()`` + * ``def get_absolute_url()`` + * Any custom methods + +* If ``choices`` is defined for a given model field, define each choice as a + list of tuples, with an all-uppercase name as a class attribute on the model. + Example:: + + class MyModel(models.Model): + DIRECTION_UP = "U" + DIRECTION_DOWN = "D" + DIRECTION_CHOICES = [ + (DIRECTION_UP, "Up"), + (DIRECTION_DOWN, "Down"), + ] + +Use of ``django.conf.settings`` +=============================== + +Modules should not in general use settings stored in ``django.conf.settings`` +at the top level (i.e. evaluated when the module is imported). The explanation +for this is as follows: + +Manual configuration of settings (i.e. not relying on the +:envvar:`DJANGO_SETTINGS_MODULE` environment variable) is allowed and possible +as follows:: + + from django.conf import settings + + settings.configure({}, SOME_SETTING="foo") + +However, if any setting is accessed before the ``settings.configure`` line, +this will not work. (Internally, ``settings`` is a ``LazyObject`` which +configures itself automatically when the settings are accessed if it has not +already been configured). + +So, if there is a module containing some code as follows:: + + from django.conf import settings + from django.urls import get_callable + + default_foo_view = get_callable(settings.FOO_VIEW) + +...then importing this module will cause the settings object to be configured. +That means that the ability for third parties to import the module at the top +level is incompatible with the ability to configure the settings object +manually, or makes it very difficult in some circumstances. + +Instead of the above code, a level of laziness or indirection must be used, +such as ``django.utils.functional.LazyObject``, +``django.utils.functional.lazy()`` or ``lambda``. + +Miscellaneous +============= + +* Mark all strings for internationalization; see the :doc:`i18n + documentation ` for details. + +* Remove ``import`` statements that are no longer used when you change code. + :pypi:`flake8` will identify these imports for you. If an unused import needs + to remain for backwards-compatibility, mark the end of with ``# NOQA`` to + silence the flake8 warning. + +* Systematically remove all trailing whitespaces from your code as those + add unnecessary bytes, add visual clutter to the patches and can also + occasionally cause unnecessary merge conflicts. Some IDE's can be + configured to automatically remove them and most VCS tools can be set to + highlight them in diff outputs. + +* Please don't put your name in the code you contribute. Our policy is to + keep contributors' names in the ``AUTHORS`` file distributed with Django + -- not scattered throughout the codebase itself. Feel free to include a + change to the ``AUTHORS`` file in your patch if you make more than a + single trivial change. + +JavaScript style +================ + +For details about the JavaScript code style used by Django, see +:doc:`javascript`. + +.. _black: https://black.readthedocs.io/en/stable/ +.. _editorconfig: https://editorconfig.org/ diff --git a/testbed/django__django/docs/internals/contributing/writing-code/index.txt b/testbed/django__django/docs/internals/contributing/writing-code/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..9402c26808f11d714d01e38c9d6a5be03f07d8c3 --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/writing-code/index.txt @@ -0,0 +1,43 @@ +============ +Writing code +============ + +So you'd like to write some code to improve Django? Awesome! There are several +ways you can help Django's development: + +* :doc:`Report bugs <../bugs-and-features>` in our `ticket tracker`_. + +* Join the |django-developers| mailing list and share your ideas for how to + improve Django. We're always open to suggestions. You can also interact on + the `Django forum`_ and the `#django-dev IRC channel`_. + +* :doc:`Submit patches ` for new and/or fixed behavior. If + you're looking for a way to get started contributing to Django read the + :doc:`/intro/contributing` tutorial and have a look at the `easy pickings`_ + tickets. The :ref:`patch-review-checklist` will also be helpful. + +* :doc:`Improve the documentation <../writing-documentation>` or :doc:`write + unit tests `. + +* :doc:`Triage tickets and review patches <../triaging-tickets>` created by + other users. + +* Read the :doc:`../new-contributors` to help you get orientated in the + development process. + +Browse the following sections to find out how to give your code patches the +best chances to be included in Django core: + +.. toctree:: + :maxdepth: 1 + + coding-style + unit-tests + submitting-patches + working-with-git + javascript + +.. _ticket tracker: https://code.djangoproject.com/ +.. _easy pickings: https://code.djangoproject.com/query?status=!closed&easy=1 +.. _#django-dev IRC channel: https://web.libera.chat/#django-dev +.. _Django forum: https://forum.djangoproject.com/ diff --git a/testbed/django__django/docs/internals/contributing/writing-code/javascript.txt b/testbed/django__django/docs/internals/contributing/writing-code/javascript.txt new file mode 100644 index 0000000000000000000000000000000000000000..657cc66ded35a9b2a7bc3c017f77af7f458340b1 --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/writing-code/javascript.txt @@ -0,0 +1,124 @@ +========== +JavaScript +========== + +While most of Django core is Python, the ``admin`` and ``gis`` contrib apps +contain JavaScript code. + +Please follow these coding standards when writing JavaScript code for inclusion +in Django. + +Code style +========== + +* Please conform to the indentation style dictated in the ``.editorconfig`` + file. We recommend using a text editor with `EditorConfig`_ support to avoid + indentation and whitespace issues. Most of the JavaScript files use 4 spaces + for indentation, but there are some exceptions. + +* When naming variables, use ``camelCase`` instead of ``underscore_case``. + Different JavaScript files sometimes use a different code style. Please try to + conform to the code style of each file. + +* Use the `ESLint`_ code linter to check your code for bugs and style errors. + ESLint will be run when you run the JavaScript tests. We also recommended + installing a ESLint plugin in your text editor. + +* Where possible, write code that will work even if the page structure is later + changed with JavaScript. For instance, when binding a click handler, use + ``$('body').on('click', selector, func)`` instead of + ``$(selector).click(func)``. This makes it easier for projects to extend + Django's default behavior with JavaScript. + +.. _javascript-patches: + +JavaScript patches +================== + +Django's admin system leverages the jQuery framework to increase the +capabilities of the admin interface. In conjunction, there is an emphasis on +admin JavaScript performance and minimizing overall admin media file size. + +.. _javascript-tests: + +JavaScript tests +================ + +Django's JavaScript tests can be run in a browser or from the command line. +The tests are located in a top level :source:`js_tests` directory. + +Writing tests +------------- + +Django's JavaScript tests use `QUnit`_. Here is an example test module: + +.. code-block:: javascript + + QUnit.module('magicTricks', { + beforeEach: function() { + const $ = django.jQuery; + $('#qunit-fixture').append(''); + } + }); + + QUnit.test('removeOnClick removes button on click', function(assert) { + const $ = django.jQuery; + removeOnClick('.button'); + assert.equal($('.button').length, 1); + $('.button').click(); + assert.equal($('.button').length, 0); + }); + + QUnit.test('copyOnClick adds button on click', function(assert) { + const $ = django.jQuery; + copyOnClick('.button'); + assert.equal($('.button').length, 1); + $('.button').click(); + assert.equal($('.button').length, 2); + }); + + +Please consult the ``QUnit`` documentation for information on the types of +`assertions supported by QUnit `_. + +Running tests +------------- + +The JavaScript tests may be run from a web browser or from the command line. + +Testing from a web browser +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To run the tests from a web browser, open up :source:`js_tests/tests.html` in your +browser. + +To measure code coverage when running the tests, you need to view that file +over HTTP. To view code coverage: + +* Execute ``python -m http.server`` from the root directory (not from inside + ``js_tests``). +* Open http://localhost:8000/js_tests/tests.html in your web browser. + +Testing from the command line +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To run the tests from the command line, you need to have `Node.js`_ installed. + +After installing ``Node.js``, install the JavaScript test dependencies by +running the following from the root of your Django checkout: + +.. console:: + + $ npm install + +Then run the tests with: + +.. console:: + + $ npm test + +.. _EditorConfig: https://editorconfig.org/ +.. _Java: https://www.java.com +.. _eslint: https://eslint.org/ +.. _node.js: https://nodejs.org/ +.. _qunit: https://qunitjs.com/ diff --git a/testbed/django__django/docs/internals/contributing/writing-code/submitting-patches.txt b/testbed/django__django/docs/internals/contributing/writing-code/submitting-patches.txt new file mode 100644 index 0000000000000000000000000000000000000000..be031f1f68c6e892a78ba43e40afe34cce108d7c --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/writing-code/submitting-patches.txt @@ -0,0 +1,338 @@ +================== +Submitting patches +================== + +We're always grateful for patches to Django's code. Indeed, bug reports +with associated patches will get fixed *far* more quickly than those +without patches. + +Typo fixes and trivial documentation changes +============================================ + +If you are fixing a really trivial issue, for example changing a word in the +documentation, the preferred way to provide the patch is using GitHub pull +requests without a Trac ticket. + +See the :doc:`working-with-git` for more details on how to use pull requests. + +"Claiming" tickets +================== + +In an open-source project with hundreds of contributors around the world, it's +important to manage communication efficiently so that work doesn't get +duplicated and contributors can be as effective as possible. + +Hence, our policy is for contributors to "claim" tickets in order to let other +developers know that a particular bug or feature is being worked on. + +If you have identified a contribution you want to make and you're capable of +fixing it (as measured by your coding ability, knowledge of Django internals +and time availability), claim it by following these steps: + +* `Login using your GitHub account`_ or `create an account`_ in our ticket + system. If you have an account but have forgotten your password, you can + reset it using the `password reset page`_. + +* If a ticket for this issue doesn't exist yet, create one in our + `ticket tracker`_. + +* If a ticket for this issue already exists, make sure nobody else has + claimed it. To do this, look at the "Owned by" section of the ticket. + If it's assigned to "nobody," then it's available to be claimed. + Otherwise, somebody else may be working on this ticket. Either find another + bug/feature to work on, or contact the developer working on the ticket to + offer your help. If a ticket has been assigned for weeks or months without + any activity, it's probably safe to reassign it to yourself. + +* Log into your account, if you haven't already, by clicking "GitHub Login" + or "DjangoProject Login" in the upper left of the ticket page. + +* Claim the ticket by clicking the "assign to myself" radio button under + "Action" near the bottom of the page, then click "Submit changes." + +.. note:: + The Django software foundation requests that anyone contributing more than + a trivial patch to Django sign and submit a `Contributor License + Agreement`_, this ensures that the Django Software Foundation has clear + license to all contributions allowing for a clear license for all users. + +.. _Login using your GitHub account: https://code.djangoproject.com/github/login +.. _Create an account: https://www.djangoproject.com/accounts/register/ +.. _password reset page: https://www.djangoproject.com/accounts/password/reset/ +.. _Contributor License Agreement: https://www.djangoproject.com/foundation/cla/ + +Ticket claimers' responsibility +------------------------------- + +Once you've claimed a ticket, you have a responsibility to work on that ticket +in a reasonably timely fashion. If you don't have time to work on it, either +unclaim it or don't claim it in the first place! + +If there's no sign of progress on a particular claimed ticket for a week or +two, another developer may ask you to relinquish the ticket claim so that it's +no longer monopolized and somebody else can claim it. + +If you've claimed a ticket and it's taking a long time (days or weeks) to code, +keep everybody updated by posting comments on the ticket. If you don't provide +regular updates, and you don't respond to a request for a progress report, +your claim on the ticket may be revoked. + +As always, more communication is better than less communication! + +Which tickets should be claimed? +-------------------------------- + +Going through the steps of claiming tickets is overkill in some cases. + +In the case of small changes, such as typos in the documentation or small bugs +that will only take a few minutes to fix, you don't need to jump through the +hoops of claiming tickets. Submit your patch directly and you're done! + +It is *always* acceptable, regardless whether someone has claimed it or not, to +submit patches to a ticket if you happen to have a patch ready. + +.. _patch-style: + +Patch style +=========== + +Make sure that any contribution you do fulfills at least the following +requirements: + +* The code required to fix a problem or add a feature is an essential part + of a patch, but it is not the only part. A good patch should also include a + :doc:`regression test ` to validate the behavior that has been + fixed and to prevent the problem from arising again. Also, if some tickets + are relevant to the code that you've written, mention the ticket numbers in + some comments in the test so that one can easily trace back the relevant + discussions after your patch gets committed, and the tickets get closed. + +* If the code associated with a patch adds a new feature, or modifies + behavior of an existing feature, the patch should also contain + documentation. + +When you think your work is ready to be reviewed, send :doc:`a GitHub pull +request `. Please review the patch yourself using our +:ref:`patch review checklist ` first. + +If you can't send a pull request for some reason, you can also use patches in +Trac. When using this style, follow these guidelines. + +* Submit patches in the format returned by the ``git diff`` command. + +* Attach patches to a ticket in the `ticket tracker`_, using the "attach + file" button. Please *don't* put the patch in the ticket description + or comment unless it's a single line patch. + +* Name the patch file with a ``.diff`` extension; this will let the ticket + tracker apply correct syntax highlighting, which is quite helpful. + +Regardless of the way you submit your work, follow these steps. + +* Make sure your code fulfills the requirements in our :ref:`patch review + checklist `. + +* Check the "Has patch" box on the ticket and make sure the "Needs + documentation", "Needs tests", and "Patch needs improvement" boxes aren't + checked. This makes the ticket appear in the "Patches needing review" queue + on the `Development dashboard`_. + +.. _ticket tracker: https://code.djangoproject.com/ +.. _Development dashboard: https://dashboard.djangoproject.com/ + +Non-trivial patches +=================== + +A "non-trivial" patch is one that is more than a small bug fix. It's a patch +that introduces Django functionality and makes some sort of design decision. + +If you provide a non-trivial patch, include evidence that alternatives have +been discussed on the `Django Forum`_ or |django-developers| list. + +If you're not sure whether your patch should be considered non-trivial, ask on +the ticket for opinions. + +.. _Django Forum: https://forum.djangoproject.com/ + +.. _deprecating-a-feature: + +Deprecating a feature +===================== + +There are a couple of reasons that code in Django might be deprecated: + +* If a feature has been improved or modified in a backwards-incompatible way, + the old feature or behavior will be deprecated. + +* Sometimes Django will include a backport of a Python library that's not + included in a version of Python that Django currently supports. When Django + no longer needs to support the older version of Python that doesn't include + the library, the library will be deprecated in Django. + +As the :ref:`deprecation policy` describes, +the first release of Django that deprecates a feature (``A.B``) should raise a +``RemovedInDjangoXXWarning`` (where XX is the Django version where the feature +will be removed) when the deprecated feature is invoked. Assuming we have good +test coverage, these warnings are converted to errors when :ref:`running the +test suite ` with warnings enabled: +``python -Wa runtests.py``. Thus, when adding a ``RemovedInDjangoXXWarning`` +you need to eliminate or silence any warnings generated when running the tests. + +The first step is to remove any use of the deprecated behavior by Django itself. +Next you can silence warnings in tests that actually test the deprecated +behavior by using the ``ignore_warnings`` decorator, either at the test or class +level: + +#) In a particular test:: + + from django.test import ignore_warnings + from django.utils.deprecation import RemovedInDjangoXXWarning + + + @ignore_warnings(category=RemovedInDjangoXXWarning) + def test_foo(self): + ... + +#) For an entire test case:: + + from django.test import ignore_warnings + from django.utils.deprecation import RemovedInDjangoXXWarning + + + @ignore_warnings(category=RemovedInDjangoXXWarning) + class MyDeprecatedTests(unittest.TestCase): + ... + +You should also add a test for the deprecation warning:: + + from django.utils.deprecation import RemovedInDjangoXXWarning + + + def test_foo_deprecation_warning(self): + msg = "Expected deprecation message" + with self.assertWarnsMessage(RemovedInDjangoXXWarning, msg): + # invoke deprecated behavior + ... + +It's important to include a ``RemovedInDjangoXXWarning`` comment above code +which has no warning reference, but will need to be changed or removed when the +deprecation ends. This could include hooks which have been added to keep the +previous behavior, or standalone items that are unnecessary or unused when the +deprecation ends. For example:: + + import warnings + from django.utils.deprecation import RemovedInDjangoXXWarning + + + # RemovedInDjangoXXWarning. + def old_private_helper(): + # Helper function that is only used in foo(). + pass + + + def foo(): + warnings.warn( + "foo() is deprecated.", + category=RemovedInDjangoXXWarning, + ) + old_private_helper() + ... + +Finally, there are a couple of updates to Django's documentation to make: + +#) If the existing feature is documented, mark it deprecated in documentation + using the ``.. deprecated:: A.B`` annotation. Include a short description + and a note about the upgrade path if applicable. + +#) Add a description of the deprecated behavior, and the upgrade path if + applicable, to the current release notes (``docs/releases/A.B.txt``) under + the "Features deprecated in A.B" heading. + +#) Add an entry in the deprecation timeline (``docs/internals/deprecation.txt``) + under the appropriate version describing what code will be removed. + +Once you have completed these steps, you are finished with the deprecation. +In each :term:`feature release `, all +``RemovedInDjangoXXWarning``\s matching the new version are removed. + +JavaScript patches +================== + +For information on JavaScript patches, see the :ref:`javascript-patches` +documentation. + +.. _patch-review-checklist: + +Patch review checklist +====================== + +Use this checklist to review a pull request. If you are reviewing a pull +request that is not your own and it passes all the criteria below, please set +the "Triage Stage" on the corresponding Trac ticket to "Ready for checkin". +If you've left comments for improvement on the pull request, please tick the +appropriate flags on the Trac ticket based on the results of your review: +"Patch needs improvement", "Needs documentation", and/or "Needs tests". As time +and interest permits, mergers do final reviews of "Ready for checkin" tickets +and will either commit the patch or bump it back to "Accepted" if further works +need to be done. If you're looking to become a merger, doing thorough reviews +of patches is a great way to earn trust. + +Looking for a patch to review? Check out the "Patches needing review" section +of the `Django Development Dashboard `_. +Looking to get your patch reviewed? Ensure the Trac flags on the ticket are +set so that the ticket appears in that queue. + +Documentation +------------- + +* Does the documentation build without any errors (``make html``, or + ``make.bat html`` on Windows, from the ``docs`` directory)? +* Does the documentation follow the writing style guidelines in + :doc:`/internals/contributing/writing-documentation`? +* Are there any :ref:`spelling errors `? + +Bugs +---- + +* Is there a proper regression test (the test should fail before the fix + is applied)? +* If it's a bug that :ref:`qualifies for a backport ` + to the stable version of Django, is there a release note in + ``docs/releases/A.B.C.txt``? Bug fixes that will be applied only to the main + branch don't need a release note. + +New Features +------------ + +* Are there tests to "exercise" all of the new code? +* Is there a release note in ``docs/releases/A.B.txt``? +* Is there documentation for the feature and is it :ref:`annotated + appropriately ` with + ``.. versionadded:: A.B`` or ``.. versionchanged:: A.B``? + +Deprecating a feature +--------------------- + +See the :ref:`deprecating-a-feature` guide. + +All code changes +---------------- + +* Does the :doc:`coding style + ` conform to our + guidelines? Are there any ``black``, ``blacken-docs``, ``flake8``, or + ``isort`` errors? You can install the :ref:`pre-commit + ` hooks to automatically catch these errors. +* If the change is backwards incompatible in any way, is there a note + in the release notes (``docs/releases/A.B.txt``)? +* Is Django's test suite passing? + +All tickets +----------- + +* Is the pull request a single squashed commit with a message that follows our + :ref:`commit message format `? +* Are you the patch author and a new contributor? Please add yourself to the + :source:`AUTHORS` file and submit a `Contributor License Agreement`_. + +.. _Contributor License Agreement: https://www.djangoproject.com/foundation/cla/ diff --git a/testbed/django__django/docs/internals/contributing/writing-code/unit-tests.txt b/testbed/django__django/docs/internals/contributing/writing-code/unit-tests.txt new file mode 100644 index 0000000000000000000000000000000000000000..bed9c9166552971ab36bbe0b7b5425f41e4ae547 --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/writing-code/unit-tests.txt @@ -0,0 +1,558 @@ +========== +Unit tests +========== + +Django comes with a test suite of its own, in the ``tests`` directory of the +code base. It's our policy to make sure all tests pass at all times. + +We appreciate any and all contributions to the test suite! + +The Django tests all use the testing infrastructure that ships with Django for +testing applications. See :doc:`/topics/testing/overview` for an explanation of +how to write new tests. + +.. _running-unit-tests: + +Running the unit tests +====================== + +Quickstart +---------- + +First, `fork Django on GitHub `__. + +Second, create and activate a virtual environment. If you're not familiar with +how to do that, read our :doc:`contributing tutorial `. + +Next, clone your fork, install some requirements, and run the tests: + +.. console:: + + $ git clone https://github.com/YourGitHubName/django.git django-repo + $ cd django-repo/tests + $ python -m pip install -e .. + $ python -m pip install -r requirements/py3.txt + $ ./runtests.py + +Installing the requirements will likely require some operating system packages +that your computer doesn't have installed. You can usually figure out which +package to install by doing a web search for the last line or so of the error +message. Try adding your operating system to the search query if needed. + +If you have trouble installing the requirements, you can skip that step. See +:ref:`running-unit-tests-dependencies` for details on installing the optional +test dependencies. If you don't have an optional dependency installed, the +tests that require it will be skipped. + +Running the tests requires a Django settings module that defines the databases +to use. To help you get started, Django provides and uses a sample settings +module that uses the SQLite database. See :ref:`running-unit-tests-settings` to +learn how to use a different settings module to run the tests with a different +database. + +Having problems? See :ref:`troubleshooting-unit-tests` for some common issues. + +Running tests using ``tox`` +--------------------------- + +`Tox `_ is a tool for running tests in different virtual +environments. Django includes a basic ``tox.ini`` that automates some checks +that our build server performs on pull requests. To run the unit tests and +other checks (such as :ref:`import sorting `, the +:ref:`documentation spelling checker `, and +:ref:`code formatting `), install and run the ``tox`` +command from any place in the Django source tree: + +.. console:: + + $ python -m pip install tox + $ tox + +By default, ``tox`` runs the test suite with the bundled test settings file for +SQLite, ``black``, ``blacken-docs``, ``flake8``, ``isort``, and the +documentation spelling checker. In addition to the system dependencies noted +elsewhere in this documentation, the command ``python3`` must be on your path +and linked to the appropriate version of Python. A list of default environments +can be seen as follows: + +.. console:: + + $ tox -l + py3 + black + blacken-docs + flake8>=3.7.0 + docs + isort>=5.1.0 + +Testing other Python versions and database backends +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In addition to the default environments, ``tox`` supports running unit tests +for other versions of Python and other database backends. Since Django's test +suite doesn't bundle a settings file for database backends other than SQLite, +however, you must :ref:`create and provide your own test settings +`. For example, to run the tests on Python 3.10 +using PostgreSQL: + +.. console:: + + $ tox -e py310-postgres -- --settings=my_postgres_settings + +This command sets up a Python 3.10 virtual environment, installs Django's +test suite dependencies (including those for PostgreSQL), and calls +``runtests.py`` with the supplied arguments (in this case, +``--settings=my_postgres_settings``). + +The remainder of this documentation shows commands for running tests without +``tox``, however, any option passed to ``runtests.py`` can also be passed to +``tox`` by prefixing the argument list with ``--``, as above. + +``Tox`` also respects the :envvar:`DJANGO_SETTINGS_MODULE` environment +variable, if set. For example, the following is equivalent to the command +above: + +.. code-block:: console + + $ DJANGO_SETTINGS_MODULE=my_postgres_settings tox -e py310-postgres + +Windows users should use: + +.. code-block:: doscon + + ...\> set DJANGO_SETTINGS_MODULE=my_postgres_settings + ...\> tox -e py310-postgres + +Running the JavaScript tests +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Django includes a set of :ref:`JavaScript unit tests ` for +functions in certain contrib apps. The JavaScript tests aren't run by default +using ``tox`` because they require ``Node.js`` to be installed and aren't +necessary for the majority of patches. To run the JavaScript tests using +``tox``: + +.. console:: + + $ tox -e javascript + +This command runs ``npm install`` to ensure test requirements are up to +date and then runs ``npm test``. + +Running tests using ``django-docker-box`` +----------------------------------------- + +`django-docker-box`_ allows you to run the Django's test suite across all +supported databases and python versions. See the `django-docker-box`_ project +page for installation and usage instructions. + +.. _django-docker-box: https://github.com/django/django-docker-box/ + +.. _running-unit-tests-settings: + +Using another ``settings`` module +--------------------------------- + +The included settings module (``tests/test_sqlite.py``) allows you to run the +test suite using SQLite. If you want to run the tests using a different +database, you'll need to define your own settings file. Some tests, such as +those for ``contrib.postgres``, are specific to a particular database backend +and will be skipped if run with a different backend. Some tests are skipped or +expected failures on a particular database backend (see +``DatabaseFeatures.django_test_skips`` and +``DatabaseFeatures.django_test_expected_failures`` on each backend). + +To run the tests with different settings, ensure that the module is on your +:envvar:`PYTHONPATH` and pass the module with ``--settings``. + +The :setting:`DATABASES` setting in any test settings module needs to define +two databases: + +* A ``default`` database. This database should use the backend that + you want to use for primary testing. + +* A database with the alias ``other``. The ``other`` database is used to test + that queries can be directed to different databases. This database should use + the same backend as the ``default``, and it must have a different name. + +If you're using a backend that isn't SQLite, you will need to provide other +details for each database: + +* The :setting:`USER` option needs to specify an existing user account + for the database. That user needs permission to execute ``CREATE DATABASE`` + so that the test database can be created. + +* The :setting:`PASSWORD` option needs to provide the password for + the :setting:`USER` that has been specified. + +Test databases get their names by prepending ``test_`` to the value of the +:setting:`NAME` settings for the databases defined in :setting:`DATABASES`. +These test databases are deleted when the tests are finished. + +You will also need to ensure that your database uses UTF-8 as the default +character set. If your database server doesn't use UTF-8 as a default charset, +you will need to include a value for :setting:`CHARSET ` in the +test settings dictionary for the applicable database. + +.. _runtests-specifying-labels: + +Running only some of the tests +------------------------------ + +Django's entire test suite takes a while to run, and running every single test +could be redundant if, say, you just added a test to Django that you want to +run quickly without running everything else. You can run a subset of the unit +tests by appending the names of the test modules to ``runtests.py`` on the +command line. + +For example, if you'd like to run tests only for generic relations and +internationalization, type: + +.. console:: + + $ ./runtests.py --settings=path.to.settings generic_relations i18n + +How do you find out the names of individual tests? Look in ``tests/`` — each +directory name there is the name of a test. + +If you want to run only a particular class of tests, you can specify a list of +paths to individual test classes. For example, to run the ``TranslationTests`` +of the ``i18n`` module, type: + +.. console:: + + $ ./runtests.py --settings=path.to.settings i18n.tests.TranslationTests + +Going beyond that, you can specify an individual test method like this: + +.. console:: + + $ ./runtests.py --settings=path.to.settings i18n.tests.TranslationTests.test_lazy_objects + +You can run tests starting at a specified top-level module with ``--start-at`` +option. For example: + +.. console:: + + $ ./runtests.py --start-at=wsgi + +You can also run tests starting after a specified top-level module with +``--start-after`` option. For example: + +.. console:: + + $ ./runtests.py --start-after=wsgi + +Note that the ``--reverse`` option doesn't impact on ``--start-at`` or +``--start-after`` options. Moreover these options cannot be used with test +labels. + +Running the Selenium tests +-------------------------- + +Some tests require Selenium and a web browser. To run these tests, you must +install the :pypi:`selenium` package and run the tests with the +``--selenium=`` option. For example, if you have Firefox and Google +Chrome installed: + +.. console:: + + $ ./runtests.py --selenium=firefox,chrome + +See the `selenium.webdriver`_ package for the list of available browsers. + +Specifying ``--selenium`` automatically sets ``--tags=selenium`` to run only +the tests that require selenium. + +Some browsers (e.g. Chrome or Firefox) support headless testing, which can be +faster and more stable. Add the ``--headless`` option to enable this mode. + +.. _selenium.webdriver: https://github.com/SeleniumHQ/selenium/tree/trunk/py/selenium/webdriver + +.. _running-unit-tests-dependencies: + +Running all the tests +--------------------- + +If you want to run the full suite of tests, you'll need to install a number of +dependencies: + +* :pypi:`aiosmtpd` +* :pypi:`argon2-cffi` 19.2.0+ +* :pypi:`asgiref` 3.7.0+ (required) +* :pypi:`bcrypt` +* :pypi:`colorama` +* :pypi:`docutils` +* :pypi:`geoip2` +* :pypi:`Jinja2` 2.11+ +* :pypi:`numpy` +* :pypi:`Pillow` 6.2.1+ +* :pypi:`PyYAML` +* :pypi:`pytz` (required) +* :pypi:`pywatchman` +* :pypi:`redis` 3.4+ +* :pypi:`setuptools` +* :pypi:`python-memcached`, plus a `supported Python binding + `_ +* `gettext `_ + (:ref:`gettext_on_windows`) +* :pypi:`selenium` 4.8.0+ +* :pypi:`sqlparse` 0.3.1+ (required) +* :pypi:`tblib` 1.5.0+ + +You can find these dependencies in `pip requirements files +`_ inside the +``tests/requirements`` directory of the Django source tree and install them +like so: + +.. console:: + + $ python -m pip install -r tests/requirements/py3.txt + +If you encounter an error during the installation, your system might be missing +a dependency for one or more of the Python packages. Consult the failing +package's documentation or search the web with the error message that you +encounter. + +You can also install the database adapter(s) of your choice using +``oracle.txt``, ``mysql.txt``, or ``postgres.txt``. + +If you want to test the memcached or Redis cache backends, you'll also need to +define a :setting:`CACHES` setting that points at your memcached or Redis +instance respectively. + +To run the GeoDjango tests, you will need to :doc:`set up a spatial database +and install the Geospatial libraries`. + +Each of these dependencies is optional. If you're missing any of them, the +associated tests will be skipped. + +To run some of the autoreload tests, you'll need to install the +`Watchman `_ service. + +Code coverage +------------- + +Contributors are encouraged to run coverage on the test suite to identify areas +that need additional tests. The coverage tool installation and use is described +in :ref:`testing code coverage`. + +To run coverage on the Django test suite using the standard test settings: + +.. console:: + + $ coverage run ./runtests.py --settings=test_sqlite + +After running coverage, combine all coverage statistics by running: + +.. console:: + + $ coverage combine + +After that generate the html report by running: + +.. console:: + + $ coverage html + +When running coverage for the Django tests, the included ``.coveragerc`` +settings file defines ``coverage_html`` as the output directory for the report +and also excludes several directories not relevant to the results +(test code or external code included in Django). + +.. _contrib-apps: + +Contrib apps +============ + +Tests for contrib apps can be found in the :source:`tests/` directory, typically +under ``_tests``. For example, tests for ``contrib.auth`` are located +in :source:`tests/auth_tests`. + +.. _troubleshooting-unit-tests: + +Troubleshooting +=============== + +Test suite hangs or shows failures on ``main`` branch +----------------------------------------------------- + +Ensure you have the latest point release of a :ref:`supported Python version +`, since there are often bugs in earlier versions +that may cause the test suite to fail or hang. + +On **macOS** (High Sierra and newer versions), you might see this message +logged, after which the tests hang: + +.. code-block:: pytb + + objc[42074]: +[__NSPlaceholderDate initialize] may have been in progress in + another thread when fork() was called. + +To avoid this set a ``OBJC_DISABLE_INITIALIZE_FORK_SAFETY`` environment +variable, for example: + +.. code-block:: shell + + $ OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES ./runtests.py + +Or add ``export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES`` to your shell's +startup file (e.g. ``~/.profile``). + +Many test failures with ``UnicodeEncodeError`` +---------------------------------------------- + +If the ``locales`` package is not installed, some tests will fail with a +``UnicodeEncodeError``. + +You can resolve this on Debian-based systems, for example, by running: + +.. code-block:: console + + $ apt-get install locales + $ dpkg-reconfigure locales + +You can resolve this for macOS systems by configuring your shell's locale: + +.. code-block:: console + + $ export LANG="en_US.UTF-8" + $ export LC_ALL="en_US.UTF-8" + +Run the ``locale`` command to confirm the change. Optionally, add those export +commands to your shell's startup file (e.g. ``~/.bashrc`` for Bash) to avoid +having to retype them. + +Tests that only fail in combination +----------------------------------- + +In case a test passes when run in isolation but fails within the whole suite, +we have some tools to help analyze the problem. + +The ``--bisect`` option of ``runtests.py`` will run the failing test while +halving the test set it is run together with on each iteration, often making +it possible to identify a small number of tests that may be related to the +failure. + +For example, suppose that the failing test that works on its own is +``ModelTest.test_eq``, then using: + +.. console:: + + $ ./runtests.py --bisect basic.tests.ModelTest.test_eq + +will try to determine a test that interferes with the given one. First, the +test is run with the first half of the test suite. If a failure occurs, the +first half of the test suite is split in two groups and each group is then run +with the specified test. If there is no failure with the first half of the test +suite, the second half of the test suite is run with the specified test and +split appropriately as described earlier. The process repeats until the set of +failing tests is minimized. + +The ``--pair`` option runs the given test alongside every other test from the +suite, letting you check if another test has side-effects that cause the +failure. So: + +.. console:: + + $ ./runtests.py --pair basic.tests.ModelTest.test_eq + +will pair ``test_eq`` with every test label. + +With both ``--bisect`` and ``--pair``, if you already suspect which cases +might be responsible for the failure, you may limit tests to be cross-analyzed +by :ref:`specifying further test labels ` after +the first one: + +.. console:: + + $ ./runtests.py --pair basic.tests.ModelTest.test_eq queries transactions + +You can also try running any set of tests in a random or reverse order using +the ``--shuffle`` and ``--reverse`` options. This can help verify that +executing tests in a different order does not cause any trouble: + +.. console:: + + $ ./runtests.py basic --shuffle + $ ./runtests.py basic --reverse + +Seeing the SQL queries run during a test +---------------------------------------- + +If you wish to examine the SQL being run in failing tests, you can turn on +:ref:`SQL logging ` using the ``--debug-sql`` option. If you +combine this with ``--verbosity=2``, all SQL queries will be output: + +.. console:: + + $ ./runtests.py basic --debug-sql + +Seeing the full traceback of a test failure +------------------------------------------- + +By default tests are run in parallel with one process per core. When the tests +are run in parallel, however, you'll only see a truncated traceback for any +test failures. You can adjust this behavior with the ``--parallel`` option: + +.. console:: + + $ ./runtests.py basic --parallel=1 + +You can also use the :envvar:`DJANGO_TEST_PROCESSES` environment variable for +this purpose. + +Tips for writing tests +====================== + +Isolating model registration +---------------------------- + +To avoid polluting the global :attr:`~django.apps.apps` registry and prevent +unnecessary table creation, models defined in a test method should be bound to +a temporary ``Apps`` instance. To do this, use the +:func:`~django.test.utils.isolate_apps` decorator:: + + from django.db import models + from django.test import SimpleTestCase + from django.test.utils import isolate_apps + + + class TestModelDefinition(SimpleTestCase): + @isolate_apps("app_label") + def test_model_definition(self): + class TestModel(models.Model): + pass + + ... + +.. admonition:: Setting ``app_label`` + + Models defined in a test method with no explicit + :attr:`~django.db.models.Options.app_label` are automatically assigned the + label of the app in which their test class is located. + + In order to make sure the models defined within the context of + :func:`~django.test.utils.isolate_apps` instances are correctly + installed, you should pass the set of targeted ``app_label`` as arguments: + + .. code-block:: python + :caption: ``tests/app_label/tests.py`` + + from django.db import models + from django.test import SimpleTestCase + from django.test.utils import isolate_apps + + + class TestModelDefinition(SimpleTestCase): + @isolate_apps("app_label", "other_app_label") + def test_model_definition(self): + # This model automatically receives app_label='app_label' + class TestModel(models.Model): + pass + + class OtherAppModel(models.Model): + class Meta: + app_label = "other_app_label" + + ... diff --git a/testbed/django__django/docs/internals/contributing/writing-code/working-with-git.txt b/testbed/django__django/docs/internals/contributing/writing-code/working-with-git.txt new file mode 100644 index 0000000000000000000000000000000000000000..579543f8767f403cbd6e81e46c876c335d48ed85 --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/writing-code/working-with-git.txt @@ -0,0 +1,311 @@ +=========================== +Working with Git and GitHub +=========================== + +This section explains how the community can contribute code to Django via pull +requests. If you're interested in how :ref:`mergers ` handle +them, see :doc:`../committing-code`. + +Below, we are going to show how to create a GitHub pull request containing the +changes for Trac ticket #xxxxx. By creating a fully-ready pull request, you +will make the reviewer's job easier, meaning that your work is more likely to +be merged into Django. + +You could also upload a traditional patch to Trac, but it's less practical for +reviews. + +Installing Git +============== + +Django uses `Git`_ for its source control. You can `download +`_ Git, but it's often easier to install with +your operating system's package manager. + +Django's `Git repository`_ is hosted on `GitHub`_, and it is recommended +that you also work using GitHub. + +After installing Git, the first thing you should do is set up your name and +email: + +.. code-block:: shell + + $ git config --global user.name "Your Real Name" + $ git config --global user.email "you@email.com" + +Note that ``user.name`` should be your real name, not your GitHub nick. GitHub +should know the email you use in the ``user.email`` field, as this will be +used to associate your commits with your GitHub account. + +.. _Git: https://git-scm.com/ +.. _Git repository: https://github.com/django/django/ +.. _GitHub: https://github.com/ + +Setting up local repository +=========================== + +When you have created your GitHub account, with the nick "GitHub_nick", and +`forked Django's repository `__, +create a local copy of your fork: + +.. code-block:: shell + + git clone https://github.com/GitHub_nick/django.git + +This will create a new directory "django", containing a clone of your GitHub +repository. The rest of the git commands on this page need to be run within the +cloned directory, so switch to it now: + +.. code-block:: shell + + cd django + +Your GitHub repository will be called "origin" in Git. + +You should also set up ``django/django`` as an "upstream" remote (that is, tell +git that the reference Django repository was the source of your fork of it): + +.. code-block:: shell + + git remote add upstream https://github.com/django/django.git + git fetch upstream + +You can add other remotes similarly, for example: + +.. code-block:: shell + + git remote add akaariai https://github.com/akaariai/django.git + +Working on a ticket +=================== + +When working on a ticket, create a new branch for the work, and base that work +on ``upstream/main``: + +.. code-block:: shell + + git checkout -b ticket_xxxxx upstream/main + +The -b flag creates a new branch for you locally. Don't hesitate to create new +branches even for the smallest things - that's what they are there for. + +If instead you were working for a fix on the 1.4 branch, you would do: + +.. code-block:: shell + + git checkout -b ticket_xxxxx_1_4 upstream/stable/1.4.x + +Assume the work is carried on the ticket_xxxxx branch. Make some changes and +commit them: + +.. code-block:: shell + + git commit + +When writing the commit message, follow the :ref:`commit message +guidelines ` to ease the work of the merger. If you're +uncomfortable with English, try at least to describe precisely what the commit +does. + +If you need to do additional work on your branch, commit as often as +necessary: + +.. code-block:: shell + + git commit -m 'Added two more tests for edge cases' + +Publishing work +--------------- + +You can publish your work on GitHub by running: + +.. code-block:: shell + + git push origin ticket_xxxxx + +When you go to your GitHub page, you will notice a new branch has been created. + +If you are working on a Trac ticket, you should mention in the ticket that +your work is available from branch ticket_xxxxx of your GitHub repo. Include a +link to your branch. + +Note that the above branch is called a "topic branch" in Git parlance. You are +free to rewrite the history of this branch, by using ``git rebase`` for +example. Other people shouldn't base their work on such a branch, because +their clone would become corrupt when you edit commits. + +There are also "public branches". These are branches other people are supposed +to fork, so the history of these branches should never change. Good examples +of public branches are the ``main`` and ``stable/A.B.x`` branches in the +``django/django`` repository. + +When you think your work is ready to be pulled into Django, you should create +a pull request at GitHub. A good pull request means: + +* commits with one logical change in each, following the + :doc:`coding style `, + +* well-formed messages for each commit: a summary line and then paragraphs + wrapped at 72 characters thereafter -- see the :ref:`committing guidelines + ` for more details, + +* documentation and tests, if needed -- actually tests are always needed, + except for documentation changes. + +The test suite must pass and the documentation must build without warnings. + +Once you have created your pull request, you should add a comment in the +related Trac ticket explaining what you've done. In particular, you should note +the environment in which you ran the tests, for instance: "all tests pass +under SQLite and MySQL". + +Pull requests at GitHub have only two states: open and closed. The merger who +will deal with your pull request has only two options: merge it or close it. +For this reason, it isn't useful to make a pull request until the code is ready +for merging -- or sufficiently close that a merger will finish it themselves. + +Rebasing branches +----------------- + +In the example above, you created two commits, the "Fixed ticket_xxxxx" commit +and "Added two more tests" commit. + +We do not want to have the entire history of your working process in your +repository. Your commit "Added two more tests" would be unhelpful noise. +Instead, we would rather only have one commit containing all your work. + +To rework the history of your branch you can squash the commits into one by +using interactive rebase: + +.. code-block:: shell + + git rebase -i HEAD~2 + +The HEAD~2 above is shorthand for two latest commits. The above command +will open an editor showing the two commits, prefixed with the word "pick". + +Change "pick" on the second line to "squash" instead. This will keep the +first commit, and squash the second commit into the first one. Save and quit +the editor. A second editor window should open, so you can reword the +commit message for the commit now that it includes both your steps. + +You can also use the "edit" option in rebase. This way you can change a single +commit, for example to fix a typo in a docstring: + +.. code-block:: shell + + git rebase -i HEAD~3 + # Choose edit, pick, pick for the commits + # Now you are able to rework the commit (use git add normally to add changes) + # When finished, commit work with "--amend" and continue + git commit --amend + # Reword the commit message if needed + git rebase --continue + # The second and third commits should be applied. + +If your topic branch is already published at GitHub, for example if you're +making minor changes to take into account a review, you will need to force-push +the changes: + +.. code-block:: shell + + git push -f origin ticket_xxxxx + +Note that this will rewrite history of ticket_xxxxx - if you check the commit +hashes before and after the operation at GitHub you will notice that the commit +hashes do not match anymore. This is acceptable, as the branch is a topic +branch, and nobody should be basing their work on it. + +After upstream has changed +-------------------------- + +When upstream (``django/django``) has changed, you should rebase your work. To +do this, use: + +.. code-block:: shell + + git fetch upstream + git rebase upstream/main + +The work is automatically rebased using the branch you forked on, in the +example case using ``upstream/main``. + +The rebase command removes all your local commits temporarily, applies the +upstream commits, and then applies your local commits again on the work. + +If there are merge conflicts, you will need to resolve them and then use ``git +rebase --continue``. At any point you can use ``git rebase --abort`` to return +to the original state. + +Note that you want to *rebase* on upstream, not *merge* the upstream. + +The reason for this is that by rebasing, your commits will always be *on +top of* the upstream's work, not *mixed in with* the changes in the upstream. +This way your branch will contain only commits related to its topic, which +makes squashing easier. + +After review +------------ + +It is unusual to get any non-trivial amount of code into core without changes +requested by reviewers. In this case, it is often a good idea to add the +changes as one incremental commit to your work. This allows the reviewer to +easily check what changes you have done. + +In this case, do the changes required by the reviewer. Commit as often as +necessary. Before publishing the changes, rebase your work. If you added two +commits, you would run: + +.. code-block:: shell + + git rebase -i HEAD~2 + +Squash the second commit into the first. Write a commit message along the lines +of: + +.. code-block:: text + + Made changes asked in review by + + - Fixed whitespace errors in foobar + - Reworded the docstring of bar() + +Finally, push your work back to your GitHub repository. Since you didn't touch +the public commits during the rebase, you should not need to force-push: + +.. code-block:: shell + + git push origin ticket_xxxxx + +Your pull request should now contain the new commit too. + +Note that the merger is likely to squash the review commit into the previous +commit when committing the code. + +Working on a patch +================== + +One of the ways that developers can contribute to Django is by reviewing +patches. Those patches will typically exist as pull requests on GitHub and +can be easily integrated into your local repository: + +.. code-block:: shell + + git checkout -b pull_xxxxx upstream/main + curl -L https://github.com/django/django/pull/xxxxx.patch | git am + +This will create a new branch and then apply the changes from the pull request +to it. At this point you can run the tests or do anything else you need to +do to investigate the quality of the patch. + +For more detail on working with pull requests see the +:ref:`guidelines for mergers `. + +Summary +======= + +* Work on GitHub if you can. +* Announce your work on the Trac ticket by linking to your GitHub branch. +* When you have something ready, make a pull request. +* Make your pull requests as good as you can. +* When doing fixes to your work, use ``git rebase -i`` to squash the commits. +* When upstream has changed, do ``git fetch upstream; git rebase``. diff --git a/testbed/django__django/docs/internals/contributing/writing-documentation.txt b/testbed/django__django/docs/internals/contributing/writing-documentation.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa3cd749f9a581e369122154956e9bdf824a0e0f --- /dev/null +++ b/testbed/django__django/docs/internals/contributing/writing-documentation.txt @@ -0,0 +1,593 @@ +===================== +Writing documentation +===================== + +We place high importance on the consistency and readability of documentation. +After all, Django was created in a journalism environment! So we treat our +documentation like we treat our code: we aim to improve it as often as +possible. + +Documentation changes generally come in two forms: + +* General improvements: typo corrections, error fixes and better + explanations through clearer writing and more examples. + +* New features: documentation of features that have been added to the + framework since the last release. + +This section explains how writers can craft their documentation changes +in the most useful and least error-prone ways. + +Getting the raw documentation +============================= + +Though Django's documentation is intended to be read as HTML at +https://docs.djangoproject.com/, we edit it as a collection of text files for +maximum flexibility. These files live in the top-level :source:`docs/` directory of a +Django release. + +If you'd like to start contributing to our docs, get the development version of +Django from the source code repository +(see :ref:`installing-development-version`). The development version has the +latest-and-greatest documentation, just as it has the latest-and-greatest code. +We also backport documentation fixes and improvements, at the discretion of the +merger, to the last release branch. That's because it's highly advantageous to +have the docs for the last release be up-to-date and correct (see +:ref:`differences-between-doc-versions`). + +Getting started with Sphinx +=========================== + +Django's documentation uses the Sphinx__ documentation system, which in turn +is based on docutils__. The basic idea is that lightly-formatted plain-text +documentation is transformed into HTML, PDF, and any other output format. + +__ https://www.sphinx-doc.org/ +__ https://docutils.sourceforge.io/ + +To build the documentation locally, install Sphinx: + +.. console:: + + $ python -m pip install Sphinx + +Then from the ``docs`` directory, build the HTML: + +.. console:: + + $ make html + +To get started contributing, you'll want to read the :ref:`reStructuredText +reference `. + +Your locally-built documentation will be accessible at +``docs/_build/html/index.html`` and it can be viewed in any web browser, though +it will be themed differently than the documentation at +`docs.djangoproject.com `_. This is OK! If +your changes look good on your local machine, they'll look good on the website. + +How the documentation is organized +================================== + +The documentation is organized into several categories: + +* :doc:`Tutorials ` take the reader by the hand through a series + of steps to create something. + + The important thing in a tutorial is to help the reader achieve something + useful, preferably as early as possible, in order to give them confidence. + + Explain the nature of the problem we're solving, so that the reader + understands what we're trying to achieve. Don't feel that you need to begin + with explanations of how things work - what matters is what the reader does, + not what you explain. It can be helpful to refer back to what you've done and + explain afterward. + +* :doc:`Topic guides ` aim to explain a concept or subject at a + fairly high level. + + Link to reference material rather than repeat it. Use examples and don't be + reluctant to explain things that seem very basic to you - it might be the + explanation someone else needs. + + Providing background context helps a newcomer connect the topic to things + that they already know. + +* :doc:`Reference guides ` contain technical references for APIs. + They describe the functioning of Django's internal machinery and instruct in + its use. + + Keep reference material tightly focused on the subject. Assume that the + reader already understands the basic concepts involved but needs to know or + be reminded of how Django does it. + + Reference guides aren't the place for general explanation. If you find + yourself explaining basic concepts, you may want to move that material to a + topic guide. + +* :doc:`How-to guides ` are recipes that take the reader through + steps in key subjects. + + What matters most in a how-to guide is what a user wants to achieve. + A how-to should always be result-oriented rather than focused on internal + details of how Django implements whatever is being discussed. + + These guides are more advanced than tutorials and assume some knowledge about + how Django works. Assume that the reader has followed the tutorials and don't + hesitate to refer the reader back to the appropriate tutorial rather than + repeat the same material. + +Writing style +============= + +When using pronouns in reference to a hypothetical person, such as "a user with +a session cookie", gender-neutral pronouns (they/their/them) should be used. +Instead of: + +* he or she... use they. +* him or her... use them. +* his or her... use their. +* his or hers... use theirs. +* himself or herself... use themselves. + +Try to avoid using words that minimize the difficulty involved in a task or +operation, such as "easily", "simply", "just", "merely", "straightforward", and +so on. People's experience may not match your expectations, and they may become +frustrated when they do not find a step as "straightforward" or "simple" as it +is implied to be. + +Commonly used terms +=================== + +Here are some style guidelines on commonly used terms throughout the +documentation: + +* **Django** -- when referring to the framework, capitalize Django. It is + lowercase only in Python code and in the djangoproject.com logo. + +* **email** -- no hyphen. + +* **HTTP** -- the expected pronunciation is "Aitch Tee Tee Pee" and therefore + should be preceded by "an" and not "a". + +* **MySQL**, **PostgreSQL**, **SQLite** + +* **SQL** -- when referring to SQL, the expected pronunciation should be + "Ess Queue Ell" and not "sequel". Thus in a phrase like "Returns an + SQL expression", "SQL" should be preceded by "an" and not "a". + +* **Python** -- when referring to the language, capitalize Python. + +* **realize**, **customize**, **initialize**, etc. -- use the American + "ize" suffix, not "ise." + +* **subclass** -- it's a single word without a hyphen, both as a verb + ("subclass that model") and as a noun ("create a subclass"). + +* **the web**, **web framework** -- it's not capitalized. + +* **website** -- use one word, without capitalization. + +Django-specific terminology +=========================== + +* **model** -- it's not capitalized. + +* **template** -- it's not capitalized. + +* **URLconf** -- use three capitalized letters, with no space before + "conf." + +* **view** -- it's not capitalized. + +Guidelines for reStructuredText files +===================================== + +These guidelines regulate the format of our reST (reStructuredText) +documentation: + +* In section titles, capitalize only initial words and proper nouns. + +* Wrap the documentation at 80 characters wide, unless a code example + is significantly less readable when split over two lines, or for another + good reason. + +* The main thing to keep in mind as you write and edit docs is that the + more semantic markup you can add the better. So: + + .. code-block:: rst + + Add ``django.contrib.auth`` to your ``INSTALLED_APPS``... + + Isn't nearly as helpful as: + + .. code-block:: rst + + Add :mod:`django.contrib.auth` to your :setting:`INSTALLED_APPS`... + + This is because Sphinx will generate proper links for the latter, which + greatly helps readers. + + You can prefix the target with a ``~`` (that's a tilde) to get only the + "last bit" of that path. So ``:mod:`~django.contrib.auth``` will + display a link with the title "auth". + +* All Python code blocks should be formatted using the :pypi:`blacken-docs` + auto-formatter. This will be run by ``pre-commit`` if that is configured. + +* Use :mod:`~sphinx.ext.intersphinx` to reference Python's and Sphinx' + documentation. + +* Add ``.. code-block:: `` to literal blocks so that they get + highlighted. Prefer relying on automatic highlighting using ``::`` + (two colons). This has the benefit that if the code contains some invalid + syntax, it won't be highlighted. Adding ``.. code-block:: python``, for + example, will force highlighting despite invalid syntax. + +* To improve readability, use ``.. admonition:: Descriptive title`` rather than + ``.. note::``. Use these boxes sparingly. + +* Use these heading styles: + + .. code-block:: rst + + === + One + === + + Two + === + + Three + ----- + + Four + ~~~~ + + Five + ^^^^ + +* Use :rst:role:`:rfc:` to reference RFC and try to link to the relevant + section if possible. For example, use ``:rfc:`2324#section-2.3.2``` or + ``:rfc:`Custom link text <2324#section-2.3.2>```. + +* Use :rst:role:`:pep:` to reference a Python Enhancement Proposal (PEP) + and try to link to the relevant section if possible. For example, use + ``:pep:`20#easter-egg``` or ``:pep:`Easter Egg <20#easter-egg>```. + +* Use :rst:role:`:mimetype:` to refer to a MIME Type unless the value + is quoted for a code example. + +* Use :rst:role:`:envvar:` to refer to an environment variable. You may + also need to define a reference to the documentation for that environment + variable using :rst:dir:`.. envvar:: `. + +.. versionchanged:: 4.2 + + All Python code blocks in the Django documentation were reformatted with + :pypi:`blacken-docs`. + +Django-specific markup +====================== + +Besides :ref:`Sphinx's built-in markup `, Django's docs +define some extra description units: + +* Settings: + + .. code-block:: rst + + .. setting:: INSTALLED_APPS + + To link to a setting, use ``:setting:`INSTALLED_APPS```. + +* Template tags: + + .. code-block:: rst + + .. templatetag:: regroup + + To link, use ``:ttag:`regroup```. + +* Template filters: + + .. code-block:: rst + + .. templatefilter:: linebreaksbr + + To link, use ``:tfilter:`linebreaksbr```. + +* Field lookups (i.e. ``Foo.objects.filter(bar__exact=whatever)``): + + .. code-block:: rst + + .. fieldlookup:: exact + + To link, use ``:lookup:`exact```. + +* ``django-admin`` commands: + + .. code-block:: rst + + .. django-admin:: migrate + + To link, use ``:djadmin:`migrate```. + +* ``django-admin`` command-line options: + + .. code-block:: rst + + .. django-admin-option:: --traceback + + To link, use ``:option:`command_name --traceback``` (or omit ``command_name`` + for the options shared by all commands like ``--verbosity``). + +* Links to Trac tickets (typically reserved for patch release notes): + + .. code-block:: rst + + :ticket:`12345` + +Django's documentation uses a custom ``console`` directive for documenting +command-line examples involving ``django-admin``, ``manage.py``, ``python``, +etc.). In the HTML documentation, it renders a two-tab UI, with one tab showing +a Unix-style command prompt and a second tab showing a Windows prompt. + +For example, you can replace this fragment: + +.. code-block:: rst + + use this command: + + .. code-block:: console + + $ python manage.py shell + +with this one: + +.. code-block:: rst + + use this command: + + .. console:: + + $ python manage.py shell + +Notice two things: + +* You usually will replace occurrences of the ``.. code-block:: console`` + directive. +* You don't need to change the actual content of the code example. You still + write it assuming a Unix-y environment (i.e. a ``'$'`` prompt symbol, + ``'/'`` as filesystem path components separator, etc.) + +The example above will render a code example block with two tabs. The first +one will show: + +.. code-block:: console + + $ python manage.py shell + +(No changes from what ``.. code-block:: console`` would have rendered). + +The second one will show: + +.. code-block:: doscon + + ...\> py manage.py shell + +.. _documenting-new-features: + +Documenting new features +======================== + +Our policy for new features is: + + All documentation of new features should be written in a way that + clearly designates the features that are only available in the Django + development version. Assume documentation readers are using the latest + release, not the development version. + +Our preferred way for marking new features is by prefacing the features' +documentation with: "``.. versionadded:: X.Y``", followed by a mandatory +blank line and an optional description (indented). + +General improvements or other changes to the APIs that should be emphasized +should use the "``.. versionchanged:: X.Y``" directive (with the same format +as the ``versionadded`` mentioned above. + +These ``versionadded`` and ``versionchanged`` blocks should be "self-contained." +In other words, since we only keep these annotations around for two releases, +it's nice to be able to remove the annotation and its contents without having +to reflow, reindent, or edit the surrounding text. For example, instead of +putting the entire description of a new or changed feature in a block, do +something like this: + +.. code-block:: rst + + .. class:: Author(first_name, last_name, middle_name=None) + + A person who writes books. + + ``first_name`` is ... + + ... + + ``middle_name`` is ... + + .. versionchanged:: A.B + + The ``middle_name`` argument was added. + +Put the changed annotation notes at the bottom of a section, not the top. + +Also, avoid referring to a specific version of Django outside a +``versionadded`` or ``versionchanged`` block. Even inside a block, it's often +redundant to do so as these annotations render as "New in Django A.B:" and +"Changed in Django A.B", respectively. + +If a function, attribute, etc. is added, it's also okay to use a +``versionadded`` annotation like this: + +.. code-block:: rst + + .. attribute:: Author.middle_name + + .. versionadded:: A.B + + An author's middle name. + +We can remove the ``.. versionadded:: A.B`` annotation without any indentation +changes when the time comes. + +Minimizing images +================= + +Optimize image compression where possible. For PNG files, use OptiPNG and +AdvanceCOMP's ``advpng``: + +.. code-block:: console + + $ cd docs + $ optipng -o7 -zm1-9 -i0 -strip all `find . -type f -not -path "./_build/*" -name "*.png"` + $ advpng -z4 `find . -type f -not -path "./_build/*" -name "*.png"` + +This is based on OptiPNG version 0.7.5. Older versions may complain about the +``-strip all`` option being lossy. + +An example +========== + +For a quick example of how it all fits together, consider this hypothetical +example: + +* First, the ``ref/settings.txt`` document could have an overall layout + like this: + + .. code-block:: rst + + ======== + Settings + ======== + + ... + + .. _available-settings: + + Available settings + ================== + + ... + + .. _deprecated-settings: + + Deprecated settings + =================== + + ... + +* Next, the ``topics/settings.txt`` document could contain something like + this: + + .. code-block:: rst + + You can access a :ref:`listing of all available settings + `. For a list of deprecated settings see + :ref:`deprecated-settings`. + + You can find both in the :doc:`settings reference document + `. + + We use the Sphinx :rst:role:`doc` cross-reference element when we want to + link to another document as a whole and the :rst:role:`ref` element when + we want to link to an arbitrary location in a document. + +* Next, notice how the settings are annotated: + + .. code-block:: rst + + .. setting:: ADMINS + + ADMINS + ====== + + Default: ``[]`` (Empty list) + + A list of all the people who get code error notifications. When + ``DEBUG=False`` and a view raises an exception, Django will email these people + with the full exception information. Each member of the list should be a tuple + of (Full name, email address). Example:: + + [("John", "john@example.com"), ("Mary", "mary@example.com")] + + Note that Django will email *all* of these people whenever an error happens. + See :doc:`/howto/error-reporting` for more information. + + This marks up the following header as the "canonical" target for the + setting ``ADMINS``. This means any time I talk about ``ADMINS``, + I can reference it using ``:setting:`ADMINS```. + +That's basically how everything fits together. + +.. _documentation-spelling-check: + +Spelling check +============== + +Before you commit your docs, it's a good idea to run the spelling checker. +You'll need to install :pypi:`sphinxcontrib-spelling` first. Then from the +``docs`` directory, run ``make spelling``. Wrong words (if any) along with the +file and line number where they occur will be saved to +``_build/spelling/output.txt``. + +If you encounter false-positives (error output that actually is correct), do +one of the following: + +* Surround inline code or brand/technology names with grave accents (`). +* Find synonyms that the spell checker recognizes. +* If, and only if, you are sure the word you are using is correct - add it + to ``docs/spelling_wordlist`` (please keep the list in alphabetical order). + +.. _documentation-link-check: + +Link check +========== + +Links in documentation can become broken or changed such that they are no +longer the canonical link. Sphinx provides a builder that can check whether the +links in the documentation are working. From the ``docs`` directory, run ``make +linkcheck``. Output is printed to the terminal, but can also be found in +``_build/linkcheck/output.txt`` and ``_build/linkcheck/output.json``. + +Entries that have a status of "working" are fine, those that are "unchecked" or +"ignored" have been skipped because they either cannot be checked or have +matched ignore rules in the configuration. + +Entries that have a status of "broken" need to be fixed. Those that have a +status of "redirected" may need to be updated to point to the canonical +location, e.g. the scheme has changed ``http://`` → ``https://``. In certain +cases, we do not want to update a "redirected" link, e.g. a rewrite to always +point to the latest or stable version of the documentation, e.g. ``/en/stable/`` → +``/en/3.2/``. + +Translating documentation +========================= + +See :ref:`Localizing the Django documentation ` if +you'd like to help translate the documentation into another language. + +.. _django-admin-manpage: + +``django-admin`` man page +========================= + +Sphinx can generate a manual page for the +:doc:`django-admin ` command. This is configured in +``docs/conf.py``. Unlike other documentation output, this man page should be +included in the Django repository and the releases as +``docs/man/django-admin.1``. There isn't a need to update this file when +updating the documentation, as it's updated once as part of the release process. + +To generate an updated version of the man page, run ``make man`` in the +``docs`` directory. The new man page will be written in +``docs/_build/man/django-admin.1``. diff --git a/testbed/django__django/docs/internals/deprecation.txt b/testbed/django__django/docs/internals/deprecation.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa2a1c0a0ceaae99d8c30036a6f0272ccb22b7c2 --- /dev/null +++ b/testbed/django__django/docs/internals/deprecation.txt @@ -0,0 +1,1347 @@ +=========================== +Django Deprecation Timeline +=========================== + +This document outlines when various pieces of Django will be removed or altered +in a backward incompatible way, following their deprecation, as per the +:ref:`deprecation policy `. More details +about each item can often be found in the release notes of two versions prior. + +.. _deprecation-removed-in-6.0: + +6.0 +--- + +See the :ref:`Django 5.0 release notes ` for more +details on these changes. + +* The ``DjangoDivFormRenderer`` and ``Jinja2DivFormRenderer`` transitional form + renderers will be removed. + +* Support for passing positional arguments to ``BaseConstraint`` will be + removed. + +* ``request`` will be required in the signature of + ``ModelAdmin.lookup_allowed()`` subclasses. + +* The ``django.db.models.sql.datastructures.Join`` will no longer fallback to + ``get_joining_columns()``. + +* The ``get_joining_columns()`` method of ``ForeignObject`` and + ``ForeignObjectRel`` will be removed. + +* The ``ForeignObject.get_reverse_joining_columns()`` method will be removed. + +* The default scheme for ``forms.URLField`` will change from ``"http"`` to + ``"https"``. + +* Support for calling ``format_html()`` without passing args or kwargs will be + removed. + +.. _deprecation-removed-in-5.1: + +5.1 +--- + +See the :ref:`Django 4.2 release notes ` for more +details on these changes. + +* The ``BaseUserManager.make_random_password()`` method will be removed. + +* The model's ``Meta.index_together`` option will be removed. + +* The ``length_is`` template filter will be removed. + +* The ``django.contrib.auth.hashers.SHA1PasswordHasher``, + ``django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher``, and + ``django.contrib.auth.hashers.UnsaltedMD5PasswordHasher`` will be removed. + +* The model ``django.contrib.postgres.fields.CICharField``, + ``django.contrib.postgres.fields.CIEmailField``, and + ``django.contrib.postgres.fields.CITextField`` will be removed. Stub fields + will remain for compatibility with historical migrations. + +* The ``django.contrib.postgres.fields.CIText`` mixin will be removed. + +* The ``map_width`` and ``map_height`` attributes of ``BaseGeometryWidget`` + will be removed. + +* The ``SimpleTestCase.assertFormsetError()`` method will be removed. + +* The ``TransactionTestCase.assertQuerysetEqual()`` method will be removed. + +* Support for passing encoded JSON string literals to ``JSONField`` and + associated lookups and expressions will be removed. + +* Support for passing positional arguments to ``Signer`` and + ``TimestampSigner`` will be removed. + +* The ``DEFAULT_FILE_STORAGE`` and ``STATICFILES_STORAGE`` settings will be + removed. + +* The ``django.core.files.storage.get_storage_class()`` function will be + removed. + +.. _deprecation-removed-in-5.0: + +5.0 +--- + +See the :ref:`Django 4.0 release notes ` for more +details on these changes. + +* The ``SERIALIZE`` test setting will be removed. + +* The undocumented ``django.utils.baseconv`` module will be removed. + +* The undocumented ``django.utils.datetime_safe`` module will be removed. + +* The default value of the ``USE_TZ`` setting will change from ``False`` to + ``True``. + +* The default sitemap protocol for sitemaps built outside the context of a + request will change from ``'http'`` to ``'https'``. + +* The ``extra_tests`` argument for ``DiscoverRunner.build_suite()`` and + ``DiscoverRunner.run_tests()`` will be removed. + +* The ``django.contrib.postgres.aggregates.ArrayAgg``, ``JSONBAgg``, and + ``StringAgg`` aggregates will return ``None`` when there are no rows instead + of ``[]``, ``[]``, and ``''`` respectively. + +* The ``USE_L10N`` setting will be removed. + +* The ``USE_DEPRECATED_PYTZ`` transitional setting will be removed. + +* Support for ``pytz`` timezones will be removed. + +* The ``is_dst`` argument will be removed from: + + * ``QuerySet.datetimes()`` + * ``django.utils.timezone.make_aware()`` + * ``django.db.models.functions.Trunc()`` + * ``django.db.models.functions.TruncSecond()`` + * ``django.db.models.functions.TruncMinute()`` + * ``django.db.models.functions.TruncHour()`` + * ``django.db.models.functions.TruncDay()`` + * ``django.db.models.functions.TruncWeek()`` + * ``django.db.models.functions.TruncMonth()`` + * ``django.db.models.functions.TruncQuarter()`` + * ``django.db.models.functions.TruncYear()`` + +* The ``django.contrib.gis.admin.GeoModelAdmin`` and ``OSMGeoAdmin`` classes + will be removed. + +* The undocumented ``BaseForm._html_output()`` method will be removed. + +* The ability to return a ``str``, rather than a ``SafeString``, when rendering + an ``ErrorDict`` and ``ErrorList`` will be removed. + +See the :ref:`Django 4.1 release notes ` for more +details on these changes. + +* The ``SitemapIndexItem.__str__()`` method will be removed. + +* The ``CSRF_COOKIE_MASKED`` transitional setting will be removed. + +* The ``name`` argument of ``django.utils.functional.cached_property()`` will + be removed. + +* The ``opclasses`` argument of + ``django.contrib.postgres.constraints.ExclusionConstraint`` will be removed. + +* The undocumented ability to pass ``errors=None`` to + ``SimpleTestCase.assertFormError()`` and ``assertFormsetError()`` will be + removed. + +* ``django.contrib.sessions.serializers.PickleSerializer`` will be removed. + +* The usage of ``QuerySet.iterator()`` on a queryset that prefetches related + objects without providing the ``chunk_size`` argument will no longer be + allowed. + +* Passing unsaved model instances to related filters will no longer be allowed. + +* ``created=True`` will be required in the signature of + ``RemoteUserBackend.configure_user()`` subclasses. + +* Support for logging out via ``GET`` requests in the + ``django.contrib.auth.views.LogoutView`` and + ``django.contrib.auth.views.logout_then_login()`` will be removed. + +* The ``django.utils.timezone.utc`` alias to ``datetime.timezone.utc`` will be + removed. + +* Passing a response object and a form/formset name to + ``SimpleTestCase.assertFormError()`` and ``assertFormsetError()`` will no + longer be allowed. + +* The ``django.contrib.gis.admin.OpenLayersWidget`` will be removed. + +* The ``django.contrib.auth.hashers.CryptPasswordHasher`` will be removed. + +* The ``"django/forms/default.html"`` and + ``"django/forms/formsets/default.html"`` templates will be removed. + +* The ability to pass ``nulls_first=False`` or ``nulls_last=False`` to + ``Expression.asc()`` and ``Expression.desc()`` methods, and the ``OrderBy`` + expression will be removed. + +.. _deprecation-removed-in-4.1: + +4.1 +--- + +See the :ref:`Django 3.2 release notes ` for more +details on these changes. + +* Support for assigning objects which don't support creating deep copies with + ``copy.deepcopy()`` to class attributes in ``TestCase.setUpTestData()`` will + be removed. + +* ``BaseCommand.requires_system_checks`` won't support boolean values. + +* The ``whitelist`` argument and ``domain_whitelist`` attribute of + ``django.core.validators.EmailValidator`` will be removed. + +* The ``default_app_config`` module variable will be removed. + +* ``TransactionTestCase.assertQuerysetEqual()`` will no longer automatically + call ``repr()`` on a queryset when compared to string values. + +* ``django.core.cache.backends.memcached.MemcachedCache`` will be removed. + +* Support for the pre-Django 3.2 format of messages used by + ``django.contrib.messages.storage.cookie.CookieStorage`` will be removed. + +.. _deprecation-removed-in-4.0: + +4.0 +--- + +See the :ref:`Django 3.0 release notes ` for more +details on these changes. + +* ``django.utils.http.urlquote()``, ``urlquote_plus()``, ``urlunquote()``, and + ``urlunquote_plus()`` will be removed. + +* ``django.utils.encoding.force_text()`` and ``smart_text()`` will be removed. + +* ``django.utils.translation.ugettext()``, ``ugettext_lazy()``, + ``ugettext_noop()``, ``ungettext()``, and ``ungettext_lazy()`` will be + removed. + +* ``django.views.i18n.set_language()`` will no longer set the user language in + ``request.session`` (key ``django.utils.translation.LANGUAGE_SESSION_KEY``). + +* ``alias=None`` will be required in the signature of + ``django.db.models.Expression.get_group_by_cols()`` subclasses. + +* ``django.utils.text.unescape_entities()`` will be removed. + +* ``django.utils.http.is_safe_url()`` will be removed. + +See the :ref:`Django 3.1 release notes ` for more +details on these changes. + +* The ``PASSWORD_RESET_TIMEOUT_DAYS`` setting will be removed. + +* The undocumented usage of the :lookup:`isnull` lookup with non-boolean values + as the right-hand side will no longer be allowed. + +* The ``django.db.models.query_utils.InvalidQuery`` exception class will be + removed. + +* The ``django-admin.py`` entry point will be removed. + +* The ``HttpRequest.is_ajax()`` method will be removed. + +* Support for the pre-Django 3.1 encoding format of cookies values used by + ``django.contrib.messages.storage.cookie.CookieStorage`` will be removed. + +* Support for the pre-Django 3.1 password reset tokens in the admin site (that + use the SHA-1 hashing algorithm) will be removed. + +* Support for the pre-Django 3.1 encoding format of sessions will be removed. + +* Support for the pre-Django 3.1 ``django.core.signing.Signer`` signatures + (encoded with the SHA-1 algorithm) will be removed. + +* Support for the pre-Django 3.1 ``django.core.signing.dumps()`` signatures + (encoded with the SHA-1 algorithm) in ``django.core.signing.loads()`` will be + removed. + +* Support for the pre-Django 3.1 user sessions (that use the SHA-1 algorithm) + will be removed. + +* The ``get_response`` argument for + ``django.utils.deprecation.MiddlewareMixin.__init__()`` will be required and + won't accept ``None``. + +* The ``providing_args`` argument for ``django.dispatch.Signal`` will be + removed. + +* The ``length`` argument for ``django.utils.crypto.get_random_string()`` will + be required. + +* The ``list`` message for ``ModelMultipleChoiceField`` will be removed. + +* Support for passing raw column aliases to ``QuerySet.order_by()`` will be + removed. + +* The model ``NullBooleanField`` will be removed. A stub field will remain for + compatibility with historical migrations. + +* ``django.conf.urls.url()`` will be removed. + +* The model ``django.contrib.postgres.fields.JSONField`` will be removed. A + stub field will remain for compatibility with historical migrations. + +* ``django.contrib.postgres.forms.JSONField``, + ``django.contrib.postgres.fields.jsonb.KeyTransform``, and + ``django.contrib.postgres.fields.jsonb.KeyTextTransform`` will be removed. + +* The ``{% ifequal %}`` and ``{% ifnotequal %}`` template tags will be removed. + +* The ``DEFAULT_HASHING_ALGORITHM`` transitional setting will be removed. + +.. _deprecation-removed-in-3.1: + +3.1 +--- + +See the :ref:`Django 2.2 release notes ` for more +details on these changes. + +* ``django.utils.timezone.FixedOffset`` will be removed. + +* ``django.core.paginator.QuerySetPaginator`` will be removed. + +* A model's ``Meta.ordering`` will no longer affect ``GROUP BY`` queries. + +* ``django.contrib.postgres.fields.FloatRangeField`` and + ``django.contrib.postgres.forms.FloatRangeField`` will be removed. + +* The ``FILE_CHARSET`` setting will be removed. + +* ``django.contrib.staticfiles.storage.CachedStaticFilesStorage`` will be + removed. + +* ``RemoteUserBackend.configure_user()`` will require ``request`` as the first + positional argument. + +* Support for ``SimpleTestCase.allow_database_queries`` and + ``TransactionTestCase.multi_db`` will be removed. + +.. _deprecation-removed-in-3.0: + +3.0 +--- + +See the :ref:`Django 2.0 release notes` for more +details on these changes. + +* The ``django.db.backends.postgresql_psycopg2`` module will be removed. + +* ``django.shortcuts.render_to_response()`` will be removed. + +* The ``DEFAULT_CONTENT_TYPE`` setting will be removed. + +* ``HttpRequest.xreadlines()`` will be removed. + +* Support for the ``context`` argument of ``Field.from_db_value()`` and + ``Expression.convert_value()`` will be removed. + +* The ``field_name`` keyword argument of ``QuerySet.earliest()`` and + ``latest()`` will be removed. + +See the :ref:`Django 2.1 release notes ` for more +details on these changes. + +* ``django.contrib.gis.db.models.functions.ForceRHR`` will be removed. + +* ``django.utils.http.cookie_date()`` will be removed. + +* The ``staticfiles`` and ``admin_static`` template tag libraries will be + removed. + +* ``django.contrib.staticfiles.templatetags.static()`` will be removed. + +* The shim to allow ``InlineModelAdmin.has_add_permission()`` to be defined + without an ``obj`` argument will be removed. + +.. _deprecation-removed-in-2.1: + +2.1 +--- + +See the :ref:`Django 1.11 release notes` for more +details on these changes. + +* ``contrib.auth.views.login()``, ``logout()``, ``password_change()``, + ``password_change_done()``, ``password_reset()``, ``password_reset_done()``, + ``password_reset_confirm()``, and ``password_reset_complete()`` will be + removed. + +* The ``extra_context`` parameter of ``contrib.auth.views.logout_then_login()`` + will be removed. + +* ``django.test.runner.setup_databases()`` will be removed. + +* ``django.utils.translation.string_concat()`` will be removed. + +* ``django.core.cache.backends.memcached.PyLibMCCache`` will no longer support + passing ``pylibmc`` behavior settings as top-level attributes of ``OPTIONS``. + +* The ``host`` parameter of ``django.utils.http.is_safe_url()`` will be + removed. + +* Silencing of exceptions raised while rendering the ``{% include %}`` template + tag will be removed. + +* ``DatabaseIntrospection.get_indexes()`` will be removed. + +* The ``authenticate()`` method of authentication backends will require + ``request`` as the first positional argument. + +* The ``django.db.models.permalink()`` decorator will be removed. + +* The ``USE_ETAGS`` setting will be removed. ``CommonMiddleware`` and + ``django.utils.cache.patch_response_headers()`` will no longer set ETags. + +* The ``Model._meta.has_auto_field`` attribute will be removed. + +* ``url()``'s support for inline flags in regular expression groups (``(?i)``, + ``(?L)``, ``(?m)``, ``(?s)``, and ``(?u)``) will be removed. + +* Support for ``Widget.render()`` methods without the ``renderer`` argument + will be removed. + +.. _deprecation-removed-in-2.0: + +2.0 +--- + +See the :ref:`Django 1.9 release notes` for more +details on these changes. + +* The ``weak`` argument to ``django.dispatch.signals.Signal.disconnect()`` will + be removed. + +* ``django.db.backends.base.BaseDatabaseOperations.check_aggregate_support()`` + will be removed. + +* The ``django.forms.extras`` package will be removed. + +* The ``assignment_tag`` helper will be removed. + +* The ``host`` argument to ``assertsRedirects`` will be removed. The + compatibility layer which allows absolute URLs to be considered equal to + relative ones when the path is identical will also be removed. + +* ``Field.rel`` will be removed. + +* ``Field.remote_field.to`` attribute will be removed. + +* The ``on_delete`` argument for ``ForeignKey`` and ``OneToOneField`` will be + required. + +* ``django.db.models.fields.add_lazy_relation()`` will be removed. + +* When time zone support is enabled, database backends that don't support time + zones won't convert aware datetimes to naive values in UTC anymore when such + values are passed as parameters to SQL queries executed outside of the ORM, + e.g. with ``cursor.execute()``. + +* The ``django.contrib.auth.tests.utils.skipIfCustomUser()`` decorator will be + removed. + +* The ``GeoManager`` and ``GeoQuerySet`` classes will be removed. + +* The ``django.contrib.gis.geoip`` module will be removed. + +* The ``supports_recursion`` check for template loaders will be removed from: + + * ``django.template.engine.Engine.find_template()`` + * ``django.template.loader_tags.ExtendsNode.find_template()`` + * ``django.template.loaders.base.Loader.supports_recursion()`` + * ``django.template.loaders.cached.Loader.supports_recursion()`` + +* The ``load_template()`` and ``load_template_sources()`` template loader + methods will be removed. + +* The ``template_dirs`` argument for template loaders will be removed: + + * ``django.template.loaders.base.Loader.get_template()`` + * ``django.template.loaders.cached.Loader.cache_key()`` + * ``django.template.loaders.cached.Loader.get_template()`` + * ``django.template.loaders.cached.Loader.get_template_sources()`` + * ``django.template.loaders.filesystem.Loader.get_template_sources()`` + +* The ``django.template.loaders.base.Loader.__call__()`` method will be + removed. + +* Support for custom error views with a single positional parameter will be + dropped. + +* The ``mime_type`` attribute of ``django.utils.feedgenerator.Atom1Feed`` and + ``django.utils.feedgenerator.RssFeed`` will be removed in favor of + ``content_type``. + +* The ``app_name`` argument to ``django.conf.urls.include()`` will be + removed. + +* Support for passing a 3-tuple as the first argument to ``include()`` will + be removed. + +* Support for setting a URL instance namespace without an application + namespace will be removed. + +* ``Field._get_val_from_obj()`` will be removed in favor of + ``Field.value_from_object()``. + +* ``django.template.loaders.eggs.Loader`` will be removed. + +* The ``current_app`` parameter to the ``contrib.auth`` views will be removed. + +* The ``callable_obj`` keyword argument to + ``SimpleTestCase.assertRaisesMessage()`` will be removed. + +* Support for the ``allow_tags`` attribute on ``ModelAdmin`` methods will be + removed. + +* The ``enclosure`` keyword argument to ``SyndicationFeed.add_item()`` will be + removed. + +* The ``django.template.loader.LoaderOrigin`` and + ``django.template.base.StringOrigin`` aliases for + ``django.template.base.Origin`` will be removed. + +See the :ref:`Django 1.10 release notes ` for more +details on these changes. + +* The ``makemigrations --exit`` option will be removed. + +* Support for direct assignment to a reverse foreign key or many-to-many + relation will be removed. + +* The ``get_srid()`` and ``set_srid()`` methods of + ``django.contrib.gis.geos.GEOSGeometry`` will be removed. + +* The ``get_x()``, ``set_x()``, ``get_y()``, ``set_y()``, ``get_z()``, and + ``set_z()`` methods of ``django.contrib.gis.geos.Point`` will be removed. + +* The ``get_coords()`` and ``set_coords()`` methods of + ``django.contrib.gis.geos.Point`` will be removed. + +* The ``cascaded_union`` property of ``django.contrib.gis.geos.MultiPolygon`` + will be removed. + +* ``django.utils.functional.allow_lazy()`` will be removed. + +* The ``shell --plain`` option will be removed. + +* The ``django.core.urlresolvers`` module will be removed. + +* The model ``CommaSeparatedIntegerField`` will be removed. A stub field will + remain for compatibility with historical migrations. + +* Support for the template ``Context.has_key()`` method will be removed. + +* Support for the ``django.core.files.storage.Storage.accessed_time()``, + ``created_time()``, and ``modified_time()`` methods will be removed. + +* Support for query lookups using the model name when + ``Meta.default_related_name`` is set will be removed. + +* The ``__search`` query lookup and the + ``DatabaseOperations.fulltext_search_sql()`` method will be removed. + +* The shim for supporting custom related manager classes without a + ``_apply_rel_filters()`` method will be removed. + +* Using ``User.is_authenticated()`` and ``User.is_anonymous()`` as methods + will no longer be supported. + +* The private attribute ``virtual_fields`` of ``Model._meta`` will be removed. + +* The private keyword arguments ``virtual_only`` in + ``Field.contribute_to_class()`` and ``virtual`` in + ``Model._meta.add_field()`` will be removed. + +* The ``javascript_catalog()`` and ``json_catalog()`` views will be removed. + +* The ``django.contrib.gis.utils.precision_wkt()`` function will be removed. + +* In multi-table inheritance, implicit promotion of a ``OneToOneField`` to a + ``parent_link`` will be removed. + +* Support for ``Widget._format_value()`` will be removed. + +* ``FileField`` methods ``get_directory_name()`` and ``get_filename()`` will be + removed. + +* The ``mark_for_escaping()`` function and the classes it uses: ``EscapeData``, + ``EscapeBytes``, ``EscapeText``, ``EscapeString``, and ``EscapeUnicode`` will + be removed. + +* The ``escape`` filter will change to use + ``django.utils.html.conditional_escape()``. + +* ``Manager.use_for_related_fields`` will be removed. + +* Model ``Manager`` inheritance will follow MRO inheritance rules and the + ``Meta.manager_inheritance_from_future`` to opt-in to this behavior will be + removed. + +* Support for old-style middleware using ``settings.MIDDLEWARE_CLASSES`` will + be removed. + +.. _deprecation-removed-in-1.10: + +1.10 +---- + +See the :ref:`Django 1.8 release notes` for more +details on these changes. + +* Support for calling a ``SQLCompiler`` directly as an alias for calling its + ``quote_name_unless_alias`` method will be removed. + +* ``cycle`` and ``firstof`` template tags will be removed from the ``future`` + template tag library (used during the 1.6/1.7 deprecation period). + +* ``django.conf.urls.patterns()`` will be removed. + +* Support for the ``prefix`` argument to + ``django.conf.urls.i18n.i18n_patterns()`` will be removed. + +* ``SimpleTestCase.urls`` will be removed. + +* Using an incorrect count of unpacked values in the ``for`` template tag + will raise an exception rather than fail silently. + +* The ability to reverse URLs using a dotted Python path will be removed. + +* The ability to use a dotted Python path for the ``LOGIN_URL`` and + ``LOGIN_REDIRECT_URL`` settings will be removed. + +* Support for :py:mod:`optparse` will be dropped for custom management commands + (replaced by :py:mod:`argparse`). + +* The class ``django.core.management.NoArgsCommand`` will be removed. Use + :class:`~django.core.management.BaseCommand` instead, which takes no arguments + by default. + +* ``django.core.context_processors`` module will be removed. + +* ``django.db.models.sql.aggregates`` module will be removed. + +* ``django.contrib.gis.db.models.sql.aggregates`` module will be removed. + +* The following methods and properties of ``django.db.sql.query.Query`` will + be removed: + + * Properties: ``aggregates`` and ``aggregate_select`` + * Methods: ``add_aggregate``, ``set_aggregate_mask``, and + ``append_aggregate_mask``. + +* ``django.template.resolve_variable`` will be removed. + +* The following private APIs will be removed from + :class:`django.db.models.options.Options` (``Model._meta``): + + * ``get_field_by_name()`` + * ``get_all_field_names()`` + * ``get_fields_with_model()`` + * ``get_concrete_fields_with_model()`` + * ``get_m2m_with_model()`` + * ``get_all_related_objects()`` + * ``get_all_related_objects_with_model()`` + * ``get_all_related_many_to_many_objects()`` + * ``get_all_related_m2m_objects_with_model()`` + +* The ``error_message`` argument of ``django.forms.RegexField`` will be removed. + +* The ``unordered_list`` filter will no longer support old style lists. + +* Support for string ``view`` arguments to ``url()`` will be removed. + +* The backward compatible shim to rename ``django.forms.Form._has_changed()`` + to ``has_changed()`` will be removed. + +* The ``removetags`` template filter will be removed. + +* The ``remove_tags()`` and ``strip_entities()`` functions in + ``django.utils.html`` will be removed. + +* The ``is_admin_site`` argument to + ``django.contrib.auth.views.password_reset()`` will be removed. + +* ``django.db.models.field.subclassing.SubfieldBase`` will be removed. + +* ``django.utils.checksums`` will be removed; its functionality is included + in ``django-localflavor`` 1.1+. + +* The ``original_content_type_id`` attribute on + ``django.contrib.admin.helpers.InlineAdminForm`` will be removed. + +* The backwards compatibility shim to allow ``FormMixin.get_form()`` to be + defined with no default value for its ``form_class`` argument will be removed. + +* The following settings will be removed: + + * ``ALLOWED_INCLUDE_ROOTS`` + * ``TEMPLATE_CONTEXT_PROCESSORS`` + * ``TEMPLATE_DEBUG`` + * ``TEMPLATE_DIRS`` + * ``TEMPLATE_LOADERS`` + * ``TEMPLATE_STRING_IF_INVALID`` + +* The backwards compatibility alias ``django.template.loader.BaseLoader`` will + be removed. + +* Django template objects returned by + :func:`~django.template.loader.get_template` and + :func:`~django.template.loader.select_template` won't accept a + :class:`~django.template.Context` in their + :meth:`~django.template.backends.base.Template.render()` method anymore. + +* :doc:`Template response APIs ` will enforce the use + of :class:`dict` and backend-dependent template objects instead of + :class:`~django.template.Context` and :class:`~django.template.Template` + respectively. + +* The ``current_app`` parameter for the following function and classes will be + removed: + + * ``django.shortcuts.render()`` + * ``django.template.Context()`` + * ``django.template.RequestContext()`` + * ``django.template.response.TemplateResponse()`` + +* The ``dictionary`` and ``context_instance`` parameters for the following + functions will be removed: + + * ``django.shortcuts.render()`` + * ``django.shortcuts.render_to_response()`` + * ``django.template.loader.render_to_string()`` + +* The ``dirs`` parameter for the following functions will be removed: + + * ``django.template.loader.get_template()`` + * ``django.template.loader.select_template()`` + * ``django.shortcuts.render()`` + * ``django.shortcuts.render_to_response()`` + +* Session verification will be enabled regardless of whether or not + ``'django.contrib.auth.middleware.SessionAuthenticationMiddleware'`` is in + ``MIDDLEWARE_CLASSES``. + +* Private attribute ``django.db.models.Field.related`` will be removed. + +* The ``--list`` option of the ``migrate`` management command will be removed. + +* The ``ssi`` template tag will be removed. + +* Support for the ``=`` comparison operator in the ``if`` template tag will be + removed. + +* The backwards compatibility shims to allow ``Storage.get_available_name()`` + and ``Storage.save()`` to be defined without a ``max_length`` argument will + be removed. + +* Support for the legacy ``%()s`` syntax in ``ModelFormMixin.success_url`` + will be removed. + +* ``GeoQuerySet`` aggregate methods ``collect()``, ``extent()``, ``extent3d()``, + ``make_line()``, and ``unionagg()`` will be removed. + +* Ability to specify ``ContentType.name`` when creating a content type instance + will be removed. + +* Support for the old signature of ``allow_migrate`` will be removed. It changed + from ``allow_migrate(self, db, model)`` to + ``allow_migrate(self, db, app_label, model_name=None, **hints)``. + +* Support for the syntax of ``{% cycle %}`` that uses comma-separated arguments + will be removed. + +* The warning that :class:`~django.core.signing.Signer` issues when given an + invalid separator will become an exception. + +.. _deprecation-removed-in-1.9: + +1.9 +--- + +See the :ref:`Django 1.7 release notes` for more +details on these changes. + +* ``django.utils.dictconfig`` will be removed. + +* ``django.utils.importlib`` will be removed. + +* ``django.utils.tzinfo`` will be removed. + +* ``django.utils.unittest`` will be removed. + +* The ``syncdb`` command will be removed. + +* ``django.db.models.signals.pre_syncdb`` and + ``django.db.models.signals.post_syncdb`` will be removed. + +* ``allow_syncdb`` on database routers will no longer automatically become + ``allow_migrate``. + +* Automatic syncing of apps without migrations will be removed. Migrations will + become compulsory for all apps unless you pass the ``--run-syncdb`` option to + ``migrate``. + +* The SQL management commands for apps without migrations, ``sql``, ``sqlall``, + ``sqlclear``, ``sqldropindexes``, and ``sqlindexes``, will be removed. + +* Support for automatic loading of ``initial_data`` fixtures and initial SQL + data will be removed. + +* All models will need to be defined inside an installed application or + declare an explicit :attr:`~django.db.models.Options.app_label`. + Furthermore, it won't be possible to import them before their application + is loaded. In particular, it won't be possible to import models inside + the root package of their application. + +* The model and form ``IPAddressField`` will be removed. A stub field will + remain for compatibility with historical migrations. + +* ``AppCommand.handle_app()`` will no longer be supported. + +* ``RequestSite`` and ``get_current_site()`` will no longer be importable from + ``django.contrib.sites.models``. + +* FastCGI support via the ``runfcgi`` management command will be + removed. Please deploy your project using WSGI. + +* ``django.utils.datastructures.SortedDict`` will be removed. Use + :class:`collections.OrderedDict` from the Python standard library instead. + +* ``ModelAdmin.declared_fieldsets`` will be removed. + +* Instances of ``util.py`` in the Django codebase have been renamed to + ``utils.py`` in an effort to unify all util and utils references. + The modules that provided backwards compatibility will be removed: + + * ``django.contrib.admin.util`` + * ``django.contrib.gis.db.backends.util`` + * ``django.db.backends.util`` + * ``django.forms.util`` + +* ``ModelAdmin.get_formsets`` will be removed. + +* The backward compatibility shim introduced to rename the + ``BaseMemcachedCache._get_memcache_timeout()`` method to + ``get_backend_timeout()`` will be removed. + +* The ``--natural`` and ``-n`` options for :djadmin:`dumpdata` will be removed. + +* The ``use_natural_keys`` argument for ``serializers.serialize()`` will be + removed. + +* Private API ``django.forms.forms.get_declared_fields()`` will be removed. + +* The ability to use a ``SplitDateTimeWidget`` with ``DateTimeField`` will be + removed. + +* The ``WSGIRequest.REQUEST`` property will be removed. + +* The class ``django.utils.datastructures.MergeDict`` will be removed. + +* The ``zh-cn`` and ``zh-tw`` language codes will be removed and have been + replaced by the ``zh-hans`` and ``zh-hant`` language code respectively. + +* The internal ``django.utils.functional.memoize`` will be removed. + +* ``django.core.cache.get_cache`` will be removed. Add suitable entries + to :setting:`CACHES` and use :data:`django.core.cache.caches` instead. + +* ``django.db.models.loading`` will be removed. + +* Passing callable arguments to querysets will no longer be possible. + +* ``BaseCommand.requires_model_validation`` will be removed in favor of + ``requires_system_checks``. Admin validators will be replaced by admin + checks. + +* The ``ModelAdmin.validator_class`` and ``default_validator_class`` attributes + will be removed. + +* ``ModelAdmin.validate()`` will be removed. + +* ``django.db.backends.DatabaseValidation.validate_field`` will be removed in + favor of the ``check_field`` method. + +* The ``validate`` management command will be removed. + +* ``django.utils.module_loading.import_by_path`` will be removed in favor of + ``django.utils.module_loading.import_string``. + +* ``ssi`` and ``url`` template tags will be removed from the ``future`` template + tag library (used during the 1.3/1.4 deprecation period). + +* ``django.utils.text.javascript_quote`` will be removed. + +* Database test settings as independent entries in the database settings, + prefixed by ``TEST_``, will no longer be supported. + +* The ``cache_choices`` option to :class:`~django.forms.ModelChoiceField` and + :class:`~django.forms.ModelMultipleChoiceField` will be removed. + +* The default value of the + :attr:`RedirectView.permanent ` + attribute will change from ``True`` to ``False``. + +* ``django.contrib.sitemaps.FlatPageSitemap`` will be removed in favor of + ``django.contrib.flatpages.sitemaps.FlatPageSitemap``. + +* Private API ``django.test.utils.TestTemplateLoader`` will be removed. + +* The ``django.contrib.contenttypes.generic`` module will be removed. + +* Private APIs ``django.db.models.sql.where.WhereNode.make_atom()`` and + ``django.db.models.sql.where.Constraint`` will be removed. + +.. _deprecation-removed-in-1.8: + +1.8 +--- + +See the :ref:`Django 1.6 release notes` for more +details on these changes. + +* ``django.contrib.comments`` will be removed. + +* The following transaction management APIs will be removed: + + - ``TransactionMiddleware``, + - the decorators and context managers ``autocommit``, ``commit_on_success``, + and ``commit_manually``, defined in ``django.db.transaction``, + - the functions ``commit_unless_managed`` and ``rollback_unless_managed``, + also defined in ``django.db.transaction``, + - the ``TRANSACTIONS_MANAGED`` setting. + +* The :ttag:`cycle` and :ttag:`firstof` template tags will auto-escape their + arguments. In 1.6 and 1.7, this behavior is provided by the version of these + tags in the ``future`` template tag library. + +* The ``SEND_BROKEN_LINK_EMAILS`` setting will be removed. Add the + :class:`django.middleware.common.BrokenLinkEmailsMiddleware` middleware to + your ``MIDDLEWARE_CLASSES`` setting instead. + +* ``django.middleware.doc.XViewMiddleware`` will be removed. Use + ``django.contrib.admindocs.middleware.XViewMiddleware`` instead. + +* ``Model._meta.module_name`` was renamed to ``model_name``. + +* Remove the backward compatible shims introduced to rename ``get_query_set`` + and similar queryset methods. This affects the following classes: + ``BaseModelAdmin``, ``ChangeList``, ``BaseCommentNode``, + ``GenericForeignKey``, ``Manager``, ``SingleRelatedObjectDescriptor`` and + ``ReverseSingleRelatedObjectDescriptor``. + +* Remove the backward compatible shims introduced to rename the attributes + ``ChangeList.root_query_set`` and ``ChangeList.query_set``. + +* ``django.views.defaults.shortcut`` will be removed, as part of the + goal of removing all ``django.contrib`` references from the core + Django codebase. Instead use + ``django.contrib.contenttypes.views.shortcut``. ``django.conf.urls.shortcut`` + will also be removed. + +* Support for the Python Imaging Library (PIL) module will be removed, as it + no longer appears to be actively maintained & does not work on Python 3. + +* The following private APIs will be removed: + + - ``django.db.backend`` + - ``django.db.close_connection()`` + - ``django.db.backends.creation.BaseDatabaseCreation.set_autocommit()`` + - ``django.db.transaction.is_managed()`` + - ``django.db.transaction.managed()`` + +* ``django.forms.widgets.RadioInput`` will be removed in favor of + ``django.forms.widgets.RadioChoiceInput``. + +* The module ``django.test.simple`` and the class + ``django.test.simple.DjangoTestSuiteRunner`` will be removed. Instead use + ``django.test.runner.DiscoverRunner``. + +* The module ``django.test._doctest`` will be removed. Instead use the doctest + module from the Python standard library. + +* The ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting will be removed. + +* Usage of the hard-coded *Hold down "Control", or "Command" on a Mac, to select + more than one.* string to override or append to user-provided ``help_text`` in + forms for ManyToMany model fields will not be performed by Django anymore + either at the model or forms layer. + +* The ``Model._meta.get_(add|change|delete)_permission`` methods will + be removed. + +* The session key ``django_language`` will no longer be read for backwards + compatibility. + +* Geographic Sitemaps will be removed + (``django.contrib.gis.sitemaps.views.index`` and + ``django.contrib.gis.sitemaps.views.sitemap``). + +* ``django.utils.html.fix_ampersands``, the ``fix_ampersands`` template filter and + ``django.utils.html.clean_html`` will be removed following an accelerated deprecation. + +.. _deprecation-removed-in-1.7: + +1.7 +--- + +See the :ref:`Django 1.5 release notes` for more +details on these changes. + +* The module ``django.utils.simplejson`` will be removed. The standard library + provides :mod:`json` which should be used instead. + +* The function ``django.utils.itercompat.product`` will be removed. The Python + builtin version should be used instead. + +* Auto-correction of INSTALLED_APPS and TEMPLATE_DIRS settings when they are + specified as a plain string instead of a tuple will be removed and raise an + exception. + +* The ``mimetype`` argument to the ``__init__`` methods of + :class:`~django.http.HttpResponse`, + :class:`~django.template.response.SimpleTemplateResponse`, and + :class:`~django.template.response.TemplateResponse`, will be removed. + ``content_type`` should be used instead. This also applies to the + ``render_to_response()`` shortcut and the sitemap views, + :func:`~django.contrib.sitemaps.views.index` and + :func:`~django.contrib.sitemaps.views.sitemap`. + +* When :class:`~django.http.HttpResponse` is instantiated with an iterator, + or when :attr:`~django.http.HttpResponse.content` is set to an iterator, + that iterator will be immediately consumed. + +* The ``AUTH_PROFILE_MODULE`` setting, and the ``get_profile()`` method on + the User model, will be removed. + +* The ``cleanup`` management command will be removed. It's replaced by + ``clearsessions``. + +* The ``daily_cleanup.py`` script will be removed. + +* The ``depth`` keyword argument will be removed from + :meth:`~django.db.models.query.QuerySet.select_related`. + +* The undocumented ``get_warnings_state()``/``restore_warnings_state()`` + functions from :mod:`django.test.utils` and the ``save_warnings_state()``/ + ``restore_warnings_state()`` + :ref:`django.test.*TestCase ` methods are + deprecated. Use the :class:`warnings.catch_warnings` context manager + available starting with Python 2.6 instead. + +* The undocumented ``check_for_test_cookie`` method in + :class:`~django.contrib.auth.forms.AuthenticationForm` will be removed + following an accelerated deprecation. Users subclassing this form should + remove calls to this method, and instead ensure that their auth related views + are CSRF protected, which ensures that cookies are enabled. + +* The version of ``django.contrib.auth.views.password_reset_confirm()`` that + supports base36 encoded user IDs + (``django.contrib.auth.views.password_reset_confirm_uidb36``) will be + removed. If your site has been running Django 1.6 for more than + ``PASSWORD_RESET_TIMEOUT_DAYS``, this change will have no effect. If not, + then any password reset links generated before you upgrade to Django 1.7 + won't work after the upgrade. + +* The ``django.utils.encoding.StrAndUnicode`` mix-in will be removed. + +.. _deprecation-removed-in-1.6: + +1.6 +--- + +See the :ref:`Django 1.4 release notes` for more +details on these changes. + +* ``django.contrib.databrowse`` will be removed. + +* ``django.contrib.localflavor`` will be removed following an accelerated + deprecation. + +* ``django.contrib.markup`` will be removed following an accelerated + deprecation. + +* The compatibility modules ``django.utils.copycompat`` and + ``django.utils.hashcompat`` as well as the functions + ``django.utils.itercompat.all`` and ``django.utils.itercompat.any`` will + be removed. The Python builtin versions should be used instead. + +* The ``csrf_response_exempt`` and ``csrf_view_exempt`` decorators will + be removed. Since 1.4 ``csrf_response_exempt`` has been a no-op (it + returns the same function), and ``csrf_view_exempt`` has been a + synonym for ``django.views.decorators.csrf.csrf_exempt``, which should + be used to replace it. + +* The ``django.core.cache.backends.memcached.CacheClass`` backend + was split into two in Django 1.3 in order to introduce support for + PyLibMC. The historical ``CacheClass`` will be removed in favor of + ``django.core.cache.backends.memcached.MemcachedCache``. + +* The UK-prefixed objects of ``django.contrib.localflavor.uk`` will only + be accessible through their GB-prefixed names (GB is the correct + ISO 3166 code for United Kingdom). + +* The ``IGNORABLE_404_STARTS`` and ``IGNORABLE_404_ENDS`` settings have been + superseded by :setting:`IGNORABLE_404_URLS` in the 1.4 release. They will be + removed. + +* The form wizard has been refactored to use class-based views with pluggable + backends in 1.4. The previous implementation will be removed. + +* Legacy ways of calling + :func:`~django.views.decorators.cache.cache_page` will be removed. + +* The backward-compatibility shim to automatically add a debug-false + filter to the ``'mail_admins'`` logging handler will be removed. The + :setting:`LOGGING` setting should include this filter explicitly if + it is desired. + +* The builtin truncation functions ``django.utils.text.truncate_words()`` + and ``django.utils.text.truncate_html_words()`` will be removed in + favor of the ``django.utils.text.Truncator`` class. + +* The ``django.contrib.gis.geoip.GeoIP`` class was moved to + ``django.contrib.gis.geoip`` in 1.4 -- the shortcut in + ``django.contrib.gis.utils`` will be removed. + +* ``django.conf.urls.defaults`` will be removed. The functions + ``include()``, ``patterns()``, and ``url()``, plus + :data:`~django.conf.urls.handler404` and :data:`~django.conf.urls.handler500` + are now available through ``django.conf.urls``. + +* The functions ``setup_environ()`` and ``execute_manager()`` will be removed + from :mod:`django.core.management`. This also means that the old (pre-1.4) + style of :file:`manage.py` file will no longer work. + +* Setting the ``is_safe`` and ``needs_autoescape`` flags as attributes of + template filter functions will no longer be supported. + +* The attribute ``HttpRequest.raw_post_data`` was renamed to ``HttpRequest.body`` + in 1.4. The backward compatibility will be removed -- + ``HttpRequest.raw_post_data`` will no longer work. + +* The value for the ``post_url_continue`` parameter in + ``ModelAdmin.response_add()`` will have to be either ``None`` (to redirect + to the newly created object's edit page) or a pre-formatted url. String + formats, such as the previous default ``'../%s/'``, will not be accepted any + more. + +.. _deprecation-removed-in-1.5: + +1.5 +--- + +See the :ref:`Django 1.3 release notes` for more +details on these changes. + +* Starting Django without a :setting:`SECRET_KEY` will result in an exception + rather than a ``DeprecationWarning``. (This is accelerated from the usual + deprecation path; see the :doc:`Django 1.4 release notes`.) + +* The ``mod_python`` request handler will be removed. The ``mod_wsgi`` + handler should be used instead. + +* The ``template`` attribute on ``django.test.client.Response`` + objects returned by the :ref:`test client ` will be removed. + The :attr:`~django.test.Response.templates` attribute should be + used instead. + +* The ``django.test.simple.DjangoTestRunner`` will be removed. + Instead use a ``unittest``-native class. The features of the + ``django.test.simple.DjangoTestRunner`` (including fail-fast and + Ctrl-C test termination) can be provided by :class:`unittest.TextTestRunner`. + +* The undocumented function + ``django.contrib.formtools.utils.security_hash`` will be removed, + instead use ``django.contrib.formtools.utils.form_hmac`` + +* The function-based generic view modules will be removed in favor of their + class-based equivalents, outlined :doc:`here + `. + +* The ``django.core.servers.basehttp.AdminMediaHandler`` will be + removed. In its place use + ``django.contrib.staticfiles.handlers.StaticFilesHandler``. + +* The template tags library ``adminmedia`` and the template tag ``{% + admin_media_prefix %}`` will be removed in favor of the generic static files + handling. (This is faster than the usual deprecation path; see the + :doc:`Django 1.4 release notes`.) + +* The ``url`` and ``ssi`` template tags will be modified so that the first + argument to each tag is a template variable, not an implied string. In 1.4, + this behavior is provided by a version of the tag in the ``future`` template + tag library. + +* The ``reset`` and ``sqlreset`` management commands will be removed. + +* Authentication backends will need to support an inactive user + being passed to all methods dealing with permissions. + The ``supports_inactive_user`` attribute will no longer be checked + and can be removed from custom backends. + +* :meth:`~django.contrib.gis.geos.GEOSGeometry.transform` will raise + a :class:`~django.contrib.gis.geos.GEOSException` when called + on a geometry with no SRID value. + +* ``django.http.CompatCookie`` will be removed in favor of + ``django.http.SimpleCookie``. + +* ``django.core.context_processors.PermWrapper`` and + ``django.core.context_processors.PermLookupDict`` will be removed in + favor of the corresponding + ``django.contrib.auth.context_processors.PermWrapper`` and + ``django.contrib.auth.context_processors.PermLookupDict``, respectively. + +* The :setting:`MEDIA_URL` or :setting:`STATIC_URL` settings will be + required to end with a trailing slash to ensure there is a consistent + way to combine paths in templates. + +* ``django.db.models.fields.URLField.verify_exists`` will be removed. The + feature was deprecated in 1.3.1 due to intractable security and + performance issues and will follow a slightly accelerated deprecation + timeframe. + +* Translations located under the so-called *project path* will be ignored during + the translation building process performed at runtime. The + :setting:`LOCALE_PATHS` setting can be used for the same task by including the + filesystem path to a ``locale`` directory containing non-app-specific + translations in its value. + +* The Markup contrib app will no longer support versions of Python-Markdown + library earlier than 2.1. An accelerated timeline was used as this was + a security related deprecation. + +* The ``CACHE_BACKEND`` setting will be removed. The cache backend(s) should be + specified in the :setting:`CACHES` setting. + +.. _deprecation-removed-in-1.4: + +1.4 +--- + +See the :ref:`Django 1.2 release notes` for more +details on these changes. + +* ``CsrfResponseMiddleware`` and ``CsrfMiddleware`` will be removed. Use + the ``{% csrf_token %}`` template tag inside forms to enable CSRF + protection. ``CsrfViewMiddleware`` remains and is enabled by default. + +* The old imports for CSRF functionality (``django.contrib.csrf.*``), + which moved to core in 1.2, will be removed. + +* The ``django.contrib.gis.db.backend`` module will be removed in favor + of the specific backends. + +* ``SMTPConnection`` will be removed in favor of a generic email backend API. + +* The many to many SQL generation functions on the database backends + will be removed. + +* The ability to use the ``DATABASE_*`` family of top-level settings to + define database connections will be removed. + +* The ability to use shorthand notation to specify a database backend + (i.e., ``sqlite3`` instead of ``django.db.backends.sqlite3``) will be + removed. + +* The ``get_db_prep_save``, ``get_db_prep_value`` and + ``get_db_prep_lookup`` methods will have to support multiple databases. + +* The ``Message`` model (in ``django.contrib.auth``), its related + manager in the ``User`` model (``user.message_set``), and the + associated methods (``user.message_set.create()`` and + ``user.get_and_delete_messages()``), will be removed. The + :doc:`messages framework ` should be used + instead. The related ``messages`` variable returned by the + auth context processor will also be removed. Note that this + means that the admin application will depend on the messages + context processor. + +* Authentication backends will need to support the ``obj`` parameter for + permission checking. The ``supports_object_permissions`` attribute + will no longer be checked and can be removed from custom backends. + +* Authentication backends will need to support the ``AnonymousUser`` class + being passed to all methods dealing with permissions. The + ``supports_anonymous_user`` variable will no longer be checked and can be + removed from custom backends. + +* The ability to specify a callable template loader rather than a + ``Loader`` class will be removed, as will the ``load_template_source`` + functions that are included with the built in template loaders for + backwards compatibility. + +* ``django.utils.translation.get_date_formats()`` and + ``django.utils.translation.get_partial_date_formats()``. These functions + will be removed; use the locale-aware + ``django.utils.formats.get_format()`` to get the appropriate formats. + +* In ``django.forms.fields``, the constants: ``DEFAULT_DATE_INPUT_FORMATS``, + ``DEFAULT_TIME_INPUT_FORMATS`` and + ``DEFAULT_DATETIME_INPUT_FORMATS`` will be removed. Use + ``django.utils.formats.get_format()`` to get the appropriate + formats. + +* The ability to use a function-based test runner will be removed, + along with the ``django.test.simple.run_tests()`` test runner. + +* The ``views.feed()`` view and ``feeds.Feed`` class in + ``django.contrib.syndication`` will be removed. The class-based view + ``views.Feed`` should be used instead. + +* ``django.core.context_processors.auth``. This release will + remove the old method in favor of the new method in + ``django.contrib.auth.context_processors.auth``. + +* The ``postgresql`` database backend will be removed, use the + ``postgresql_psycopg2`` backend instead. + +* The ``no`` language code will be removed and has been replaced by the + ``nb`` language code. + +* Authentication backends will need to define the boolean attribute + ``supports_inactive_user`` until version 1.5 when it will be assumed that + all backends will handle inactive users. + +* ``django.db.models.fields.XMLField`` will be removed. This was + deprecated as part of the 1.3 release. An accelerated deprecation + schedule has been used because the field hasn't performed any role + beyond that of a simple ``TextField`` since the removal of ``oldforms``. + All uses of ``XMLField`` can be replaced with ``TextField``. + +* The undocumented ``mixin`` parameter to the ``open()`` method of + ``django.core.files.storage.Storage`` (and subclasses) will be removed. + +.. _deprecation-removed-in-1.3: + +1.3 +--- + +See the :ref:`Django 1.1 release notes` for more +details on these changes. + +* ``AdminSite.root()``. This method of hooking up the admin URLs will be + removed in favor of including ``admin.site.urls``. + +* Authentication backends need to define the boolean attributes + ``supports_object_permissions`` and ``supports_anonymous_user`` until + version 1.4, at which point it will be assumed that all backends will + support these options. diff --git a/testbed/django__django/docs/internals/git.txt b/testbed/django__django/docs/internals/git.txt new file mode 100644 index 0000000000000000000000000000000000000000..7329fe0bbcbc325df370b2b5965801979677e956 --- /dev/null +++ b/testbed/django__django/docs/internals/git.txt @@ -0,0 +1,225 @@ +================================= +The Django source code repository +================================= + +When deploying a Django application into a real production environment, you +will almost always want to use `an official packaged release of Django`_. + +However, if you'd like to try out in-development code from an upcoming release +or contribute to the development of Django, you'll need to obtain a clone of +Django's source code repository. + +This document covers the way the code repository is laid out and how to work +with and find things in it. + +.. _an official packaged release of Django: https://www.djangoproject.com/download/ + +High-level overview +=================== + +The Django source code repository uses `Git`_ to track changes to the code +over time, so you'll need a copy of the Git client (a program called ``git``) +on your computer, and you'll want to familiarize yourself with the basics of +how Git works. + +Git's website offers downloads for various operating systems. The site also +contains vast amounts of `documentation`_. + +The Django Git repository is located online at `github.com/django/django +`_. It contains the full source code for all +Django releases, which you can browse online. + +The Git repository includes several `branches`_: + +* ``main`` contains the main in-development code which will become + the next packaged release of Django. This is where most development + activity is focused. + +* ``stable/A.B.x`` are the branches where release preparation work happens. + They are also used for bugfix and security releases which occur as necessary + after the initial release of a feature version. + +The Git repository also contains `tags`_. These are the exact revisions from +which packaged Django releases were produced, since version 1.0. + +A number of tags also exist under the ``archive/`` prefix for :ref:`archived +work`. + +The source code for the `Djangoproject.com `_ +website can be found at `github.com/django/djangoproject.com +`_. + +.. _Git: https://git-scm.com/ +.. _documentation: https://git-scm.com/doc +.. _branches: https://github.com/django/django/branches +.. _tags: https://github.com/django/django/tags + +The main branch +=============== + +If you'd like to try out the in-development code for the next release of +Django, or if you'd like to contribute to Django by fixing bugs or developing +new features, you'll want to get the code from the main branch. + +.. note:: + + Prior to March 2021, the main branch was called ``master``. + +Note that this will get *all* of Django: in addition to the top-level +``django`` module containing Python code, you'll also get a copy of Django's +documentation, test suite, packaging scripts and other miscellaneous bits. +Django's code will be present in your clone as a directory named +``django``. + +To try out the in-development code with your own applications, place the +directory containing your clone on your Python import path. Then ``import`` +statements which look for Django will find the ``django`` module within your +clone. + +If you're going to be working on Django's code (say, to fix a bug or +develop a new feature), you can probably stop reading here and move +over to :doc:`the documentation for contributing to Django +`, which covers things like the preferred +coding style and how to generate and submit a patch. + +Stable branches +=============== + +Django uses branches to prepare for releases of Django. Each major release +series has its own stable branch. + +These branches can be found in the repository as ``stable/A.B.x`` +branches and will be created right after the first alpha is tagged. + +For example, immediately after *Django 1.5 alpha 1* was tagged, the branch +``stable/1.5.x`` was created and all further work on preparing the code for the +final 1.5 release was done there. + +These branches also provide bugfix and security support as described in +:ref:`supported-versions-policy`. + +For example, after the release of Django 1.5, the branch ``stable/1.5.x`` +receives only fixes for security and critical stability bugs, which are +eventually released as Django 1.5.1 and so on, ``stable/1.4.x`` receives only +security and data loss fixes, and ``stable/1.3.x`` no longer receives any +updates. + +.. admonition:: Historical information + + This policy for handling ``stable/A.B.x`` branches was adopted starting + with the Django 1.5 release cycle. + + Previously, these branches weren't created until right after the releases + and the stabilization work occurred on the main repository branch. Thus, + no new feature development work for the next release of Django could be + committed until the final release happened. + + For example, shortly after the release of Django 1.3 the branch + ``stable/1.3.x`` was created. Official support for that release has expired, + and so it no longer receives direct maintenance from the Django project. + However, that and all other similarly named branches continue to exist, and + interested community members have occasionally used them to provide + unofficial support for old Django releases. + +Tags +==== + +Each Django release is tagged and signed by the releaser. + +The tags can be found on GitHub's `tags`_ page. + +.. _tags: https://github.com/django/django/tags + +.. _archived-feature-development-work: + +Archived feature-development work +--------------------------------- + +.. admonition:: Historical information + + Since Django moved to Git in 2012, anyone can clone the repository and + create their own branches, alleviating the need for official branches in + the source code repository. + + The following section is mostly useful if you're exploring the repository's + history, for example if you're trying to understand how some features were + designed. + +Feature-development branches tend by their nature to be temporary. Some +produce successful features which are merged back into Django's main branch to +become part of an official release, but others do not; in either case, there +comes a time when the branch is no longer being actively worked on by any +developer. At this point the branch is considered closed. + +Django used to be maintained with the Subversion revision control system, that +has no standard way of indicating this. As a workaround, branches of Django +which are closed and no longer maintained were moved into ``attic``. + +A number of tags exist under the ``archive/`` prefix to maintain a reference to +this and other work of historical interest. + +The following tags under the ``archive/attic/`` prefix reference the tip of +branches whose code eventually became part of Django itself: + +* ``boulder-oracle-sprint``: Added support for Oracle databases to + Django's object-relational mapper. This has been part of Django + since the 1.0 release. + +* ``gis``: Added support for geographic/spatial queries to Django's + object-relational mapper. This has been part of Django since the 1.0 + release, as the bundled application ``django.contrib.gis``. + +* ``i18n``: Added :doc:`internationalization support ` to + Django. This has been part of Django since the 0.90 release. + +* ``magic-removal``: A major refactoring of both the internals and + public APIs of Django's object-relational mapper. This has been part + of Django since the 0.95 release. + +* ``multi-auth``: A refactoring of :doc:`Django's bundled + authentication framework ` which added support for + :ref:`authentication backends `. This has + been part of Django since the 0.95 release. + +* ``new-admin``: A refactoring of :doc:`Django's bundled + administrative application `. This became part of + Django as of the 0.91 release, but was superseded by another + refactoring (see next listing) prior to the Django 1.0 release. + +* ``newforms-admin``: The second refactoring of Django's bundled + administrative application. This became part of Django as of the 1.0 + release, and is the basis of the current incarnation of + ``django.contrib.admin``. + +* ``queryset-refactor``: A refactoring of the internals of Django's + object-relational mapper. This became part of Django as of the 1.0 + release. + +* ``unicode``: A refactoring of Django's internals to consistently use + Unicode-based strings in most places within Django and Django + applications. This became part of Django as of the 1.0 release. + +Additionally, the following tags under the ``archive/attic/`` prefix reference +the tips of branches that were closed, but whose code was never merged into +Django, and the features they aimed to implement were never finished: + +* ``full-history`` + +* ``generic-auth`` + +* ``multiple-db-support`` + +* ``per-object-permissions`` + +* ``schema-evolution`` + +* ``schema-evolution-ng`` + +* ``search-api`` + +* ``sqlalchemy`` + +Finally, under the ``archive/`` prefix, the repository contains +``soc20XX/`` tags referencing the tip of branches that were used by +students who worked on Django during the 2009 and 2010 Google Summer of Code +programs. diff --git a/testbed/django__django/docs/internals/howto-release-django.txt b/testbed/django__django/docs/internals/howto-release-django.txt new file mode 100644 index 0000000000000000000000000000000000000000..f7ca5fb537fb0ade3cfe16d17fc6e2e262f3f821 --- /dev/null +++ b/testbed/django__django/docs/internals/howto-release-django.txt @@ -0,0 +1,521 @@ +===================== +How is Django Formed? +===================== + +This document explains how to release Django. + +**Please, keep these instructions up-to-date if you make changes!** The point +here is to be descriptive, not prescriptive, so feel free to streamline or +otherwise make changes, but **update this document accordingly!** + +Overview +======== + +There are three types of releases that you might need to make: + +* Security releases: disclosing and fixing a vulnerability. This'll + generally involve two or three simultaneous releases -- e.g. + 3.2.x, 4.0.x, and, depending on timing, perhaps a 4.1.x. + +* Regular version releases: either a final release (e.g. 4.1) or a + bugfix update (e.g. 4.1.1). + +* Pre-releases: e.g. 4.2 alpha, beta, or rc. + +The short version of the steps involved is: + +#. If this is a security release, pre-notify the security distribution list + one week before the actual release. + +#. Proofread the release notes, looking for organization and writing errors. + Draft a blog post and email announcement. + +#. Update version numbers and create the release package(s). + +#. Upload the package(s) to the ``djangoproject.com`` server. + +#. Verify package(s) signatures, check if they can be installed, and ensure + minimal functionality. + +#. Upload the new version(s) to PyPI. + +#. Declare the new version in the admin on ``djangoproject.com``. + +#. Post the blog entry and send out the email announcements. + +#. Update version numbers post-release. + +There are a lot of details, so please read on. + +Prerequisites +============= + +You'll need a few things before getting started: + +* A GPG key. If the key you want to use is not your default signing key, you'll + need to add ``-u you@example.com`` to every GPG signing command below, where + ``you@example.com`` is the email address associated with the key you want to + use. You will also need to add ``-i you@example.com`` to the ``twine`` call. + +* An install of some required Python packages: + + .. code-block:: shell + + $ python -m pip install wheel twine + +* Access to Django's project on PyPI. Create a project-scoped token following + the `official documentation `_ and set up + your ``$HOME/.pypirc`` file like this: + + .. code-block:: ini + :caption: ``~/.pypirc`` + + [distutils] + index-servers = + pypi + django + + [pypi] + username = __token__ + password = # User-scoped or project-scoped token, to set as the default. + + [django] + repository = https://upload.pypi.org/legacy/ + username = __token__ + password = # A project token. + +* Access to the ``djangoproject.com`` server to upload files. + +* Access to the admin on ``djangoproject.com`` as a "Site maintainer". + +* Access to post to ``django-announce``. + +* If this is a security release, access to the pre-notification distribution + list. + +If this is your first release, you'll need to coordinate with another releaser +to get all these things lined up. + +Pre-release tasks +================= + +A few items need to be taken care of before even beginning the release process. +This stuff starts about a week before the release; most of it can be done +any time leading up to the actual release: + +#. If this is a security release, send out pre-notification **one week** before + the release. The template for that email and a list of the recipients are in + the private ``django-security`` GitHub wiki. BCC the pre-notification + recipients. Sign the email with the key you'll use for the release and + include `CVE IDs `_ (requested with Vendor: + djangoproject, Product: django) and patches for each issue being fixed. + Also, :ref:`notify django-announce ` of the upcoming + security release. + +#. As the release approaches, watch Trac to make sure no release blockers + are left for the upcoming release. + +#. Check with the other mergers to make sure they don't have any uncommitted + changes for the release. + +#. Proofread the release notes, including looking at the online version to + :ref:`catch any broken links ` or reST errors, and + make sure the release notes contain the correct date. + +#. Double-check that the release notes mention deprecation timelines + for any APIs noted as deprecated, and that they mention any changes + in Python version support. + +#. Double-check that the release notes index has a link to the notes + for the new release; this will be in ``docs/releases/index.txt``. + +#. If this is a feature release, ensure translations from Transifex have been + integrated. This is typically done by a separate translation's manager + rather than the releaser, but here are the steps. Provided you have an + account on Transifex: + + .. code-block:: shell + + $ python scripts/manage_translations.py fetch + + and then commit the changed/added files (both ``.po`` and ``.mo``). + Sometimes there are validation errors which need to be debugged, so avoid + doing this task immediately before a release is needed. + +#. :ref:`Update the django-admin manual page `: + + .. code-block:: shell + + $ cd docs + $ make man + $ man _build/man/django-admin.1 # do a quick sanity check + $ cp _build/man/django-admin.1 man/django-admin.1 + + and then commit the changed man page. + +#. If this is the alpha release of a new series, create a new stable branch + from main. For example, when releasing Django 4.2: + + .. code-block:: shell + + $ git checkout -b stable/4.2.x origin/main + $ git push origin -u stable/4.2.x:stable/4.2.x + + At the same time, update the ``django_next_version`` variable in + ``docs/conf.py`` on the stable release branch to point to the new + development version. For example, when creating ``stable/4.2.x``, set + ``django_next_version`` to ``'5.0'`` on the new branch. + +#. If this is the "dot zero" release of a new series, create a new branch from + the current stable branch in the `django-docs-translations + `_ repository. For + example, when releasing Django 4.2: + + .. code-block:: shell + + $ git checkout -b stable/4.2.x origin/stable/4.1.x + $ git push origin stable/4.2.x:stable/4.2.x + +Preparing for release +===================== + +Write the announcement blog post for the release. You can enter it into the +admin at any time and mark it as inactive. Here are a few examples: `example +security release announcement`__, `example regular release announcement`__, +`example pre-release announcement`__. + +__ https://www.djangoproject.com/weblog/2013/feb/19/security/ +__ https://www.djangoproject.com/weblog/2012/mar/23/14/ +__ https://www.djangoproject.com/weblog/2012/nov/27/15-beta-1/ + +Actually rolling the release +============================ + +OK, this is the fun part, where we actually push out a release! + +#. Check `Jenkins`__ is green for the version(s) you're putting out. You + probably shouldn't issue a release until it's green. + + __ https://djangoci.com + +#. A release always begins from a release branch, so you should make sure + you're on a stable branch and up-to-date. For example: + + .. code-block:: shell + + $ git checkout stable/4.1.x + $ git pull + +#. If this is a security release, merge the appropriate patches from + ``django-security``. Rebase these patches as necessary to make each one a + plain commit on the release branch rather than a merge commit. To ensure + this, merge them with the ``--ff-only`` flag; for example: + + .. code-block:: shell + + $ git checkout stable/4.1.x + $ git merge --ff-only security/4.1.x + + (This assumes ``security/4.1.x`` is a branch in the ``django-security`` repo + containing the necessary security patches for the next release in the 4.1 + series.) + + If git refuses to merge with ``--ff-only``, switch to the security-patch + branch and rebase it on the branch you are about to merge it into (``git + checkout security/4.1.x; git rebase stable/4.1.x``) and then switch back and + do the merge. Make sure the commit message for each security fix explains + that the commit is a security fix and that an announcement will follow + (:commit:`example security commit `). + +#. For a feature release, remove the ``UNDER DEVELOPMENT`` header at the + top of the release notes and add the release date on the next line. For a + patch release, remove the ``Expected`` prefix and update the release date, + if necessary. Make this change on all branches where the release notes for a + particular version are located. + +#. Update the version number in ``django/__init__.py`` for the release. + Please see `notes on setting the VERSION tuple`_ below for details + on ``VERSION``. + +#. If this is a pre-release package, update the "Development Status" trove + classifier in ``setup.cfg`` to reflect this. Otherwise, make sure the + classifier is set to ``Development Status :: 5 - Production/Stable``. + +#. Tag the release using ``git tag``. For example: + + .. code-block:: shell + + $ git tag --sign --message="Tag 4.1.1" 4.1.1 + + You can check your work by running ``git tag --verify ``. + +#. Push your work, including the tag: ``git push --tags``. + +#. Make sure you have an absolutely clean tree by running ``git clean -dfx``. + +#. Run ``make -f extras/Makefile`` to generate the release packages. This will + create the release packages in a ``dist/`` directory. + +#. Generate the hashes of the release packages: + + .. code-block:: shell + + $ cd dist + $ md5sum * + $ sha1sum * + $ sha256sum * + +#. Create a "checksums" file, ``Django-<>.checksum.txt`` containing + the hashes and release information. Start with this template and insert the + correct version, date, GPG key ID (from + ``gpg --list-keys --keyid-format LONG``), release manager's GitHub username, + release URL, and checksums: + + .. code-block:: text + + This file contains MD5, SHA1, and SHA256 checksums for the source-code + tarball and wheel files of Django <>, released <>. + + To use this file, you will need a working install of PGP or other + compatible public-key encryption software. You will also need to have + the Django release manager's public key in your keyring. This key has + the ID ``XXXXXXXXXXXXXXXX`` and can be imported from the MIT + keyserver, for example, if using the open-source GNU Privacy Guard + implementation of PGP: + + gpg --keyserver pgp.mit.edu --recv-key XXXXXXXXXXXXXXXX + + or via the GitHub API: + + curl https://github.com/<>.gpg | gpg --import - + + Once the key is imported, verify this file: + + gpg --verify <> + + Once you have verified this file, you can use normal MD5, SHA1, or SHA256 + checksumming applications to generate the checksums of the Django + package and compare them to the checksums listed below. + + Release packages + ================ + + https://www.djangoproject.com/m/releases/<>/<> + https://www.djangoproject.com/m/releases/<>/<> + + MD5 checksums + ============= + + <> <> + <> <> + + SHA1 checksums + ============== + + <> <> + <> <> + + SHA256 checksums + ================ + + <> <> + <> <> + +#. Sign the checksum file (``gpg --clearsign --digest-algo SHA256 + Django-.checksum.txt``). This generates a signed document, + ``Django-.checksum.txt.asc`` which you can then verify using ``gpg + --verify Django-.checksum.txt.asc``. + +If you're issuing multiple releases, repeat these steps for each release. + +Making the release(s) available to the public +============================================= + +Now you're ready to actually put the release out there. To do this: + +#. Upload the release package(s) to the djangoproject server, replacing + A.B. with the appropriate version number, e.g. 4.1 for a 4.1.x release: + + .. code-block:: shell + + $ scp Django-* djangoproject.com:/home/www/www/media/releases/A.B + + If this is the alpha release of a new series, you will need to create the + directory A.B. + +#. Upload the checksum file(s): + + .. code-block:: shell + + $ scp Django-A.B.C.checksum.txt.asc djangoproject.com:/home/www/www/media/pgp/Django-A.B.C.checksum.txt + +#. Test that the release packages install correctly using ``pip``. Here's one + method: + + .. code-block:: shell + + $ RELEASE_VERSION='4.1.1' + $ MAJOR_VERSION=`echo $RELEASE_VERSION| cut -c 1-3` + + $ python -m venv django-pip + $ . django-pip/bin/activate + $ python -m pip install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django-$RELEASE_VERSION.tar.gz + $ deactivate + $ python -m venv django-pip-wheel + $ . django-pip-wheel/bin/activate + $ python -m pip install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django-$RELEASE_VERSION-py3-none-any.whl + $ deactivate + + This just tests that the tarballs are available (i.e. redirects are up) and + that they install correctly, but it'll catch silly mistakes. + +#. Run the `confirm-release`__ build on Jenkins to verify the checksum file(s) + (e.g. use ``4.2rc1`` for + https://media.djangoproject.com/pgp/Django-4.2rc1.checksum.txt). + + __ https://djangoci.com/job/confirm-release/ + +#. Upload the release packages to PyPI (for pre-releases, only upload the wheel + file): + + .. code-block:: shell + + $ twine upload -s dist/* + +#. Go to the `Add release page in the admin`__, enter the new release number + exactly as it appears in the name of the tarball + (``Django-.tar.gz``). So for example enter "4.1.1" or "4.2rc1", + etc. If the release is part of an LTS branch, mark it so. + + __ https://www.djangoproject.com/admin/releases/release/add/ + + If this is the alpha release of a new series, also create a Release object + for the *final* release, ensuring that the *Release date* field is blank, + thus marking it as *unreleased*. For example, when creating the Release + object for ``4.2a1``, also create ``4.2`` with the Release date field blank. + +#. Make the blog post announcing the release live. + +#. For a new version release (e.g. 4.1, 4.2), update the default stable version + of the docs by flipping the ``is_default`` flag to ``True`` on the + appropriate ``DocumentRelease`` object in the ``docs.djangoproject.com`` + database (this will automatically flip it to ``False`` for all + others); you can do this using the site's admin. + + Create new ``DocumentRelease`` objects for each language that has an entry + for the previous release. Update djangoproject.com's `robots.docs.txt`__ + file by copying entries from ``manage_translations.py robots_txt`` from the + current stable branch in the ``django-docs-translations`` repository. For + example, when releasing Django 4.2: + + .. code-block:: shell + + $ git checkout stable/4.2.x + $ git pull + $ python manage_translations.py robots_txt + + __ https://github.com/django/djangoproject.com/blob/main/djangoproject/static/robots.docs.txt + +#. Post the release announcement to the |django-announce|, |django-developers|, + |django-users| mailing lists, and the Django Forum. This should include a + link to the announcement blog post. + +#. If this is a security release, send a separate email to + oss-security@lists.openwall.com. Provide a descriptive subject, for example, + "Django" plus the issue title from the release notes (including CVE ID). The + message body should include the vulnerability details, for example, the + announcement blog post text. Include a link to the announcement blog post. + +#. Add a link to the blog post in the topic of the ``#django`` IRC channel: + ``/msg chanserv TOPIC #django new topic goes here``. + +Post-release +============ + +You're almost done! All that's left to do now is: + +#. Update the ``VERSION`` tuple in ``django/__init__.py`` again, + incrementing to whatever the next expected release will be. For + example, after releasing 4.1.1, update ``VERSION`` to + ``VERSION = (4, 1, 2, 'alpha', 0)``. + +#. Add the release in `Trac's versions list`_ if necessary (and make it the + default by changing the ``default_version`` setting in the + code.djangoproject.com's `trac.ini`__, if it's a final release). The new X.Y + version should be added after the alpha release and the default version + should be updated after "dot zero" release. + + __ https://github.com/django/code.djangoproject.com/blob/main/trac-env/conf/trac.ini + +#. If this was a security release, update :doc:`/releases/security` with + details of the issues addressed. + +.. _Trac's versions list: https://code.djangoproject.com/admin/ticket/versions + +New stable branch tasks +======================= + +There are several items to do in the time following the creation of a new +stable branch (often following an alpha release). Some of these tasks don't +need to be done by the releaser. + +#. Create a new ``DocumentRelease`` object in the ``docs.djangoproject.com`` + database for the new version's docs, and update the + ``docs/fixtures/doc_releases.json`` JSON fixture, so people without access + to the production DB can still run an up-to-date copy of the docs site. + +#. Create a stub release note for the new feature version. Use the stub from + the previous feature release version or copy the contents from the previous + feature version and delete most of the contents leaving only the headings. + +#. Increase the default PBKDF2 iterations in + ``django.contrib.auth.hashers.PBKDF2PasswordHasher`` by about 20% + (pick a round number). Run the tests, and update the 3 failing + hasher tests with the new values. Make sure this gets noted in the + release notes (see the 4.1 release notes for an example). + +#. Remove features that have reached the end of their deprecation cycle. Each + removal should be done in a separate commit for clarity. In the commit + message, add a "refs #XXXX" to the original ticket where the deprecation + began if possible. + +#. Remove ``.. versionadded::``, ``.. versionadded::``, and ``.. deprecated::`` + annotations in the documentation from two releases ago. For example, in + Django 4.2, notes for 4.0 will be removed. + +#. Add the new branch to `Read the Docs + `_. Since the automatically + generated version names ("stable-A.B.x") differ from the version names + used in Read the Docs ("A.B.x"), `create a ticket + `_ requesting + the new version. + +#. `Request the new classifier on PyPI + `_. For example + ``Framework :: Django :: 3.1``. + +Notes on setting the VERSION tuple +================================== + +Django's version reporting is controlled by the ``VERSION`` tuple in +``django/__init__.py``. This is a five-element tuple, whose elements +are: + +#. Major version. +#. Minor version. +#. Micro version. +#. Status -- can be one of "alpha", "beta", "rc" or "final". +#. Series number, for alpha/beta/RC packages which run in sequence + (allowing, for example, "beta 1", "beta 2", etc.). + +For a final release, the status is always "final" and the series +number is always 0. A series number of 0 with an "alpha" status will +be reported as "pre-alpha". + +Some examples: + +* ``(4, 1, 1, "final", 0)`` → "4.1.1" + +* ``(4, 2, 0, "alpha", 0)`` → "4.2 pre-alpha" + +* ``(4, 2, 0, "beta", 1)`` → "4.2 beta 1" diff --git a/testbed/django__django/docs/internals/index.txt b/testbed/django__django/docs/internals/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..b76696abb59ec63d71df9eeccf312034d4a4409d --- /dev/null +++ b/testbed/django__django/docs/internals/index.txt @@ -0,0 +1,18 @@ +================ +Django internals +================ + +Documentation for people hacking on Django itself. This is the place to go if +you'd like to help improve Django or learn about how Django is managed. + +.. toctree:: + :maxdepth: 2 + + contributing/index + mailing-lists + organization + security + release-process + deprecation + git + howto-release-django diff --git a/testbed/django__django/docs/internals/mailing-lists.txt b/testbed/django__django/docs/internals/mailing-lists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7ec4972d6e94983e55973381e6cd609552a3c299 --- /dev/null +++ b/testbed/django__django/docs/internals/mailing-lists.txt @@ -0,0 +1,118 @@ +======================= +Mailing lists and Forum +======================= + +.. Important:: + + Please report security issues **only** to + security@djangoproject.com. This is a private list only open to + long-time, highly trusted Django developers, and its archives are + not public. For further details, please see :doc:`our security + policies `. + +Django Forum +============ + +Django has an `official Forum`_ where you can input and ask questions. + +There are several categories of discussion including: + +* `Using Django`_: to ask any question regarding the installation, usage, or + debugging of Django. +* `Internals`_: for discussion of the development of Django itself. + +.. _official Forum: https://forum.djangoproject.com +.. _Internals: https://forum.djangoproject.com/c/internals/5 +.. _Using Django: https://forum.djangoproject.com/c/users/6 + +In addition, Django has several official mailing lists on Google Groups that +are open to anyone. + +.. _django-users-mailing-list: + +``django-users`` +================ + +.. note:: + + The `Using Django`_ category of the `official Forum`_ is now the preferred + venue for asking usage questions. + +This is the right place if you are looking to ask any question regarding the +installation, usage, or debugging of Django. + +.. note:: + + If it's the first time you send an email to this list, your email must be + accepted first so don't worry if :ref:`your message does not appear + ` instantly. + +* `django-users mailing archive`_ +* `django-users subscription email address`_ +* `django-users posting email`_ + +.. _django-users mailing archive: https://groups.google.com/g/django-users +.. _django-users subscription email address: mailto:django-users+subscribe@googlegroups.com +.. _django-users posting email: mailto:django-users@googlegroups.com + +.. _django-developers-mailing-list: + +``django-developers`` +===================== + +.. note:: + + The `Internals`_ category of the `official Forum`_ is now the preferred + venue for discussing the development of Django. + +The discussion about the development of Django itself takes place here. + +Before asking a question about how to contribute, read +:doc:`/internals/contributing/index`. Many frequently asked questions are +answered there. + +.. note:: + + Please make use of + :ref:`django-users mailing list ` if you want + to ask for tech support, doing so in this list is inappropriate. + +* `django-developers mailing archive`_ +* `django-developers subscription email address`_ +* `django-developers posting email`_ + +.. _django-developers mailing archive: https://groups.google.com/g/django-developers +.. _django-developers subscription email address: mailto:django-developers+subscribe@googlegroups.com +.. _django-developers posting email: mailto:django-developers@googlegroups.com + +.. _django-announce-mailing-list: + +``django-announce`` +=================== + +A (very) low-traffic list for announcing :ref:`upcoming security releases +`, new releases of Django, and security advisories. + +* `django-announce mailing archive`_ +* `django-announce subscription email address`_ +* `django-announce posting email`_ + +.. _django-announce mailing archive: https://groups.google.com/g/django-announce +.. _django-announce subscription email address: mailto:django-announce+subscribe@googlegroups.com +.. _django-announce posting email: mailto:django-announce@googlegroups.com + +.. _django-updates-mailing-list: + +``django-updates`` +================== + +All the ticket updates are mailed automatically to this list, which is tracked +by developers and interested community members. + +* `django-updates mailing archive`_ +* `django-updates subscription email address`_ +* `django-updates posting email`_ + +.. _django-updates mailing archive: https://groups.google.com/g/django-updates +.. _django-updates subscription email address: mailto:django-updates+subscribe@googlegroups.com +.. _django-updates posting email: mailto:django-updates@googlegroups.com diff --git a/testbed/django__django/docs/internals/organization.txt b/testbed/django__django/docs/internals/organization.txt new file mode 100644 index 0000000000000000000000000000000000000000..5fd8115b5a331bf5b85ea3f148f6de64c748dbe3 --- /dev/null +++ b/testbed/django__django/docs/internals/organization.txt @@ -0,0 +1,297 @@ +================================== +Organization of the Django Project +================================== + +Principles +========== + +The Django Project is managed by a team of volunteers pursuing three goals: + +- Driving the development of the Django web framework, +- Fostering the ecosystem of Django-related software, +- Leading the Django community in accordance with the values described in the + `Django Code of Conduct`_. + +The Django Project isn't a legal entity. The `Django Software Foundation`_, a +non-profit organization, handles financial and legal matters related to the +Django Project. Other than that, the Django Software Foundation lets the +Django Project manage the development of the Django framework, its ecosystem +and its community. + +.. _Django Code of Conduct: https://www.djangoproject.com/conduct/ +.. _Django Software Foundation: https://www.djangoproject.com/foundation/ + +.. _mergers-team: + +Mergers +======= + +Role +---- + +Mergers_ are a small set of people who merge pull requests to the `Django Git +repository`_. + +Prerogatives +------------ + +Mergers hold the following prerogatives: + +- Merging any pull request which constitutes a `minor change`_ (small enough + not to require the use of the `DEP process`_). A Merger must not merge a + change primarily authored by that Merger, unless the pull request has been + approved by: + + - another Merger, + - a steering council member, + - a member of the `triage & review team`_, or + - a member of the `security team`_. + +- Initiating discussion of a minor change in the appropriate venue, and request + that other Mergers refrain from merging it while discussion proceeds. +- Requesting a vote of the steering council regarding any minor change if, in + the Merger's opinion, discussion has failed to reach a consensus. +- Requesting a vote of the steering council when a `major change`_ (significant + enough to require the use of the `DEP process`_) reaches one of its + implementation milestones and is intended to merge. + +.. _`minor change`: https://github.com/django/deps/blob/main/accepted/0010-new-governance.rst#terminology +.. _`major change`: https://github.com/django/deps/blob/main/accepted/0010-new-governance.rst#terminology + +Membership +---------- + +`The steering council`_ selects Mergers_ as necessary to maintain their number +at a minimum of three, in order to spread the workload and avoid over-burdening +or burning out any individual Merger. There is no upper limit to the number of +Mergers. + +It's not a requirement that a Merger is also a Django Fellow, but the Django +Software Foundation has the power to use funding of Fellow positions as a way +to make the role of Merger sustainable. + +The following restrictions apply to the role of Merger: + +- A person must not simultaneously serve as a member of the steering council. If + a Merger is elected to the steering council, they shall cease to be a Merger + immediately upon taking up membership in the steering council. +- A person may serve in the roles of Releaser and Merger simultaneously. + +The selection process, when a vacancy occurs or when the steering council deems +it necessary to select additional persons for such a role, occur as follows: + +- Any member in good standing of an appropriate discussion venue, or the Django + Software Foundation board acting with the input of the DSF's Fellowship + committee, may suggest a person for consideration. +- The steering council considers the suggestions put forth, and then any member + of the steering council formally nominates a candidate for the role. +- The steering council votes on nominees. + +Mergers may resign their role at any time, but should endeavor to provide some +advance notice in order to allow the selection of a replacement. Termination of +the contract of a Django Fellow by the Django Software Foundation temporarily +suspends that person's Merger role until such time as the steering council can +vote on their nomination. + +Otherwise, a Merger may be removed by: + +- Becoming disqualified due to election to the steering council. +- Becoming disqualified due to actions taken by the Code of Conduct committee + of the Django Software Foundation. +- A vote of the steering council. + +.. _releasers-team: + +Releasers +========= + +Role +---- + +Releasers_ are a small set of people who have the authority to upload packaged +releases of Django to the :pypi:`Python Package Index ` and to the +`djangoproject.com`_ website. + +Prerogatives +------------ + +Releasers_ :doc:`build Django releases ` and +upload them to the :pypi:`Python Package Index ` and to the +`djangoproject.com`_ website. + +Membership +---------- + +`The steering council`_ selects Releasers_ as necessary to maintain their number +at a minimum of three, in order to spread the workload and avoid over-burdening +or burning out any individual Releaser. There is no upper limit to the number +of Releasers. + +It's not a requirement that a Releaser is also a Django Fellow, but the Django +Software Foundation has the power to use funding of Fellow positions as a way +to make the role of Releaser sustainable. + +A person may serve in the roles of Releaser and Merger simultaneously. + +The selection process, when a vacancy occurs or when the steering council deems +it necessary to select additional persons for such a role, occur as follows: + +- Any member in good standing of an appropriate discussion venue, or the Django + Software Foundation board acting with the input of the DSF's Fellowship + committee, may suggest a person for consideration. +- The steering council considers the suggestions put forth, and then any member + of the steering council formally nominates a candidate for the role. +- The steering council votes on nominees. + +Releasers may resign their role at any time, but should endeavor to provide +some advance notice in order to allow the selection of a replacement. +Termination of the contract of a Django Fellow by the Django Software +Foundation temporarily suspends that person's Releaser role until such time as +the steering council can vote on their nomination. + +Otherwise, a Releaser may be removed by: + +- Becoming disqualified due to actions taken by the Code of Conduct committee + of the Django Software Foundation. +- A vote of the steering council. + +.. _djangoproject.com: https://www.djangoproject.com/download/ + +.. _steering-council: + +Steering council +================ + +Role +---- + +The steering council is a group of experienced contributors who: + +- provide oversight of Django's development and release process, +- assist in setting the direction of feature development and releases, +- take part in filling certain roles, and +- have a tie-breaking vote when other decision-making processes fail. + +Their main concern is to maintain the quality and stability of the Django Web +Framework. + +Prerogatives +------------ + +The steering council holds the following prerogatives: + +- Making a binding decision regarding any question of a technical change to + Django. +- Vetoing the merging of any particular piece of code into Django or ordering + the reversion of any particular merge or commit. +- Announcing calls for proposals and ideas for the future technical direction + of Django. +- Setting and adjusting the schedule of releases of Django. +- Selecting and removing mergers and releasers. +- Participating in the removal of members of the steering council, when deemed + appropriate. +- Calling elections of the steering council outside of those which are + automatically triggered, at times when the steering council deems an election + is appropriate. +- Participating in modifying Django's governance (see + :ref:`organization-change`). +- Declining to vote on a matter the steering council feels is unripe for a + binding decision, or which the steering council feels is outside the scope of + its powers. +- Taking charge of the governance of other technical teams within the Django + open-source project, and governing those teams accordingly. + +Membership +---------- + +`The steering council`_ is an elected group of five experienced contributors +who demonstrate: + +- A history of substantive contributions to Django or the Django ecosystem. + This history must begin at least 18 months prior to the individual's + candidacy for the Steering Council, and include substantive contributions in + at least two of these bullet points: + - Code contributions on Django projects or major third-party packages in the Django ecosystem + - Reviewing pull requests and/or triaging Django project tickets + - Documentation, tutorials or blog posts + - Discussions about Django on the django-developers mailing list or the Django Forum + - Running Django-related events or user groups + +- A history of engagement with the direction and future of Django. This does + not need to be recent, but candidates who have not engaged in the past three + years must still demonstrate an understanding of Django's changes and + direction within those three years. + +A new council is elected after each release cycle of Django. The election process +works as follows: + +#. The steering council directs one of its members to notify the Secretary of the + Django Software Foundation, in writing, of the triggering of the election, + and the condition which triggered it. The Secretary post to the appropriate + venue -- the |django-developers| mailing list and the `Django forum`_ to + announce the election and its timeline. +#. As soon as the election is announced, the `DSF Board`_ begin a period of + voter registration. All `individual members of the DSF`_ are automatically + registered and need not explicitly register. All other persons who believe + themselves eligible to vote, but who have not yet registered to vote, may + make an application to the DSF Board for voting privileges. The voter + registration form and roll of voters is maintained by the DSF Board. The DSF + Board may challenge and reject the registration of voters it believes are + registering in bad faith or who it believes have falsified their + qualifications or are otherwise unqualified. +#. Registration of voters close one week after the announcement of the + election. At that point, registration of candidates begin. Any qualified + person may register as a candidate. The candidate registration form and + roster of candidates are maintained by the DSF Board, and candidates must + provide evidence of their qualifications as part of registration. The DSF + Board may challenge and reject the registration of candidates it believes do + not meet the qualifications of members of the Steering Council, or who it + believes are registering in bad faith. +#. Registration of candidates close one week after it has opened. One week + after registration of candidates closes, the Secretary of the DSF publish + the roster of candidates to the |django-developers| mailing list and the + `Django forum`_, and the election begin. The DSF Board provide a voting form + accessible to registered voters, and is the custodian of the votes. +#. Voting is by secret ballot containing the roster of candidates, and any + relevant materials regarding the candidates, in a randomized order. Each + voter may vote for up to five candidates on the ballot. +#. The election conclude one week after it begins. The DSF Board then tally the + votes and produce a summary, including the total number of votes cast and + the number received by each candidate. This summary is ratified by a + majority vote of the DSF Board, then posted by the Secretary of the DSF to + the |django-developers| mailing list and the Django Forum. The five + candidates with the highest vote totals are immediately become the new + steering council. + +A member of the steering council may be removed by: + +- Becoming disqualified due to actions taken by the Code of Conduct committee + of the Django Software Foundation. +- Determining that they did not possess the qualifications of a member of the + steering council. This determination must be made jointly by the other members + of the steering council, and the `DSF Board`_. A valid determination of + ineligibility requires that all other members of the steering council and all + members of the DSF Board vote who can vote on the issue (the affected person, + if a DSF Board member, must not vote) vote "yes" on a motion that the person + in question is ineligible. + +.. _`Django forum`: https://forum.djangoproject.com/ +.. _`Django Git repository`: https://github.com/django/django/ +.. _`DSF Board`: https://www.djangoproject.com/foundation/#board +.. _`individual members of the DSF`: https://www.djangoproject.com/foundation/individual-members/ +.. _mergers: https://www.djangoproject.com/foundation/teams/#mergers-team +.. _releasers: https://www.djangoproject.com/foundation/teams/#releasers-team +.. _`security team`: https://www.djangoproject.com/foundation/teams/#security-team +.. _`the steering council`: https://www.djangoproject.com/foundation/teams/#steering-council-team +.. _`triage & review team`: https://www.djangoproject.com/foundation/teams/#triage-review-team + +.. _organization-change: + +Changing the organization +========================= + +Changes to this document require the use of the `DEP process`_, with +modifications described in `DEP 0010`_. + +.. _`DEP process`: https://github.com/django/deps/blob/main/final/0001-dep-process.rst +.. _`DEP 0010`: https://github.com/django/deps/blob/main/accepted/0010-new-governance.rst#changing-this-governance-process diff --git a/testbed/django__django/docs/internals/release-process.txt b/testbed/django__django/docs/internals/release-process.txt new file mode 100644 index 0000000000000000000000000000000000000000..a845faf3307051f9e96c0323f88032fd86fe9367 --- /dev/null +++ b/testbed/django__django/docs/internals/release-process.txt @@ -0,0 +1,246 @@ +======================== +Django's release process +======================== + +.. _official-releases: + +Official releases +================= + +Since version 1.0, Django's release numbering works as follows: + +* Versions are numbered in the form ``A.B`` or ``A.B.C``. + +* ``A.B`` is the *feature release* version number. Each version will be mostly + backwards compatible with the previous release. Exceptions to this rule will + be listed in the release notes. + +* ``C`` is the *patch release* version number, which is incremented for bugfix + and security releases. These releases will be 100% backwards-compatible with + the previous patch release. The only exception is when a security or data + loss issue can't be fixed without breaking backwards-compatibility. If this + happens, the release notes will provide detailed upgrade instructions. + +* Before a new feature release, we'll make alpha, beta, and release candidate + releases. These are of the form ``A.B alpha/beta/rc N``, which means the + ``Nth`` alpha/beta/release candidate of version ``A.B``. + +In git, each Django release will have a tag indicating its version number, +signed with the Django release key. Additionally, each release series has its +own branch, called ``stable/A.B.x``, and bugfix/security releases will be +issued from those branches. + +For more information about how the Django project issues new releases for +security purposes, please see :doc:`our security policies `. + +.. glossary:: + + Feature release + Feature releases (A.B, A.B+1, etc.) will happen roughly every eight months + -- see `release process`_ for details. These releases will contain new + features, improvements to existing features, and such. + + Patch release + Patch releases (A.B.C, A.B.C+1, etc.) will be issued as needed, to fix + bugs and/or security issues. + + These releases will be 100% compatible with the associated feature release, + unless this is impossible for security reasons or to prevent data loss. + So the answer to "should I upgrade to the latest patch release?" will always + be "yes." + + Long-term support release + Certain feature releases will be designated as long-term support (LTS) + releases. These releases will get security and data loss fixes applied for + a guaranteed period of time, typically three years. + + See `the download page`_ for the releases that have been designated for + long-term support. + + .. _the download page: https://www.djangoproject.com/download/ + +.. _internal-release-cadence: + +Release cadence +=============== + +Starting with Django 2.0, version numbers will use a loose form of `semantic +versioning `_ such that each version following an LTS will +bump to the next "dot zero" version. For example: 2.0, 2.1, 2.2 (LTS), 3.0, +3.1, 3.2 (LTS), etc. + +SemVer makes it easier to see at a glance how compatible releases are with each +other. It also helps to anticipate when compatibility shims will be removed. +It's not a pure form of SemVer as each feature release will continue to have a +few documented backwards incompatibilities where a deprecation path isn't +possible or not worth the cost. Also, deprecations started in an LTS release +(X.2) will be dropped in a non-dot-zero release (Y.1) to accommodate our policy +of keeping deprecation shims for at least two feature releases. Read on to the +next section for an example. + +.. _internal-release-deprecation-policy: + +Deprecation policy +================== + +A feature release may deprecate certain features from previous releases. If a +feature is deprecated in feature release A.x, it will continue to work in all +A.x versions (for all versions of x) but raise warnings. Deprecated features +will be removed in the B.0 release, or B.1 for features deprecated in the last +A.x feature release to ensure deprecations are done over at least 2 feature +releases. + +So, for example, if we decided to start the deprecation of a function in +Django 4.2: + +* Django 4.2 will contain a backwards-compatible replica of the function which + will raise a ``RemovedInDjango51Warning``. + +* Django 5.0 (the version that follows 4.2) will still contain the + backwards-compatible replica. + +* Django 5.1 will remove the feature outright. + +The warnings are silent by default. You can turn on display of these warnings +with the ``python -Wd`` option. + +A more generic example: + +* X.0 +* X.1 +* X.2 LTS +* Y.0: Drop deprecation shims added in X.0 and X.1. +* Y.1: Drop deprecation shims added in X.2. +* Y.2 LTS: No deprecation shims dropped (while Y.0 is no longer supported, + third-party apps need to maintain compatibility back to X.2 LTS to ease + LTS to LTS upgrades). +* Z.0: Drop deprecation shims added in Y.0 and Y.1. + +See also the :ref:`deprecating-a-feature` guide. + +.. _supported-versions-policy: + +Supported versions +================== + +At any moment in time, Django's developer team will support a set of releases to +varying levels. See `the supported versions section +`_ of the download +page for the current state of support for each version. + +* The current development branch ``main`` will get new features and bug fixes + requiring non-trivial refactoring. + +* Patches applied to the main branch must also be applied to the last feature + release branch, to be released in the next patch release of that feature + series, when they fix critical problems: + + * Security issues. + + * Data loss bugs. + + * Crashing bugs. + + * Major functionality bugs in new features of the latest stable release. + + * Regressions from older versions of Django introduced in the current release + series. + + The rule of thumb is that fixes will be backported to the last feature + release for bugs that would have prevented a release in the first place + (release blockers). + +* Security fixes and data loss bugs will be applied to the current main branch, + the last two feature release branches, and any other supported long-term + support release branches. + +* Documentation fixes generally will be more freely backported to the last + release branch. That's because it's highly advantageous to have the docs for + the last release be up-to-date and correct, and the risk of introducing + regressions is much less of a concern. + +As a concrete example, consider a moment in time halfway between the release of +Django 5.1 and 5.2. At this point in time: + +* Features will be added to the development main branch, to be released as + Django 5.2. + +* Critical bug fixes will be applied to the ``stable/5.1.x`` branch, and + released as 5.1.1, 5.1.2, etc. + +* Security fixes and bug fixes for data loss issues will be applied to + ``main`` and to the ``stable/5.1.x``, ``stable/5.0.x``, and + ``stable/4.2.x`` (LTS) branches. They will trigger the release of ``5.1.1``, + ``5.0.5``, ``4.2.8``, etc. + +* Documentation fixes will be applied to main, and, if easily backported, to + the latest stable branch, ``5.1.x``. + +.. _release-process: + +Release process +=============== + +Django uses a time-based release schedule, with feature releases every eight +months or so. + +After each feature release, the release manager will announce a timeline for +the next feature release. + +Release cycle +------------- + +Each release cycle consists of three parts: + +Phase one: feature proposal +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The first phase of the release process will include figuring out what major +features to include in the next version. This should include a good deal of +preliminary work on those features -- working code trumps grand design. + +Major features for an upcoming release will be added to the wiki roadmap page, +e.g. https://code.djangoproject.com/wiki/Version1.11Roadmap. + +Phase two: development +~~~~~~~~~~~~~~~~~~~~~~ + +The second part of the release schedule is the "heads-down" working period. +Using the roadmap produced at the end of phase one, we'll all work very hard to +get everything on it done. + +At the end of phase two, any unfinished features will be postponed until the +next release. + +Phase two will culminate with an alpha release. At this point, the +``stable/A.B.x`` branch will be forked from ``main``. + +Phase three: bugfixes +~~~~~~~~~~~~~~~~~~~~~ + +The last part of a release cycle is spent fixing bugs -- no new features will +be accepted during this time. We'll try to release a beta release one month +after the alpha and a release candidate one month after the beta. + +The release candidate marks the string freeze, and it happens at least two +weeks before the final release. After this point, new translatable strings +must not be added. + +During this phase, mergers will be more and more conservative with backports, +to avoid introducing regressions. After the release candidate, only release +blockers and documentation fixes should be backported. + +In parallel to this phase, ``main`` can receive new features, to be released +in the ``A.B+1`` cycle. + +Bug-fix releases +---------------- + +After a feature release (e.g. A.B), the previous release will go into bugfix +mode. + +The branch for the previous feature release (e.g. ``stable/A.B-1.x``) will +include bugfixes. Critical bugs fixed on main must *also* be fixed on the +bugfix branch; this means that commits need to cleanly separate bug fixes from +feature additions. The developer who commits a fix to main will be +responsible for also applying the fix to the current bugfix branch. diff --git a/testbed/django__django/docs/internals/security.txt b/testbed/django__django/docs/internals/security.txt new file mode 100644 index 0000000000000000000000000000000000000000..373012b707e5e952058d63cf4971dd6c15cc9dc9 --- /dev/null +++ b/testbed/django__django/docs/internals/security.txt @@ -0,0 +1,248 @@ +========================== +Django's security policies +========================== + +Django's development team is strongly committed to responsible +reporting and disclosure of security-related issues. As such, we've +adopted and follow a set of policies which conform to that ideal and +are geared toward allowing us to deliver timely security updates to +the official distribution of Django, as well as to third-party +distributions. + +.. _reporting-security-issues: + +Reporting security issues +========================= + +**Short version: please report security issues by emailing +security@djangoproject.com**. + +Most normal bugs in Django are reported to `our public Trac instance`_, but +due to the sensitive nature of security issues, we ask that they **not** be +publicly reported in this fashion. + +Instead, if you believe you've found something in Django which has security +implications, please send a description of the issue via email to +``security@djangoproject.com``. Mail sent to that address reaches the `security +team `_. + +Once you've submitted an issue via email, you should receive an acknowledgment +from a member of the security team within 48 hours, and depending on the +action to be taken, you may receive further followup emails. + +.. admonition:: Sending encrypted reports + + If you want to send an encrypted email (*optional*), the public key ID for + ``security@djangoproject.com`` is ``0xfcb84b8d1d17f80b``, and this public + key is available from most commonly-used keyservers. + +.. _our public Trac instance: https://code.djangoproject.com/query + +.. _security-support: + +Supported versions +================== + +At any given time, the Django team provides official security support +for several versions of Django: + +* The `main development branch`_, hosted on GitHub, which will become the + next major release of Django, receives security support. Security issues that + only affect the main development branch and not any stable released versions + are fixed in public without going through the :ref:`disclosure process + `. + +* The two most recent Django release series receive security + support. For example, during the development cycle leading to the + release of Django 1.5, support will be provided for Django 1.4 and + Django 1.3. Upon the release of Django 1.5, Django 1.3's security + support will end. + +* :term:`Long-term support release`\s will receive security updates for a + specified period. + +When new releases are issued for security reasons, the accompanying +notice will include a list of affected versions. This list is +comprised solely of *supported* versions of Django: older versions may +also be affected, but we do not investigate to determine that, and +will not issue patches or new releases for those versions. + +.. _main development branch: https://github.com/django/django/ + +.. _security-disclosure: + +How Django discloses security issues +==================================== + +Our process for taking a security issue from private discussion to +public disclosure involves multiple steps. + +Approximately one week before public disclosure, we send two notifications: + +First, we notify |django-announce| of the date and approximate time of the +upcoming security release, as well as the severity of the issues. This is to +aid organizations that need to ensure they have staff available to handle +triaging our announcement and upgrade Django as needed. Severity levels are: + +**High**: + +* Remote code execution +* SQL injection + +**Moderate**: + +* Cross site scripting (XSS) +* Cross site request forgery (CSRF) +* Denial-of-service attacks +* Broken authentication + +**Low**: + +* Sensitive data exposure +* Broken session management +* Unvalidated redirects/forwards +* Issues requiring an uncommon configuration option + +Second, we notify a list of :ref:`people and organizations +`, primarily composed of operating-system vendors and +other distributors of Django. This email is signed with the PGP key of someone +from `Django's release team`_ and consists of: + +* A full description of the issue and the affected versions of Django. + +* The steps we will be taking to remedy the issue. + +* The patch(es), if any, that will be applied to Django. + +* The date on which the Django team will apply these patches, issue + new releases and publicly disclose the issue. + +On the day of disclosure, we will take the following steps: + +#. Apply the relevant patch(es) to Django's codebase. + +#. Issue the relevant release(s), by placing new packages on the :pypi:`Python + Package Index ` and on the `djangoproject.com website + `_, and tagging the new release(s) + in Django's git repository. + +#. Post a public entry on `the official Django development blog`_, + describing the issue and its resolution in detail, pointing to the + relevant patches and new releases, and crediting the reporter of + the issue (if the reporter wishes to be publicly identified). + +#. Post a notice to the |django-announce| and oss-security@lists.openwall.com + mailing lists that links to the blog post. + +.. _the official Django development blog: https://www.djangoproject.com/weblog/ + +If a reported issue is believed to be particularly time-sensitive -- +due to a known exploit in the wild, for example -- the time between +advance notification and public disclosure may be shortened +considerably. + +Additionally, if we have reason to believe that an issue reported to +us affects other frameworks or tools in the Python/web ecosystem, we +may privately contact and discuss those issues with the appropriate +maintainers, and coordinate our own disclosure and resolution with +theirs. + +The Django team also maintains an :doc:`archive of security issues +disclosed in Django`. + +.. _Django's release team: https://www.djangoproject.com/foundation/teams/#releasers-team + +.. _security-notifications: + +Who receives advance notification +================================= + +The full list of people and organizations who receive advance +notification of security issues is not and will not be made public. + +We also aim to keep this list as small as effectively possible, in +order to better manage the flow of confidential information prior to +disclosure. As such, our notification list is *not* simply a list of +users of Django, and being a user of Django is not sufficient reason +to be placed on the notification list. + +In broad terms, recipients of security notifications fall into three +groups: + +1. Operating-system vendors and other distributors of Django who + provide a suitably-generic (i.e., *not* an individual's personal + email address) contact address for reporting issues with their + Django package, or for general security reporting. In either case, + such addresses **must not** forward to public mailing lists or bug + trackers. Addresses which forward to the private email of an + individual maintainer or security-response contact are acceptable, + although private security trackers or security-response groups are + strongly preferred. + +2. On a case-by-case basis, individual package maintainers who have + demonstrated a commitment to responding to and responsibly acting + on these notifications. + +3. On a case-by-case basis, other entities who, in the judgment of the + Django development team, need to be made aware of a pending + security issue. Typically, membership in this group will consist of + some of the largest and/or most likely to be severely impacted + known users or distributors of Django, and will require a + demonstrated ability to responsibly receive, keep confidential and + act on these notifications. + +.. admonition:: Security audit and scanning entities + + As a policy, we do not add these types of entities to the notification + list. + +Requesting notifications +======================== + +If you believe that you, or an organization you are authorized to +represent, fall into one of the groups listed above, you can ask to be +added to Django's notification list by emailing +``security@djangoproject.com``. Please use the subject line "Security +notification request". + +Your request **must** include the following information: + +* Your full, real name and the name of the organization you represent, + if applicable, as well as your role within that organization. + +* A detailed explanation of how you or your organization fit at least + one set of criteria listed above. + +* A detailed explanation of why you are requesting security notifications. + Again, please keep in mind that this is *not* simply a list for users of + Django, and the overwhelming majority of users should subscribe to + |django-announce| to receive advanced notice of when a security release will + happen, without the details of the issues, rather than request detailed + notifications. + +* The email address you would like to have added to our notification + list. + +* An explanation of who will be receiving/reviewing mail sent to that + address, as well as information regarding any automated actions that + will be taken (i.e., filing of a confidential issue in a bug + tracker). + +* For individuals, the ID of a public key associated with your address + which can be used to verify email received from you and encrypt + email sent to you, as needed. + +Once submitted, your request will be considered by the Django +development team; you will receive a reply notifying you of the result +of your request within 30 days. + +Please also bear in mind that for any individual or organization, +receiving security notifications is a privilege granted at the sole +discretion of the Django development team, and that this privilege can +be revoked at any time, with or without explanation. + +.. admonition:: Provide all required information + + A failure to provide the required information in your initial contact + will count against you when making the decision on whether or not to + approve your request. diff --git a/testbed/django__django/docs/intro/contributing.txt b/testbed/django__django/docs/intro/contributing.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9b5734569c59fae261261b882278d0bb51b805b --- /dev/null +++ b/testbed/django__django/docs/intro/contributing.txt @@ -0,0 +1,625 @@ +=================================== +Writing your first patch for Django +=================================== + +Introduction +============ + +Interested in giving back to the community a little? Maybe you've found a bug +in Django that you'd like to see fixed, or maybe there's a small feature you +want added. + +Contributing back to Django itself is the best way to see your own concerns +addressed. This may seem daunting at first, but it's a well-traveled path with +documentation, tooling, and a community to support you. We'll walk you through +the entire process, so you can learn by example. + +Who's this tutorial for? +------------------------ + +.. seealso:: + + If you are looking for a reference on the details of making code + contributions, see the :doc:`/internals/contributing/writing-code/index` + documentation. + +For this tutorial, we expect that you have at least a basic understanding of +how Django works. This means you should be comfortable going through the +existing tutorials on :doc:`writing your first Django app`. +In addition, you should have a good understanding of Python itself. But if you +don't, `Dive Into Python`__ is a fantastic (and free) online book for +beginning Python programmers. + +Those of you who are unfamiliar with version control systems and Trac will find +that this tutorial and its links include just enough information to get started. +However, you'll probably want to read some more about these different tools if +you plan on contributing to Django regularly. + +For the most part though, this tutorial tries to explain as much as possible, +so that it can be of use to the widest audience. + +.. admonition:: Where to get help: + + If you're having trouble going through this tutorial, please post a message + on the `Django Forum`_, |django-developers|, or drop by + `#django-dev on irc.libera.chat`__ to chat with other Django users who + might be able to help. + +__ https://diveinto.org/python3/table-of-contents.html +__ https://web.libera.chat/#django-dev +.. _Django Forum: https://forum.djangoproject.com/ + +What does this tutorial cover? +------------------------------ + +We'll be walking you through contributing a patch to Django for the first time. +By the end of this tutorial, you should have a basic understanding of both the +tools and the processes involved. Specifically, we'll be covering the following: + +* Installing Git. +* Downloading a copy of Django's development version. +* Running Django's test suite. +* Writing a test for your patch. +* Writing the code for your patch. +* Testing your patch. +* Submitting a pull request. +* Where to look for more information. + +Once you're done with the tutorial, you can look through the rest of +:doc:`Django's documentation on contributing`. +It contains lots of great information and is a must read for anyone who'd like +to become a regular contributor to Django. If you've got questions, it's +probably got the answers. + +.. admonition:: Python 3 required! + + The current version of Django doesn't support Python 2.7. Get Python 3 at + `Python's download page `_ or with your + operating system's package manager. + +.. admonition:: For Windows users + + See :ref:`install_python_windows` on Windows docs for additional guidance. + +Code of Conduct +=============== + +As a contributor, you can help us keep the Django community open and inclusive. +Please read and follow our `Code of Conduct `_. + +Installing Git +============== + +For this tutorial, you'll need Git installed to download the current +development version of Django and to generate patch files for the changes you +make. + +To check whether or not you have Git installed, enter ``git`` into the command +line. If you get messages saying that this command could not be found, you'll +have to download and install it, see `Git's download page`__. + +If you're not that familiar with Git, you can always find out more about its +commands (once it's installed) by typing ``git help`` into the command line. + +__ https://git-scm.com/download + +Getting a copy of Django's development version +============================================== + +The first step to contributing to Django is to get a copy of the source code. +First, `fork Django on GitHub `__. Then, +from the command line, use the ``cd`` command to navigate to the directory +where you'll want your local copy of Django to live. + +Download the Django source code repository using the following command: + +.. console:: + + $ git clone https://github.com/YourGitHubName/django.git + +.. admonition:: Low bandwidth connection? + + You can add the ``--depth 1`` argument to ``git clone`` to skip downloading + all of Django's commit history, which reduces data transfer from ~250 MB + to ~70 MB. + +Now that you have a local copy of Django, you can install it just like you would +install any package using ``pip``. The most convenient way to do so is by using +a *virtual environment*, which is a feature built into Python that allows you +to keep a separate directory of installed packages for each of your projects so +that they don't interfere with each other. + +It's a good idea to keep all your virtual environments in one place, for +example in ``.virtualenvs/`` in your home directory. + +Create a new virtual environment by running: + +.. console:: + + $ python3 -m venv ~/.virtualenvs/djangodev + +The path is where the new environment will be saved on your computer. + +The final step in setting up your virtual environment is to activate it: + +.. code-block:: console + + $ source ~/.virtualenvs/djangodev/bin/activate + +If the ``source`` command is not available, you can try using a dot instead: + +.. code-block:: console + + $ . ~/.virtualenvs/djangodev/bin/activate + +You have to activate the virtual environment whenever you open a new +terminal window. + +.. admonition:: For Windows users + + To activate your virtual environment on Windows, run: + + .. code-block:: doscon + + ...\> %HOMEPATH%\.virtualenvs\djangodev\Scripts\activate.bat + +The name of the currently activated virtual environment is displayed on the +command line to help you keep track of which one you are using. Anything you +install through ``pip`` while this name is displayed will be installed in that +virtual environment, isolated from other environments and system-wide packages. + +.. _intro-contributing-install-local-copy: + +Go ahead and install the previously cloned copy of Django: + +.. console:: + + $ python -m pip install -e /path/to/your/local/clone/django/ + +The installed version of Django is now pointing at your local copy by installing +in editable mode. You will immediately see any changes you make to it, which is +of great help when writing your first patch. + +Creating projects with a local copy of Django +--------------------------------------------- + +It may be helpful to test your local changes with a Django project. First you +have to create a new virtual environment, :ref:`install the previously cloned +local copy of Django in editable mode `, +and create a new Django project outside of your local copy of Django. You will +immediately see any changes you make to Django in your new project, which is +of great help when writing your first patch. + +Running Django's test suite for the first time +============================================== + +When contributing to Django it's very important that your code changes don't +introduce bugs into other areas of Django. One way to check that Django still +works after you make your changes is by running Django's test suite. If all +the tests still pass, then you can be reasonably sure that your changes +work and haven't broken other parts of Django. If you've never run Django's test +suite before, it's a good idea to run it once beforehand to get familiar with +its output. + +Before running the test suite, enter the Django ``tests/`` directory using the +``cd tests`` command, and install test dependencies by running: + +.. console:: + + $ python -m pip install -r requirements/py3.txt + +If you encounter an error during the installation, your system might be missing +a dependency for one or more of the Python packages. Consult the failing +package's documentation or search the web with the error message that you +encounter. + +Now we are ready to run the test suite. If you're using GNU/Linux, macOS, or +some other flavor of Unix, run: + +.. console:: + + $ ./runtests.py + +Now sit back and relax. Django's entire test suite has thousands of tests, and +it takes at least a few minutes to run, depending on the speed of your +computer. + +While Django's test suite is running, you'll see a stream of characters +representing the status of each test as it completes. ``E`` indicates that an +error was raised during a test, and ``F`` indicates that a test's assertions +failed. Both of these are considered to be test failures. Meanwhile, ``x`` and +``s`` indicated expected failures and skipped tests, respectively. Dots indicate +passing tests. + +Skipped tests are typically due to missing external libraries required to run +the test; see :ref:`running-unit-tests-dependencies` for a list of dependencies +and be sure to install any for tests related to the changes you are making (we +won't need any for this tutorial). Some tests are specific to a particular +database backend and will be skipped if not testing with that backend. SQLite +is the database backend for the default settings. To run the tests using a +different backend, see :ref:`running-unit-tests-settings`. + +Once the tests complete, you should be greeted with a message informing you +whether the test suite passed or failed. Since you haven't yet made any changes +to Django's code, the entire test suite **should** pass. If you get failures or +errors make sure you've followed all of the previous steps properly. See +:ref:`running-unit-tests` for more information. + +Note that the latest Django "main" branch may not always be stable. When +developing against "main", you can check `Django's continuous integration +builds`__ to determine if the failures are specific to your machine or if they +are also present in Django's official builds. If you click to view a particular +build, you can view the "Configuration Matrix" which shows failures broken down +by Python version and database backend. + +__ https://djangoci.com + +.. note:: + + For this tutorial and the ticket we're working on, testing against SQLite + is sufficient, however, it's possible (and sometimes necessary) to + :ref:`run the tests using a different database + `. + +Working on a feature +==================== + +For this tutorial, we'll work on a "fake ticket" as a case study. Here are the +imaginary details: + +.. admonition:: Ticket #99999 -- Allow making toast + + Django should provide a function ``django.shortcuts.make_toast()`` that + returns ``'toast'``. + +We'll now implement this feature and associated tests. + +Creating a branch for your patch +================================ + +Before making any changes, create a new branch for the ticket: + +.. console:: + + $ git checkout -b ticket_99999 + +You can choose any name that you want for the branch, "ticket_99999" is an +example. All changes made in this branch will be specific to the ticket and +won't affect the main copy of the code that we cloned earlier. + +Writing some tests for your ticket +================================== + +In most cases, for a patch to be accepted into Django it has to include tests. +For bug fix patches, this means writing a regression test to ensure that the +bug is never reintroduced into Django later on. A regression test should be +written in such a way that it will fail while the bug still exists and pass +once the bug has been fixed. For patches containing new features, you'll need +to include tests which ensure that the new features are working correctly. +They too should fail when the new feature is not present, and then pass once it +has been implemented. + +A good way to do this is to write your new tests first, before making any +changes to the code. This style of development is called +`test-driven development`__ and can be applied to both entire projects and +single patches. After writing your tests, you then run them to make sure that +they do indeed fail (since you haven't fixed that bug or added that feature +yet). If your new tests don't fail, you'll need to fix them so that they do. +After all, a regression test that passes regardless of whether a bug is present +is not very helpful at preventing that bug from reoccurring down the road. + +Now for our hands-on example. + +__ https://en.wikipedia.org/wiki/Test-driven_development + +Writing a test for ticket #99999 +-------------------------------- + +In order to resolve this ticket, we'll add a ``make_toast()`` function to the +``django.shortcuts`` module. First we are going to write a test that tries to +use the function and check that its output looks correct. + +Navigate to Django's ``tests/shortcuts/`` folder and create a new file +``test_make_toast.py``. Add the following code:: + + from django.shortcuts import make_toast + from django.test import SimpleTestCase + + + class MakeToastTests(SimpleTestCase): + def test_make_toast(self): + self.assertEqual(make_toast(), "toast") + +This test checks that the ``make_toast()`` returns ``'toast'``. + +.. admonition:: But this testing thing looks kinda hard... + + If you've never had to deal with tests before, they can look a little hard + to write at first glance. Fortunately, testing is a *very* big subject in + computer programming, so there's lots of information out there: + + * A good first look at writing tests for Django can be found in the + documentation on :doc:`/topics/testing/overview`. + * Dive Into Python (a free online book for beginning Python developers) + includes a great `introduction to Unit Testing`__. + * After reading those, if you want something a little meatier to sink + your teeth into, there's always the Python :mod:`unittest` documentation. + +__ https://diveinto.org/python3/unit-testing.html + +Running your new test +--------------------- + +Since we haven't made any modifications to ``django.shortcuts`` yet, our test +should fail. Let's run all the tests in the ``shortcuts`` folder to make sure +that's really what happens. ``cd`` to the Django ``tests/`` directory and run: + +.. console:: + + $ ./runtests.py shortcuts + +If the tests ran correctly, you should see one failure corresponding to the test +method we added, with this error: + +.. code-block:: pytb + + ImportError: cannot import name 'make_toast' from 'django.shortcuts' + +If all of the tests passed, then you'll want to make sure that you added the +new test shown above to the appropriate folder and file name. + +Writing the code for your ticket +================================ + +Next we'll be adding the ``make_toast()`` function. + +Navigate to the ``django/`` folder and open the ``shortcuts.py`` file. At the +bottom, add:: + + def make_toast(): + return "toast" + +Now we need to make sure that the test we wrote earlier passes, so we can see +whether the code we added is working correctly. Again, navigate to the Django +``tests/`` directory and run: + +.. console:: + + $ ./runtests.py shortcuts + +Everything should pass. If it doesn't, make sure you correctly added the +function to the correct file. + +Running Django's test suite for the second time +=============================================== + +Once you've verified that your patch and your test are working correctly, it's +a good idea to run the entire Django test suite to verify that your change +hasn't introduced any bugs into other areas of Django. While successfully +passing the entire test suite doesn't guarantee your code is bug free, it does +help identify many bugs and regressions that might otherwise go unnoticed. + +To run the entire Django test suite, ``cd`` into the Django ``tests/`` +directory and run: + +.. console:: + + $ ./runtests.py + +Writing Documentation +===================== + +This is a new feature, so it should be documented. Open the file +``docs/topics/http/shortcuts.txt`` and add the following at the end of the +file: + +.. code-block:: rst + + ``make_toast()`` + ================ + + .. function:: make_toast() + + .. versionadded:: 2.2 + + Returns ``'toast'``. + +Since this new feature will be in an upcoming release it is also added to the +release notes for the next version of Django. Open the release notes for the +latest version in ``docs/releases/``, which at time of writing is ``2.2.txt``. +Add a note under the "Minor Features" header: + +.. code-block:: rst + + :mod:`django.shortcuts` + ~~~~~~~~~~~~~~~~~~~~~~~ + + * The new :func:`django.shortcuts.make_toast` function returns ``'toast'``. + +For more information on writing documentation, including an explanation of what +the ``versionadded`` bit is all about, see +:doc:`/internals/contributing/writing-documentation`. That page also includes +an explanation of how to build a copy of the documentation locally, so you can +preview the HTML that will be generated. + +Previewing your changes +======================= + +Now it's time to go through all the changes made in our patch. To stage all the +changes ready for commit, run: + +.. console:: + + $ git add --all + +Then display the differences between your current copy of Django (with your +changes) and the revision that you initially checked out earlier in the +tutorial with: + +.. console:: + + $ git diff --cached + +Use the arrow keys to move up and down. + +.. code-block:: diff + + diff --git a/django/shortcuts.py b/django/shortcuts.py + index 7ab1df0e9d..8dde9e28d9 100644 + --- a/django/shortcuts.py + +++ b/django/shortcuts.py + @@ -156,3 +156,7 @@ def resolve_url(to, *args, **kwargs): + + # Finally, fall back and assume it's a URL + return to + + + + + +def make_toast(): + + return 'toast' + diff --git a/docs/releases/2.2.txt b/docs/releases/2.2.txt + index 7d85d30c4a..81518187b3 100644 + --- a/docs/releases/2.2.txt + +++ b/docs/releases/2.2.txt + @@ -40,6 +40,11 @@ database constraints. Constraints are added to models using the + Minor features + -------------- + + +:mod:`django.shortcuts` + +~~~~~~~~~~~~~~~~~~~~~~~ + + + +* The new :func:`django.shortcuts.make_toast` function returns ``'toast'``. + + + :mod:`django.contrib.admin` + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt + index 7b3a3a2c00..711bf6bb6d 100644 + --- a/docs/topics/http/shortcuts.txt + +++ b/docs/topics/http/shortcuts.txt + @@ -271,3 +271,12 @@ This example is equivalent to:: + my_objects = list(MyModel.objects.filter(published=True)) + if not my_objects: + raise Http404("No MyModel matches the given query.") + + + +``make_toast()`` + +================ + + + +.. function:: make_toast() + + + +.. versionadded:: 2.2 + + + +Returns ``'toast'``. + diff --git a/tests/shortcuts/test_make_toast.py b/tests/shortcuts/test_make_toast.py + new file mode 100644 + index 0000000000..6f4c627b6e + --- /dev/null + +++ b/tests/shortcuts/test_make_toast.py + @@ -0,0 +1,7 @@ + +from django.shortcuts import make_toast + +from django.test import SimpleTestCase + + + + + +class MakeToastTests(SimpleTestCase): + + def test_make_toast(self): + + self.assertEqual(make_toast(), 'toast') + +When you're done previewing the patch, hit the ``q`` key to return to the +command line. If the patch's content looked okay, it's time to commit the +changes. + +Committing the changes in the patch +=================================== + +To commit the changes: + +.. console:: + + $ git commit + +This opens up a text editor to type the commit message. Follow the :ref:`commit +message guidelines ` and write a message like: + +.. code-block:: text + + Fixed #99999 -- Added a shortcut function to make toast. + +Pushing the commit and making a pull request +============================================ + +After committing the patch, send it to your fork on GitHub (substitute +"ticket_99999" with the name of your branch if it's different): + +.. console:: + + $ git push origin ticket_99999 + +You can create a pull request by visiting the `Django GitHub page +`_. You'll see your branch under "Your +recently pushed branches". Click "Compare & pull request" next to it. + +Please don't do it for this tutorial, but on the next page that displays a +preview of the patch, you would click "Create pull request". + +Next steps +========== + +Congratulations, you've learned how to make a pull request to Django! Details +of more advanced techniques you may need are in +:doc:`/internals/contributing/writing-code/working-with-git`. + +Now you can put those skills to good use by helping to improve Django's +codebase. + +More information for new contributors +------------------------------------- + +Before you get too into writing patches for Django, there's a little more +information on contributing that you should probably take a look at: + +* You should make sure to read Django's documentation on + :doc:`claiming tickets and submitting patches + `. + It covers Trac etiquette, how to claim tickets for yourself, expected + coding style for patches, and many other important details. +* First time contributors should also read Django's :doc:`documentation + for first time contributors`. + It has lots of good advice for those of us who are new to helping out + with Django. +* After those, if you're still hungry for more information about + contributing, you can always browse through the rest of + :doc:`Django's documentation on contributing`. + It contains a ton of useful information and should be your first source + for answering any questions you might have. + +Finding your first real ticket +------------------------------ + +Once you've looked through some of that information, you'll be ready to go out +and find a ticket of your own to write a patch for. Pay special attention to +tickets with the "easy pickings" criterion. These tickets are often much +simpler in nature and are great for first time contributors. Once you're +familiar with contributing to Django, you can move on to writing patches for +more difficult and complicated tickets. + +If you just want to get started already (and nobody would blame you!), try +taking a look at the list of `easy tickets that need patches`__ and the +`easy tickets that have patches which need improvement`__. If you're familiar +with writing tests, you can also look at the list of +`easy tickets that need tests`__. Remember to follow the guidelines about +claiming tickets that were mentioned in the link to Django's documentation on +:doc:`claiming tickets and submitting patches +`. + +__ https://code.djangoproject.com/query?status=new&status=reopened&has_patch=0&easy=1&col=id&col=summary&col=status&col=owner&col=type&col=milestone&order=priority +__ https://code.djangoproject.com/query?status=new&status=reopened&needs_better_patch=1&easy=1&col=id&col=summary&col=status&col=owner&col=type&col=milestone&order=priority +__ https://code.djangoproject.com/query?status=new&status=reopened&needs_tests=1&easy=1&col=id&col=summary&col=status&col=owner&col=type&col=milestone&order=priority + +What's next after creating a pull request? +------------------------------------------ + +After a ticket has a patch, it needs to be reviewed by a second set of eyes. +After submitting a pull request, update the ticket metadata by setting the +flags on the ticket to say "has patch", "doesn't need tests", etc, so others +can find it for review. Contributing doesn't necessarily always mean writing a +patch from scratch. Reviewing existing patches is also a very helpful +contribution. See :doc:`/internals/contributing/triaging-tickets` for details. diff --git a/testbed/django__django/docs/intro/index.txt b/testbed/django__django/docs/intro/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca4836367f5e675d07367ce7d177092443d1b645 --- /dev/null +++ b/testbed/django__django/docs/intro/index.txt @@ -0,0 +1,41 @@ +=============== +Getting started +=============== + +New to Django? Or to web development in general? Well, you came to the right +place: read this material to quickly get up and running. + +.. toctree:: + :maxdepth: 1 + + overview + install + tutorial01 + tutorial02 + tutorial03 + tutorial04 + tutorial05 + tutorial06 + tutorial07 + tutorial08 + reusable-apps + whatsnext + contributing + +.. seealso:: + + If you're new to Python_, you might want to start by getting an idea of what + the language is like. Django is 100% Python, so if you've got minimal + comfort with Python you'll probably get a lot more out of Django. + + If you're new to programming entirely, you might want to start with this + `list of Python resources for non-programmers`_ + + If you already know a few other languages and want to get up to speed with + Python quickly, we recommend `Dive Into Python`_. If that's not quite your + style, there are many other `books about Python`_. + + .. _python: https://www.python.org/ + .. _list of Python resources for non-programmers: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers + .. _Dive Into Python: https://diveinto.org/python3/table-of-contents.html + .. _books about Python: https://wiki.python.org/moin/PythonBooks diff --git a/testbed/django__django/docs/intro/install.txt b/testbed/django__django/docs/intro/install.txt new file mode 100644 index 0000000000000000000000000000000000000000..b590df951bdb58c8ee5af7b336bdc070675cddf1 --- /dev/null +++ b/testbed/django__django/docs/intro/install.txt @@ -0,0 +1,84 @@ +=================== +Quick install guide +=================== + +Before you can use Django, you'll need to get it installed. We have a +:doc:`complete installation guide ` that covers all the +possibilities; this guide will guide you to a minimal installation that'll work +while you walk through the introduction. + +Install Python +============== + +Being a Python web framework, Django requires Python. See +:ref:`faq-python-version-support` for details. Python includes a lightweight +database called SQLite_ so you won't need to set up a database just yet. + +.. _sqlite: https://www.sqlite.org/ + +Get the latest version of Python at https://www.python.org/downloads/ or with +your operating system's package manager. + +You can verify that Python is installed by typing ``python`` from your shell; +you should see something like: + +.. code-block:: pycon + + Python 3.x.y + [GCC 4.x] on linux + Type "help", "copyright", "credits" or "license" for more information. + >>> + +Set up a database +================= + +This step is only necessary if you'd like to work with a "large" database engine +like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database, consult +the :ref:`database installation information `. + +Install Django +============== + +You've got three options to install Django: + +* :ref:`Install an official release `. This + is the best approach for most users. + +* Install a version of Django :ref:`provided by your operating system + distribution `. + +* :ref:`Install the latest development version + `. This option is for enthusiasts who want + the latest-and-greatest features and aren't afraid of running brand new code. + You might encounter new bugs in the development version, but reporting them + helps the development of Django. Also, releases of third-party packages are + less likely to be compatible with the development version than with the + latest stable release. + +.. admonition:: Always refer to the documentation that corresponds to the + version of Django you're using! + + If you do either of the first two steps, keep an eye out for parts of the + documentation marked **new in development version**. That phrase flags + features that are only available in development versions of Django, and + they likely won't work with an official release. + + +Verifying +========= + +To verify that Django can be seen by Python, type ``python`` from your shell. +Then at the Python prompt, try to import Django: + +.. parsed-literal:: + + >>> import django + >>> print(django.get_version()) + |version| + +You may have another version of Django installed. + +That's it! +========== + +That's it -- you can now :doc:`move onto the tutorial `. diff --git a/testbed/django__django/docs/intro/overview.txt b/testbed/django__django/docs/intro/overview.txt new file mode 100644 index 0000000000000000000000000000000000000000..8314b3d35159ed859778f3a15c7790bfea0df67f --- /dev/null +++ b/testbed/django__django/docs/intro/overview.txt @@ -0,0 +1,358 @@ +================== +Django at a glance +================== + +Because Django was developed in a fast-paced newsroom environment, it was +designed to make common web development tasks fast and easy. Here's an informal +overview of how to write a database-driven web app with Django. + +The goal of this document is to give you enough technical specifics to +understand how Django works, but this isn't intended to be a tutorial or +reference -- but we've got both! When you're ready to start a project, you can +:doc:`start with the tutorial ` or :doc:`dive right into more +detailed documentation `. + +Design your model +================= + +Although you can use Django without a database, it comes with an +`object-relational mapper`_ in which you describe your database layout in Python +code. + +.. _object-relational mapper: https://en.wikipedia.org/wiki/Object-relational_mapping + +The :doc:`data-model syntax ` offers many rich ways of +representing your models -- so far, it's been solving many years' worth of +database-schema problems. Here's a quick example: + +.. code-block:: python + :caption: ``mysite/news/models.py`` + + from django.db import models + + + class Reporter(models.Model): + full_name = models.CharField(max_length=70) + + def __str__(self): + return self.full_name + + + class Article(models.Model): + pub_date = models.DateField() + headline = models.CharField(max_length=200) + content = models.TextField() + reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) + + def __str__(self): + return self.headline + +Install it +========== + +Next, run the Django command-line utilities to create the database tables +automatically: + +.. console:: + + $ python manage.py makemigrations + $ python manage.py migrate + +The :djadmin:`makemigrations` command looks at all your available models and +creates migrations for whichever tables don't already exist. :djadmin:`migrate` +runs the migrations and creates tables in your database, as well as optionally +providing :doc:`much richer schema control `. + +Enjoy the free API +================== + +With that, you've got a free, and rich, :doc:`Python API ` +to access your data. The API is created on the fly, no code generation +necessary: + +.. code-block:: pycon + + # Import the models we created from our "news" app + >>> from news.models import Article, Reporter + + # No reporters are in the system yet. + >>> Reporter.objects.all() + + + # Create a new Reporter. + >>> r = Reporter(full_name="John Smith") + + # Save the object into the database. You have to call save() explicitly. + >>> r.save() + + # Now it has an ID. + >>> r.id + 1 + + # Now the new reporter is in the database. + >>> Reporter.objects.all() + ]> + + # Fields are represented as attributes on the Python object. + >>> r.full_name + 'John Smith' + + # Django provides a rich database lookup API. + >>> Reporter.objects.get(id=1) + + >>> Reporter.objects.get(full_name__startswith="John") + + >>> Reporter.objects.get(full_name__contains="mith") + + >>> Reporter.objects.get(id=2) + Traceback (most recent call last): + ... + DoesNotExist: Reporter matching query does not exist. + + # Create an article. + >>> from datetime import date + >>> a = Article( + ... pub_date=date.today(), headline="Django is cool", content="Yeah.", reporter=r + ... ) + >>> a.save() + + # Now the article is in the database. + >>> Article.objects.all() + ]> + + # Article objects get API access to related Reporter objects. + >>> r = a.reporter + >>> r.full_name + 'John Smith' + + # And vice versa: Reporter objects get API access to Article objects. + >>> r.article_set.all() + ]> + + # The API follows relationships as far as you need, performing efficient + # JOINs for you behind the scenes. + # This finds all articles by a reporter whose name starts with "John". + >>> Article.objects.filter(reporter__full_name__startswith="John") + ]> + + # Change an object by altering its attributes and calling save(). + >>> r.full_name = "Billy Goat" + >>> r.save() + + # Delete an object with delete(). + >>> r.delete() + +A dynamic admin interface: it's not just scaffolding -- it's the whole house +============================================================================ + +Once your models are defined, Django can automatically create a professional, +production ready :doc:`administrative interface ` -- +a website that lets authenticated users add, change and delete objects. The +only step required is to register your model in the admin site: + +.. code-block:: python + :caption: ``mysite/news/models.py`` + + from django.db import models + + + class Article(models.Model): + pub_date = models.DateField() + headline = models.CharField(max_length=200) + content = models.TextField() + reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) + +.. code-block:: python + :caption: ``mysite/news/admin.py`` + + from django.contrib import admin + + from . import models + + admin.site.register(models.Article) + +The philosophy here is that your site is edited by a staff, or a client, or +maybe just you -- and you don't want to have to deal with creating backend +interfaces only to manage content. + +One typical workflow in creating Django apps is to create models and get the +admin sites up and running as fast as possible, so your staff (or clients) can +start populating data. Then, develop the way data is presented to the public. + +Design your URLs +================ + +A clean, elegant URL scheme is an important detail in a high-quality web +application. Django encourages beautiful URL design and doesn't put any cruft +in URLs, like ``.php`` or ``.asp``. + +To design URLs for an app, you create a Python module called a :doc:`URLconf +`. A table of contents for your app, it contains a mapping +between URL patterns and Python callback functions. URLconfs also serve to +decouple URLs from Python code. + +Here's what a URLconf might look like for the ``Reporter``/``Article`` +example above: + +.. code-block:: python + :caption: ``mysite/news/urls.py`` + + from django.urls import path + + from . import views + + urlpatterns = [ + path("articles//", views.year_archive), + path("articles///", views.month_archive), + path("articles////", views.article_detail), + ] + +The code above maps URL paths to Python callback functions ("views"). The path +strings use parameter tags to "capture" values from the URLs. When a user +requests a page, Django runs through each path, in order, and stops at the +first one that matches the requested URL. (If none of them matches, Django +calls a special-case 404 view.) This is blazingly fast, because the paths are +compiled into regular expressions at load time. + +Once one of the URL patterns matches, Django calls the given view, which is a +Python function. Each view gets passed a request object -- which contains +request metadata -- and the values captured in the pattern. + +For example, if a user requested the URL "/articles/2005/05/39323/", Django +would call the function ``news.views.article_detail(request, +year=2005, month=5, pk=39323)``. + +Write your views +================ + +Each view is responsible for doing one of two things: Returning an +:class:`~django.http.HttpResponse` object containing the content for the +requested page, or raising an exception such as :class:`~django.http.Http404`. +The rest is up to you. + +Generally, a view retrieves data according to the parameters, loads a template +and renders the template with the retrieved data. Here's an example view for +``year_archive`` from above: + +.. code-block:: python + :caption: ``mysite/news/views.py`` + + from django.shortcuts import render + + from .models import Article + + + def year_archive(request, year): + a_list = Article.objects.filter(pub_date__year=year) + context = {"year": year, "article_list": a_list} + return render(request, "news/year_archive.html", context) + +This example uses Django's :doc:`template system `, which has +several powerful features but strives to stay simple enough for non-programmers +to use. + +Design your templates +===================== + +The code above loads the ``news/year_archive.html`` template. + +Django has a template search path, which allows you to minimize redundancy among +templates. In your Django settings, you specify a list of directories to check +for templates with :setting:`DIRS `. If a template doesn't exist +in the first directory, it checks the second, and so on. + +Let's say the ``news/year_archive.html`` template was found. Here's what that +might look like: + +.. code-block:: html+django + :caption: ``mysite/news/templates/news/year_archive.html`` + + {% extends "base.html" %} + + {% block title %}Articles for {{ year }}{% endblock %} + + {% block content %} +

Articles for {{ year }}

+ + {% for article in article_list %} +

{{ article.headline }}

+

By {{ article.reporter.full_name }}

+

Published {{ article.pub_date|date:"F j, Y" }}

+ {% endfor %} + {% endblock %} + +Variables are surrounded by double-curly braces. ``{{ article.headline }}`` +means "Output the value of the article's headline attribute." But dots aren't +used only for attribute lookup. They also can do dictionary-key lookup, index +lookup and function calls. + +Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|" +character). This is called a template filter, and it's a way to filter the value +of a variable. In this case, the date filter formats a Python datetime object in +the given format (as found in PHP's date function). + +You can chain together as many filters as you'd like. You can write :ref:`custom +template filters `. You can write +:doc:`custom template tags `, which run custom +Python code behind the scenes. + +Finally, Django uses the concept of "template inheritance". That's what the +``{% extends "base.html" %}`` does. It means "First load the template called +'base', which has defined a bunch of blocks, and fill the blocks with the +following blocks." In short, that lets you dramatically cut down on redundancy +in templates: each template has to define only what's unique to that template. + +Here's what the "base.html" template, including the use of :doc:`static files +`, might look like: + +.. code-block:: html+django + :caption: ``mysite/templates/base.html`` + + {% load static %} + + + {% block title %}{% endblock %} + + + Logo + {% block content %}{% endblock %} + + + +Simplistically, it defines the look-and-feel of the site (with the site's logo), +and provides "holes" for child templates to fill. This means that a site redesign +can be done by changing a single file -- the base template. + +It also lets you create multiple versions of a site, with different base +templates, while reusing child templates. Django's creators have used this +technique to create strikingly different mobile versions of sites by only +creating a new base template. + +Note that you don't have to use Django's template system if you prefer another +system. While Django's template system is particularly well-integrated with +Django's model layer, nothing forces you to use it. For that matter, you don't +have to use Django's database API, either. You can use another database +abstraction layer, you can read XML files, you can read files off disk, or +anything you want. Each piece of Django -- models, views, templates -- is +decoupled from the next. + +This is just the surface +======================== + +This has been only a quick overview of Django's functionality. Some more useful +features: + +* A :doc:`caching framework ` that integrates with memcached + or other backends. + +* A :doc:`syndication framework ` that lets you + create RSS and Atom feeds by writing a small Python class. + +* More attractive automatically-generated admin features -- this overview + barely scratched the surface. + +The next steps are for you to `download Django`_, read :doc:`the tutorial +` and join `the community`_. Thanks for your interest! + +.. _download Django: https://www.djangoproject.com/download/ +.. _the community: https://www.djangoproject.com/community/ diff --git a/testbed/django__django/docs/intro/reusable-apps.txt b/testbed/django__django/docs/intro/reusable-apps.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c827bb1399054aefed43548c31e0423676cf692 --- /dev/null +++ b/testbed/django__django/docs/intro/reusable-apps.txt @@ -0,0 +1,340 @@ +============================================= +Advanced tutorial: How to write reusable apps +============================================= + +This advanced tutorial begins where :doc:`Tutorial 8 ` +left off. We'll be turning our web-poll into a standalone Python package +you can reuse in new projects and share with other people. + +If you haven't recently completed Tutorials 1–7, we encourage you to review +these so that your example project matches the one described below. + +Reusability matters +=================== + +It's a lot of work to design, build, test and maintain a web application. Many +Python and Django projects share common problems. Wouldn't it be great if we +could save some of this repeated work? + +Reusability is the way of life in Python. `The Python Package Index (PyPI) +`_ has a vast range of packages you can use in your own +Python programs. Check out `Django Packages `_ for +existing reusable apps you could incorporate in your project. Django itself is +also a normal Python package. This means that you can take existing Python +packages or Django apps and compose them into your own web project. You only +need to write the parts that make your project unique. + +Let's say you were starting a new project that needed a polls app like the one +we've been working on. How do you make this app reusable? Luckily, you're well +on the way already. In :doc:`Tutorial 1 `, we saw how we +could decouple polls from the project-level URLconf using an ``include``. +In this tutorial, we'll take further steps to make the app easy to use in new +projects and ready to publish for others to install and use. + +.. admonition:: Package? App? + + A Python :term:`package` provides a way of grouping related Python code for + easy reuse. A package contains one or more files of Python code (also known + as "modules"). + + A package can be imported with ``import foo.bar`` or ``from foo import + bar``. For a directory (like ``polls``) to form a package, it must contain + a special file ``__init__.py``, even if this file is empty. + + A Django *application* is a Python package that is specifically intended + for use in a Django project. An application may use common Django + conventions, such as having ``models``, ``tests``, ``urls``, and ``views`` + submodules. + + Later on we use the term *packaging* to describe the process of making a + Python package easy for others to install. It can be a little confusing, we + know. + +Your project and your reusable app +================================== + +After the previous tutorials, our project should look like this: + +.. code-block:: text + + mysite/ + manage.py + mysite/ + __init__.py + settings.py + urls.py + asgi.py + wsgi.py + polls/ + __init__.py + admin.py + apps.py + migrations/ + __init__.py + 0001_initial.py + models.py + static/ + polls/ + images/ + background.gif + style.css + templates/ + polls/ + detail.html + index.html + results.html + tests.py + urls.py + views.py + templates/ + admin/ + base_site.html + +You created ``mysite/templates`` in :doc:`Tutorial 7 `, +and ``polls/templates`` in :doc:`Tutorial 3 `. Now perhaps +it is clearer why we chose to have separate template directories for the +project and application: everything that is part of the polls application is in +``polls``. It makes the application self-contained and easier to drop into a +new project. + +The ``polls`` directory could now be copied into a new Django project and +immediately reused. It's not quite ready to be published though. For that, we +need to package the app to make it easy for others to install. + +.. _installing-reusable-apps-prerequisites: + +Installing some prerequisites +============================= + +The current state of Python packaging is a bit muddled with various tools. For +this tutorial, we're going to use :pypi:`setuptools` to build our package. It's +the recommended packaging tool (merged with the ``distribute`` fork). We'll +also be using :pypi:`pip` to install and uninstall it. You should install these +two packages now. If you need help, you can refer to :ref:`how to install +Django with pip`. You can install ``setuptools`` +the same way. + +Packaging your app +================== + +Python *packaging* refers to preparing your app in a specific format that can +be easily installed and used. Django itself is packaged very much like +this. For a small app like polls, this process isn't too difficult. + +#. First, create a parent directory for ``polls``, outside of your Django + project. Call this directory ``django-polls``. + + .. admonition:: Choosing a name for your app + + When choosing a name for your package, check resources like PyPI to avoid + naming conflicts with existing packages. It's often useful to prepend + ``django-`` to your module name when creating a package to distribute. + This helps others looking for Django apps identify your app as Django + specific. + + Application labels (that is, the final part of the dotted path to + application packages) *must* be unique in :setting:`INSTALLED_APPS`. + Avoid using the same label as any of the Django :doc:`contrib packages + `, for example ``auth``, ``admin``, or + ``messages``. + +#. Move the ``polls`` directory into the ``django-polls`` directory. + +#. Create a file ``django-polls/README.rst`` with the following contents: + + .. code-block:: rst + :caption: ``django-polls/README.rst`` + + ===== + Polls + ===== + + Polls is a Django app to conduct web-based polls. For each question, + visitors can choose between a fixed number of answers. + + Detailed documentation is in the "docs" directory. + + Quick start + ----------- + + 1. Add "polls" to your INSTALLED_APPS setting like this:: + + INSTALLED_APPS = [ + ..., + "polls", + ] + + 2. Include the polls URLconf in your project urls.py like this:: + + path("polls/", include("polls.urls")), + + 3. Run ``python manage.py migrate`` to create the polls models. + + 4. Start the development server and visit http://127.0.0.1:8000/admin/ + to create a poll (you'll need the Admin app enabled). + + 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll. + +#. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the + scope of this tutorial, but suffice it to say that code released publicly + without a license is *useless*. Django and many Django-compatible apps are + distributed under the BSD license; however, you're free to pick your own + license. Just be aware that your licensing choice will affect who is able + to use your code. + +#. Next we'll create ``pyproject.toml``, ``setup.cfg``, and ``setup.py`` files + which detail how to build and install the app. A full explanation of these + files is beyond the scope of this tutorial, but the `setuptools + documentation `_ has a good + explanation. Create the ``django-polls/pyproject.toml``, + ``django-polls/setup.cfg``, and ``django-polls/setup.py`` files with the + following contents: + + .. code-block:: toml + :caption: ``django-polls/pyproject.toml`` + + [build-system] + requires = ['setuptools>=40.8.0'] + build-backend = 'setuptools.build_meta' + + .. code-block:: ini + :caption: ``django-polls/setup.cfg`` + + [metadata] + name = django-polls + version = 0.1 + description = A Django app to conduct web-based polls. + long_description = file: README.rst + url = https://www.example.com/ + author = Your Name + author_email = yourname@example.com + license = BSD-3-Clause # Example license + classifiers = + Environment :: Web Environment + Framework :: Django + Framework :: Django :: X.Y # Replace "X.Y" as appropriate + Intended Audience :: Developers + License :: OSI Approved :: BSD License + Operating System :: OS Independent + Programming Language :: Python + Programming Language :: Python :: 3 + Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.11 + Topic :: Internet :: WWW/HTTP + Topic :: Internet :: WWW/HTTP :: Dynamic Content + + [options] + include_package_data = true + packages = find: + python_requires = >=3.10 + install_requires = + Django >= X.Y # Replace "X.Y" as appropriate + + .. code-block:: python + :caption: ``django-polls/setup.py`` + + from setuptools import setup + + setup() + +#. Only Python modules and packages are included in the package by default. To + include additional files, we'll need to create a ``MANIFEST.in`` file. The + setuptools docs referred to in the previous step discuss this file in more + detail. To include the templates, the ``README.rst`` and our ``LICENSE`` + file, create a file ``django-polls/MANIFEST.in`` with the following + contents: + + .. code-block:: text + :caption: ``django-polls/MANIFEST.in`` + + include LICENSE + include README.rst + recursive-include polls/static * + recursive-include polls/templates * + +#. It's optional, but recommended, to include detailed documentation with your + app. Create an empty directory ``django-polls/docs`` for future + documentation. Add an additional line to ``django-polls/MANIFEST.in``: + + .. code-block:: text + + recursive-include docs * + + Note that the ``docs`` directory won't be included in your package unless + you add some files to it. Many Django apps also provide their documentation + online through sites like `readthedocs.org `_. + +#. Try building your package with ``python setup.py sdist`` (run from inside + ``django-polls``). This creates a directory called ``dist`` and builds your + new package, ``django-polls-0.1.tar.gz``. + +For more information on packaging, see Python's `Tutorial on Packaging and +Distributing Projects +`_. + +Using your own package +====================== + +Since we moved the ``polls`` directory out of the project, it's no longer +working. We'll now fix this by installing our new ``django-polls`` package. + +.. admonition:: Installing as a user library + + The following steps install ``django-polls`` as a user library. Per-user + installs have a lot of advantages over installing the package system-wide, + such as being usable on systems where you don't have administrator access + as well as preventing the package from affecting system services and other + users of the machine. + + Note that per-user installations can still affect the behavior of system + tools that run as that user, so using a virtual environment is a more robust + solution (see below). + +#. To install the package, use pip (you already :ref:`installed it + `, right?): + + .. code-block:: shell + + python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz + +#. With luck, your Django project should now work correctly again. Run the + server again to confirm this. + +#. To uninstall the package, use pip: + + .. code-block:: shell + + python -m pip uninstall django-polls + +Publishing your app +=================== + +Now that we've packaged and tested ``django-polls``, it's ready to share with +the world! If this wasn't just an example, you could now: + +* Email the package to a friend. + +* Upload the package on your website. + +* Post the package on a public repository, such as `the Python Package Index + (PyPI)`_. `packaging.python.org `_ has `a good + tutorial `_ + for doing this. + +Installing Python packages with a virtual environment +===================================================== + +Earlier, we installed the polls app as a user library. This has some +disadvantages: + +* Modifying the user libraries can affect other Python software on your system. + +* You won't be able to run multiple versions of this package (or others with + the same name). + +Typically, these situations only arise once you're maintaining several Django +projects. When they do, the best solution is to use :doc:`venv +`. This tool allows you to maintain multiple isolated +Python environments, each with its own copy of the libraries and package +namespace. diff --git a/testbed/django__django/docs/intro/tutorial01.txt b/testbed/django__django/docs/intro/tutorial01.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb296129c00e8e10d7473b27f8be02071d887f5c --- /dev/null +++ b/testbed/django__django/docs/intro/tutorial01.txt @@ -0,0 +1,380 @@ +===================================== +Writing your first Django app, part 1 +===================================== + +Let's learn by example. + +Throughout this tutorial, we'll walk you through the creation of a basic +poll application. + +It'll consist of two parts: + +* A public site that lets people view polls and vote in them. +* An admin site that lets you add, change, and delete polls. + +We'll assume you have :doc:`Django installed ` already. You can +tell Django is installed and which version by running the following command +in a shell prompt (indicated by the $ prefix): + +.. console:: + + $ python -m django --version + +If Django is installed, you should see the version of your installation. If it +isn't, you'll get an error telling "No module named django". + +This tutorial is written for Django |version|, which supports Python 3.10 and +later. If the Django version doesn't match, you can refer to the tutorial for +your version of Django by using the version switcher at the bottom right corner +of this page, or update Django to the newest version. If you're using an older +version of Python, check :ref:`faq-python-version-support` to find a compatible +version of Django. + +See :doc:`How to install Django ` for advice on how to remove +older versions of Django and install a newer one. + +.. admonition:: Where to get help: + + If you're having trouble going through this tutorial, please head over to + the :doc:`Getting Help` section of the FAQ. + +Creating a project +================== + +If this is your first time using Django, you'll have to take care of some +initial setup. Namely, you'll need to auto-generate some code that establishes a +Django :term:`project` -- a collection of settings for an instance of Django, +including database configuration, Django-specific options and +application-specific settings. + +From the command line, ``cd`` into a directory where you'd like to store your +code, then run the following command: + +.. console:: + + $ django-admin startproject mysite + +This will create a ``mysite`` directory in your current directory. If it didn't +work, see :ref:`troubleshooting-django-admin`. + +.. note:: + + You'll need to avoid naming projects after built-in Python or Django + components. In particular, this means you should avoid using names like + ``django`` (which will conflict with Django itself) or ``test`` (which + conflicts with a built-in Python package). + +.. admonition:: Where should this code live? + + If your background is in plain old PHP (with no use of modern frameworks), + you're probably used to putting code under the web server's document root + (in a place such as ``/var/www``). With Django, you don't do that. It's + not a good idea to put any of this Python code within your web server's + document root, because it risks the possibility that people may be able + to view your code over the web. That's not good for security. + + Put your code in some directory **outside** of the document root, such as + :file:`/home/mycode`. + +Let's look at what :djadmin:`startproject` created: + +.. code-block:: text + + mysite/ + manage.py + mysite/ + __init__.py + settings.py + urls.py + asgi.py + wsgi.py + +These files are: + +* The outer :file:`mysite/` root directory is a container for your project. Its + name doesn't matter to Django; you can rename it to anything you like. + +* :file:`manage.py`: A command-line utility that lets you interact with this + Django project in various ways. You can read all the details about + :file:`manage.py` in :doc:`/ref/django-admin`. + +* The inner :file:`mysite/` directory is the actual Python package for your + project. Its name is the Python package name you'll need to use to import + anything inside it (e.g. ``mysite.urls``). + +* :file:`mysite/__init__.py`: An empty file that tells Python that this + directory should be considered a Python package. If you're a Python beginner, + read :ref:`more about packages ` in the official Python docs. + +* :file:`mysite/settings.py`: Settings/configuration for this Django + project. :doc:`/topics/settings` will tell you all about how settings + work. + +* :file:`mysite/urls.py`: The URL declarations for this Django project; a + "table of contents" of your Django-powered site. You can read more about + URLs in :doc:`/topics/http/urls`. + +* :file:`mysite/asgi.py`: An entry-point for ASGI-compatible web servers to + serve your project. See :doc:`/howto/deployment/asgi/index` for more details. + +* :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible web servers to + serve your project. See :doc:`/howto/deployment/wsgi/index` for more details. + +The development server +====================== + +Let's verify your Django project works. Change into the outer :file:`mysite` directory, if +you haven't already, and run the following commands: + +.. console:: + + $ python manage.py runserver + +You'll see the following output on the command line: + +.. parsed-literal:: + + Performing system checks... + + System check identified no issues (0 silenced). + + You have unapplied migrations; your app may not work properly until they are applied. + Run 'python manage.py migrate' to apply them. + + |today| - 15:50:53 + Django version |version|, using settings 'mysite.settings' + Starting development server at http://127.0.0.1:8000/ + Quit the server with CONTROL-C. + +.. note:: + Ignore the warning about unapplied database migrations for now; we'll deal + with the database shortly. + +You've started the Django development server, a lightweight web server written +purely in Python. We've included this with Django so you can develop things +rapidly, without having to deal with configuring a production server -- such as +Apache -- until you're ready for production. + +Now's a good time to note: **don't** use this server in anything resembling a +production environment. It's intended only for use while developing. (We're in +the business of making web frameworks, not web servers.) + +Now that the server's running, visit http://127.0.0.1:8000/ with your web +browser. You'll see a "Congratulations!" page, with a rocket taking off. +It worked! + +.. admonition:: Changing the port + + By default, the :djadmin:`runserver` command starts the development server + on the internal IP at port 8000. + + If you want to change the server's port, pass + it as a command-line argument. For instance, this command starts the server + on port 8080: + + .. console:: + + $ python manage.py runserver 8080 + + If you want to change the server's IP, pass it along with the port. For + example, to listen on all available public IPs (which is useful if you are + running Vagrant or want to show off your work on other computers on the + network), use: + + .. console:: + + $ python manage.py runserver 0.0.0.0:8000 + + Full docs for the development server can be found in the + :djadmin:`runserver` reference. + +.. admonition:: Automatic reloading of :djadmin:`runserver` + + The development server automatically reloads Python code for each request + as needed. You don't need to restart the server for code changes to take + effect. However, some actions like adding files don't trigger a restart, + so you'll have to restart the server in these cases. + +Creating the Polls app +====================== + +Now that your environment -- a "project" -- is set up, you're set to start +doing work. + +Each application you write in Django consists of a Python package that follows +a certain convention. Django comes with a utility that automatically generates +the basic directory structure of an app, so you can focus on writing code +rather than creating directories. + +.. admonition:: Projects vs. apps + + What's the difference between a project and an app? An app is a web + application that does something -- e.g., a blog system, a database of + public records or a small poll app. A project is a collection of + configuration and apps for a particular website. A project can contain + multiple apps. An app can be in multiple projects. + +Your apps can live anywhere on your :ref:`Python path `. In +this tutorial, we'll create our poll app in the same directory as your +:file:`manage.py` file so that it can be imported as its own top-level module, +rather than a submodule of ``mysite``. + +To create your app, make sure you're in the same directory as :file:`manage.py` +and type this command: + +.. console:: + + $ python manage.py startapp polls + +That'll create a directory :file:`polls`, which is laid out like this: + +.. code-block:: text + + polls/ + __init__.py + admin.py + apps.py + migrations/ + __init__.py + models.py + tests.py + views.py + +This directory structure will house the poll application. + +Write your first view +===================== + +Let's write the first view. Open the file ``polls/views.py`` +and put the following Python code in it: + +.. code-block:: python + :caption: ``polls/views.py`` + + from django.http import HttpResponse + + + def index(request): + return HttpResponse("Hello, world. You're at the polls index.") + +This is the simplest view possible in Django. To call the view, we need to map +it to a URL - and for this we need a URLconf. + +To create a URLconf in the polls directory, create a file called ``urls.py``. +Your app directory should now look like: + +.. code-block:: text + + polls/ + __init__.py + admin.py + apps.py + migrations/ + __init__.py + models.py + tests.py + urls.py + views.py + +In the ``polls/urls.py`` file include the following code: + +.. code-block:: python + :caption: ``polls/urls.py`` + + from django.urls import path + + from . import views + + urlpatterns = [ + path("", views.index, name="index"), + ] + +The next step is to point the root URLconf at the ``polls.urls`` module. In +``mysite/urls.py``, add an import for ``django.urls.include`` and insert an +:func:`~django.urls.include` in the ``urlpatterns`` list, so you have: + +.. code-block:: python + :caption: ``mysite/urls.py`` + + from django.contrib import admin + from django.urls import include, path + + urlpatterns = [ + path("polls/", include("polls.urls")), + path("admin/", admin.site.urls), + ] + +The :func:`~django.urls.include` function allows referencing other URLconfs. +Whenever Django encounters :func:`~django.urls.include`, it chops off whatever +part of the URL matched up to that point and sends the remaining string to the +included URLconf for further processing. + +The idea behind :func:`~django.urls.include` is to make it easy to +plug-and-play URLs. Since polls are in their own URLconf +(``polls/urls.py``), they can be placed under "/polls/", or under +"/fun_polls/", or under "/content/polls/", or any other path root, and the +app will still work. + +.. admonition:: When to use :func:`~django.urls.include()` + + You should always use ``include()`` when you include other URL patterns. + ``admin.site.urls`` is the only exception to this. + +You have now wired an ``index`` view into the URLconf. Verify it's working with +the following command: + +.. console:: + + $ python manage.py runserver + +Go to http://localhost:8000/polls/ in your browser, and you should see the +text "*Hello, world. You're at the polls index.*", which you defined in the +``index`` view. + +.. admonition:: Page not found? + + If you get an error page here, check that you're going to + http://localhost:8000/polls/ and not http://localhost:8000/. + +The :func:`~django.urls.path` function is passed four arguments, two required: +``route`` and ``view``, and two optional: ``kwargs``, and ``name``. +At this point, it's worth reviewing what these arguments are for. + +:func:`~django.urls.path` argument: ``route`` +--------------------------------------------- + +``route`` is a string that contains a URL pattern. When processing a request, +Django starts at the first pattern in ``urlpatterns`` and makes its way down +the list, comparing the requested URL against each pattern until it finds one +that matches. + +Patterns don't search GET and POST parameters, or the domain name. For example, +in a request to ``https://www.example.com/myapp/``, the URLconf will look for +``myapp/``. In a request to ``https://www.example.com/myapp/?page=3``, the +URLconf will also look for ``myapp/``. + +:func:`~django.urls.path` argument: ``view`` +-------------------------------------------- + +When Django finds a matching pattern, it calls the specified view function with +an :class:`~django.http.HttpRequest` object as the first argument and any +"captured" values from the route as keyword arguments. We'll give an example +of this in a bit. + +:func:`~django.urls.path` argument: ``kwargs`` +---------------------------------------------- + +Arbitrary keyword arguments can be passed in a dictionary to the target view. We +aren't going to use this feature of Django in the tutorial. + +:func:`~django.urls.path` argument: ``name`` +-------------------------------------------- + +Naming your URL lets you refer to it unambiguously from elsewhere in Django, +especially from within templates. This powerful feature allows you to make +global changes to the URL patterns of your project while only touching a single +file. + +When you're comfortable with the basic request and response flow, read +:doc:`part 2 of this tutorial ` to start working with the +database. diff --git a/testbed/django__django/docs/intro/tutorial02.txt b/testbed/django__django/docs/intro/tutorial02.txt new file mode 100644 index 0000000000000000000000000000000000000000..6ba70ddc1c1aa32a076befc38f3b4082b8170943 --- /dev/null +++ b/testbed/django__django/docs/intro/tutorial02.txt @@ -0,0 +1,725 @@ +===================================== +Writing your first Django app, part 2 +===================================== + +This tutorial begins where :doc:`Tutorial 1 ` left off. +We'll set up the database, create your first model, and get a quick +introduction to Django's automatically-generated admin site. + +.. admonition:: Where to get help: + + If you're having trouble going through this tutorial, please head over to + the :doc:`Getting Help` section of the FAQ. + +Database setup +============== + +Now, open up :file:`mysite/settings.py`. It's a normal Python module with +module-level variables representing Django settings. + +By default, the configuration uses SQLite. If you're new to databases, or +you're just interested in trying Django, this is the easiest choice. SQLite is +included in Python, so you won't need to install anything else to support your +database. When starting your first real project, however, you may want to use a +more scalable database like PostgreSQL, to avoid database-switching headaches +down the road. + +If you wish to use another database, install the appropriate :ref:`database +bindings ` and change the following keys in the +:setting:`DATABASES` ``'default'`` item to match your database connection +settings: + +* :setting:`ENGINE ` -- Either + ``'django.db.backends.sqlite3'``, + ``'django.db.backends.postgresql'``, + ``'django.db.backends.mysql'``, or + ``'django.db.backends.oracle'``. Other backends are :ref:`also available + `. + +* :setting:`NAME` -- The name of your database. If you're using SQLite, the + database will be a file on your computer; in that case, :setting:`NAME` + should be the full absolute path, including filename, of that file. The + default value, ``BASE_DIR / 'db.sqlite3'``, will store the file in your + project directory. + +If you are not using SQLite as your database, additional settings such as +:setting:`USER`, :setting:`PASSWORD`, and :setting:`HOST` must be added. +For more details, see the reference documentation for :setting:`DATABASES`. + +.. admonition:: For databases other than SQLite + + If you're using a database besides SQLite, make sure you've created a + database by this point. Do that with "``CREATE DATABASE database_name;``" + within your database's interactive prompt. + + Also make sure that the database user provided in :file:`mysite/settings.py` + has "create database" privileges. This allows automatic creation of a + :ref:`test database ` which will be needed in a later + tutorial. + + If you're using SQLite, you don't need to create anything beforehand - the + database file will be created automatically when it is needed. + +While you're editing :file:`mysite/settings.py`, set :setting:`TIME_ZONE` to +your time zone. + +Also, note the :setting:`INSTALLED_APPS` setting at the top of the file. That +holds the names of all Django applications that are activated in this Django +instance. Apps can be used in multiple projects, and you can package and +distribute them for use by others in their projects. + +By default, :setting:`INSTALLED_APPS` contains the following apps, all of which +come with Django: + +* :mod:`django.contrib.admin` -- The admin site. You'll use it shortly. + +* :mod:`django.contrib.auth` -- An authentication system. + +* :mod:`django.contrib.contenttypes` -- A framework for content types. + +* :mod:`django.contrib.sessions` -- A session framework. + +* :mod:`django.contrib.messages` -- A messaging framework. + +* :mod:`django.contrib.staticfiles` -- A framework for managing + static files. + +These applications are included by default as a convenience for the common case. + +Some of these applications make use of at least one database table, though, +so we need to create the tables in the database before we can use them. To do +that, run the following command: + +.. console:: + + $ python manage.py migrate + +The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting +and creates any necessary database tables according to the database settings +in your :file:`mysite/settings.py` file and the database migrations shipped +with the app (we'll cover those later). You'll see a message for each +migration it applies. If you're interested, run the command-line client for your +database and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL), +``.tables`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to +display the tables Django created. + +.. admonition:: For the minimalists + + Like we said above, the default applications are included for the common + case, but not everybody needs them. If you don't need any or all of them, + feel free to comment-out or delete the appropriate line(s) from + :setting:`INSTALLED_APPS` before running :djadmin:`migrate`. The + :djadmin:`migrate` command will only run migrations for apps in + :setting:`INSTALLED_APPS`. + +.. _creating-models: + +Creating models +=============== + +Now we'll define your models -- essentially, your database layout, with +additional metadata. + +.. admonition:: Philosophy + + A model is the single, definitive source of information about your data. It + contains the essential fields and behaviors of the data you're storing. + Django follows the :ref:`DRY Principle `. The goal is to define your + data model in one place and automatically derive things from it. + + This includes the migrations - unlike in Ruby On Rails, for example, migrations + are entirely derived from your models file, and are essentially a + history that Django can roll through to update your database schema to + match your current models. + +In our poll app, we'll create two models: ``Question`` and ``Choice``. A +``Question`` has a question and a publication date. A ``Choice`` has two +fields: the text of the choice and a vote tally. Each ``Choice`` is associated +with a ``Question``. + +These concepts are represented by Python classes. Edit the +:file:`polls/models.py` file so it looks like this: + +.. code-block:: python + :caption: ``polls/models.py`` + + from django.db import models + + + class Question(models.Model): + question_text = models.CharField(max_length=200) + pub_date = models.DateTimeField("date published") + + + class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=200) + votes = models.IntegerField(default=0) + +Here, each model is represented by a class that subclasses +:class:`django.db.models.Model`. Each model has a number of class variables, +each of which represents a database field in the model. + +Each field is represented by an instance of a :class:`~django.db.models.Field` +class -- e.g., :class:`~django.db.models.CharField` for character fields and +:class:`~django.db.models.DateTimeField` for datetimes. This tells Django what +type of data each field holds. + +The name of each :class:`~django.db.models.Field` instance (e.g. +``question_text`` or ``pub_date``) is the field's name, in machine-friendly +format. You'll use this value in your Python code, and your database will use +it as the column name. + +You can use an optional first positional argument to a +:class:`~django.db.models.Field` to designate a human-readable name. That's used +in a couple of introspective parts of Django, and it doubles as documentation. +If this field isn't provided, Django will use the machine-readable name. In this +example, we've only defined a human-readable name for ``Question.pub_date``. +For all other fields in this model, the field's machine-readable name will +suffice as its human-readable name. + +Some :class:`~django.db.models.Field` classes have required arguments. +:class:`~django.db.models.CharField`, for example, requires that you give it a +:attr:`~django.db.models.CharField.max_length`. That's used not only in the +database schema, but in validation, as we'll soon see. + +A :class:`~django.db.models.Field` can also have various optional arguments; in +this case, we've set the :attr:`~django.db.models.Field.default` value of +``votes`` to 0. + +Finally, note a relationship is defined, using +:class:`~django.db.models.ForeignKey`. That tells Django each ``Choice`` is +related to a single ``Question``. Django supports all the common database +relationships: many-to-one, many-to-many, and one-to-one. + +Activating models +================= + +That small bit of model code gives Django a lot of information. With it, Django +is able to: + +* Create a database schema (``CREATE TABLE`` statements) for this app. +* Create a Python database-access API for accessing ``Question`` and ``Choice`` objects. + +But first we need to tell our project that the ``polls`` app is installed. + +.. admonition:: Philosophy + + Django apps are "pluggable": You can use an app in multiple projects, and + you can distribute apps, because they don't have to be tied to a given + Django installation. + +To include the app in our project, we need to add a reference to its +configuration class in the :setting:`INSTALLED_APPS` setting. The +``PollsConfig`` class is in the :file:`polls/apps.py` file, so its dotted path +is ``'polls.apps.PollsConfig'``. Edit the :file:`mysite/settings.py` file and +add that dotted path to the :setting:`INSTALLED_APPS` setting. It'll look like +this: + +.. code-block:: python + :caption: ``mysite/settings.py`` + + INSTALLED_APPS = [ + "polls.apps.PollsConfig", + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + ] + +Now Django knows to include the ``polls`` app. Let's run another command: + +.. console:: + + $ python manage.py makemigrations polls + +You should see something similar to the following: + +.. code-block:: text + + Migrations for 'polls': + polls/migrations/0001_initial.py + - Create model Question + - Create model Choice + +By running ``makemigrations``, you're telling Django that you've made +some changes to your models (in this case, you've made new ones) and that +you'd like the changes to be stored as a *migration*. + +Migrations are how Django stores changes to your models (and thus your +database schema) - they're files on disk. You can read the migration for your +new model if you like; it's the file ``polls/migrations/0001_initial.py``. +Don't worry, you're not expected to read them every time Django makes one, but +they're designed to be human-editable in case you want to manually tweak how +Django changes things. + +There's a command that will run the migrations for you and manage your database +schema automatically - that's called :djadmin:`migrate`, and we'll come to it in a +moment - but first, let's see what SQL that migration would run. The +:djadmin:`sqlmigrate` command takes migration names and returns their SQL: + +.. console:: + + $ python manage.py sqlmigrate polls 0001 + +You should see something similar to the following (we've reformatted it for +readability): + +.. code-block:: sql + + BEGIN; + -- + -- Create model Question + -- + CREATE TABLE "polls_question" ( + "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, + "question_text" varchar(200) NOT NULL, + "pub_date" timestamp with time zone NOT NULL + ); + -- + -- Create model Choice + -- + CREATE TABLE "polls_choice" ( + "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, + "choice_text" varchar(200) NOT NULL, + "votes" integer NOT NULL, + "question_id" bigint NOT NULL + ); + ALTER TABLE "polls_choice" + ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id" + FOREIGN KEY ("question_id") + REFERENCES "polls_question" ("id") + DEFERRABLE INITIALLY DEFERRED; + CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id"); + + COMMIT; + +Note the following: + +* The exact output will vary depending on the database you are using. The + example above is generated for PostgreSQL. + +* Table names are automatically generated by combining the name of the app + (``polls``) and the lowercase name of the model -- ``question`` and + ``choice``. (You can override this behavior.) + +* Primary keys (IDs) are added automatically. (You can override this, too.) + +* By convention, Django appends ``"_id"`` to the foreign key field name. + (Yes, you can override this, as well.) + +* The foreign key relationship is made explicit by a ``FOREIGN KEY`` + constraint. Don't worry about the ``DEFERRABLE`` parts; it's telling + PostgreSQL to not enforce the foreign key until the end of the transaction. + +* It's tailored to the database you're using, so database-specific field types + such as ``auto_increment`` (MySQL), ``bigint PRIMARY KEY GENERATED BY DEFAULT + AS IDENTITY`` (PostgreSQL), or ``integer primary key autoincrement`` (SQLite) + are handled for you automatically. Same goes for the quoting of field names + -- e.g., using double quotes or single quotes. + +* The :djadmin:`sqlmigrate` command doesn't actually run the migration on your + database - instead, it prints it to the screen so that you can see what SQL + Django thinks is required. It's useful for checking what Django is going to + do or if you have database administrators who require SQL scripts for + changes. + +If you're interested, you can also run +:djadmin:`python manage.py check `; this checks for any problems in +your project without making migrations or touching the database. + +Now, run :djadmin:`migrate` again to create those model tables in your database: + +.. console:: + + $ python manage.py migrate + Operations to perform: + Apply all migrations: admin, auth, contenttypes, polls, sessions + Running migrations: + Rendering model states... DONE + Applying polls.0001_initial... OK + +The :djadmin:`migrate` command takes all the migrations that haven't been +applied (Django tracks which ones are applied using a special table in your +database called ``django_migrations``) and runs them against your database - +essentially, synchronizing the changes you made to your models with the schema +in the database. + +Migrations are very powerful and let you change your models over time, as you +develop your project, without the need to delete your database or tables and +make new ones - it specializes in upgrading your database live, without +losing data. We'll cover them in more depth in a later part of the tutorial, +but for now, remember the three-step guide to making model changes: + +* Change your models (in ``models.py``). +* Run :djadmin:`python manage.py makemigrations ` to create + migrations for those changes +* Run :djadmin:`python manage.py migrate ` to apply those changes to + the database. + +The reason that there are separate commands to make and apply migrations is +because you'll commit migrations to your version control system and ship them +with your app; they not only make your development easier, they're also +usable by other developers and in production. + +Read the :doc:`django-admin documentation ` for full +information on what the ``manage.py`` utility can do. + +Playing with the API +==================== + +Now, let's hop into the interactive Python shell and play around with the free +API Django gives you. To invoke the Python shell, use this command: + +.. console:: + + $ python manage.py shell + +We're using this instead of simply typing "python", because :file:`manage.py` +sets the :envvar:`DJANGO_SETTINGS_MODULE` environment variable, which gives +Django the Python import path to your :file:`mysite/settings.py` file. + +Once you're in the shell, explore the :doc:`database API `: + +.. code-block:: pycon + + >>> from polls.models import Choice, Question # Import the model classes we just wrote. + + # No questions are in the system yet. + >>> Question.objects.all() + + + # Create a new Question. + # Support for time zones is enabled in the default settings file, so + # Django expects a datetime with tzinfo for pub_date. Use timezone.now() + # instead of datetime.datetime.now() and it will do the right thing. + >>> from django.utils import timezone + >>> q = Question(question_text="What's new?", pub_date=timezone.now()) + + # Save the object into the database. You have to call save() explicitly. + >>> q.save() + + # Now it has an ID. + >>> q.id + 1 + + # Access model field values via Python attributes. + >>> q.question_text + "What's new?" + >>> q.pub_date + datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=datetime.timezone.utc) + + # Change values by changing the attributes, then calling save(). + >>> q.question_text = "What's up?" + >>> q.save() + + # objects.all() displays all the questions in the database. + >>> Question.objects.all() + ]> + +Wait a minute. ```` isn't a helpful +representation of this object. Let's fix that by editing the ``Question`` model +(in the ``polls/models.py`` file) and adding a +:meth:`~django.db.models.Model.__str__` method to both ``Question`` and +``Choice``: + +.. code-block:: python + :caption: ``polls/models.py`` + + from django.db import models + + + class Question(models.Model): + # ... + def __str__(self): + return self.question_text + + + class Choice(models.Model): + # ... + def __str__(self): + return self.choice_text + +It's important to add :meth:`~django.db.models.Model.__str__` methods to your +models, not only for your own convenience when dealing with the interactive +prompt, but also because objects' representations are used throughout Django's +automatically-generated admin. + +.. _tutorial02-import-timezone: + +Let's also add a custom method to this model: + +.. code-block:: python + :caption: ``polls/models.py`` + + import datetime + + from django.db import models + from django.utils import timezone + + + class Question(models.Model): + # ... + def was_published_recently(self): + return self.pub_date >= timezone.now() - datetime.timedelta(days=1) + +Note the addition of ``import datetime`` and ``from django.utils import +timezone``, to reference Python's standard :mod:`datetime` module and Django's +time-zone-related utilities in :mod:`django.utils.timezone`, respectively. If +you aren't familiar with time zone handling in Python, you can learn more in +the :doc:`time zone support docs `. + +Save these changes and start a new Python interactive shell by running +``python manage.py shell`` again: + +.. code-block:: pycon + + >>> from polls.models import Choice, Question + + # Make sure our __str__() addition worked. + >>> Question.objects.all() + ]> + + # Django provides a rich database lookup API that's entirely driven by + # keyword arguments. + >>> Question.objects.filter(id=1) + ]> + >>> Question.objects.filter(question_text__startswith="What") + ]> + + # Get the question that was published this year. + >>> from django.utils import timezone + >>> current_year = timezone.now().year + >>> Question.objects.get(pub_date__year=current_year) + + + # Request an ID that doesn't exist, this will raise an exception. + >>> Question.objects.get(id=2) + Traceback (most recent call last): + ... + DoesNotExist: Question matching query does not exist. + + # Lookup by a primary key is the most common case, so Django provides a + # shortcut for primary-key exact lookups. + # The following is identical to Question.objects.get(id=1). + >>> Question.objects.get(pk=1) + + + # Make sure our custom method worked. + >>> q = Question.objects.get(pk=1) + >>> q.was_published_recently() + True + + # Give the Question a couple of Choices. The create call constructs a new + # Choice object, does the INSERT statement, adds the choice to the set + # of available choices and returns the new Choice object. Django creates + # a set to hold the "other side" of a ForeignKey relation + # (e.g. a question's choice) which can be accessed via the API. + >>> q = Question.objects.get(pk=1) + + # Display any choices from the related object set -- none so far. + >>> q.choice_set.all() + + + # Create three choices. + >>> q.choice_set.create(choice_text="Not much", votes=0) + + >>> q.choice_set.create(choice_text="The sky", votes=0) + + >>> c = q.choice_set.create(choice_text="Just hacking again", votes=0) + + # Choice objects have API access to their related Question objects. + >>> c.question + + + # And vice versa: Question objects get access to Choice objects. + >>> q.choice_set.all() + , , ]> + >>> q.choice_set.count() + 3 + + # The API automatically follows relationships as far as you need. + # Use double underscores to separate relationships. + # This works as many levels deep as you want; there's no limit. + # Find all Choices for any question whose pub_date is in this year + # (reusing the 'current_year' variable we created above). + >>> Choice.objects.filter(question__pub_date__year=current_year) + , , ]> + + # Let's delete one of the choices. Use delete() for that. + >>> c = q.choice_set.filter(choice_text__startswith="Just hacking") + >>> c.delete() + +For more information on model relations, see :doc:`Accessing related objects +`. For more on how to use double underscores to perform +field lookups via the API, see :ref:`Field lookups `. For +full details on the database API, see our :doc:`Database API reference +`. + +Introducing the Django Admin +============================ + +.. admonition:: Philosophy + + Generating admin sites for your staff or clients to add, change, and delete + content is tedious work that doesn't require much creativity. For that + reason, Django entirely automates creation of admin interfaces for models. + + Django was written in a newsroom environment, with a very clear separation + between "content publishers" and the "public" site. Site managers use the + system to add news stories, events, sports scores, etc., and that content is + displayed on the public site. Django solves the problem of creating a + unified interface for site administrators to edit content. + + The admin isn't intended to be used by site visitors. It's for site + managers. + +Creating an admin user +---------------------- + +First we'll need to create a user who can login to the admin site. Run the +following command: + +.. console:: + + $ python manage.py createsuperuser + +Enter your desired username and press enter. + +.. code-block:: text + + Username: admin + +You will then be prompted for your desired email address: + +.. code-block:: text + + Email address: admin@example.com + +The final step is to enter your password. You will be asked to enter your +password twice, the second time as a confirmation of the first. + +.. code-block:: text + + Password: ********** + Password (again): ********* + Superuser created successfully. + +Start the development server +---------------------------- + +The Django admin site is activated by default. Let's start the development +server and explore it. + +If the server is not running start it like so: + +.. console:: + + $ python manage.py runserver + +Now, open a web browser and go to "/admin/" on your local domain -- e.g., +http://127.0.0.1:8000/admin/. You should see the admin's login screen: + +.. image:: _images/admin01.png + :alt: Django admin login screen + +Since :doc:`translation ` is turned on by default, if +you set :setting:`LANGUAGE_CODE`, the login screen will be displayed in the +given language (if Django has appropriate translations). + +Enter the admin site +-------------------- + +Now, try logging in with the superuser account you created in the previous step. +You should see the Django admin index page: + +.. image:: _images/admin02.png + :alt: Django admin index page + +You should see a few types of editable content: groups and users. They are +provided by :mod:`django.contrib.auth`, the authentication framework shipped +by Django. + +Make the poll app modifiable in the admin +----------------------------------------- + +But where's our poll app? It's not displayed on the admin index page. + +Only one more thing to do: we need to tell the admin that ``Question`` objects +have an admin interface. To do this, open the :file:`polls/admin.py` file, and +edit it to look like this: + +.. code-block:: python + :caption: ``polls/admin.py`` + + from django.contrib import admin + + from .models import Question + + admin.site.register(Question) + +Explore the free admin functionality +------------------------------------ + +Now that we've registered ``Question``, Django knows that it should be displayed on +the admin index page: + +.. image:: _images/admin03t.png + :alt: Django admin index page, now with polls displayed + +Click "Questions". Now you're at the "change list" page for questions. This page +displays all the questions in the database and lets you choose one to change it. +There's the "What's up?" question we created earlier: + +.. image:: _images/admin04t.png + :alt: Polls change list page + +Click the "What's up?" question to edit it: + +.. image:: _images/admin05t.png + :alt: Editing form for question object + +Things to note here: + +* The form is automatically generated from the ``Question`` model. + +* The different model field types (:class:`~django.db.models.DateTimeField`, + :class:`~django.db.models.CharField`) correspond to the appropriate HTML + input widget. Each type of field knows how to display itself in the Django + admin. + +* Each :class:`~django.db.models.DateTimeField` gets free JavaScript + shortcuts. Dates get a "Today" shortcut and calendar popup, and times get + a "Now" shortcut and a convenient popup that lists commonly entered times. + +The bottom part of the page gives you a couple of options: + +* Save -- Saves changes and returns to the change-list page for this type of + object. + +* Save and continue editing -- Saves changes and reloads the admin page for + this object. + +* Save and add another -- Saves changes and loads a new, blank form for this + type of object. + +* Delete -- Displays a delete confirmation page. + +If the value of "Date published" doesn't match the time when you created the +question in :doc:`Tutorial 1`, it probably +means you forgot to set the correct value for the :setting:`TIME_ZONE` setting. +Change it, reload the page and check that the correct value appears. + +Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then +click "Save and continue editing." Then click "History" in the upper right. +You'll see a page listing all changes made to this object via the Django admin, +with the timestamp and username of the person who made the change: + +.. image:: _images/admin06t.png + :alt: History page for question object + +When you're comfortable with the models API and have familiarized yourself with +the admin site, read :doc:`part 3 of this tutorial` to learn +about how to add more views to our polls app. diff --git a/testbed/django__django/docs/intro/tutorial03.txt b/testbed/django__django/docs/intro/tutorial03.txt new file mode 100644 index 0000000000000000000000000000000000000000..04bd83ae52f3e1acb2637dc22865350f0e55dbd2 --- /dev/null +++ b/testbed/django__django/docs/intro/tutorial03.txt @@ -0,0 +1,474 @@ +===================================== +Writing your first Django app, part 3 +===================================== + +This tutorial begins where :doc:`Tutorial 2 ` left off. We're +continuing the web-poll application and will focus on creating the public +interface -- "views." + +.. admonition:: Where to get help: + + If you're having trouble going through this tutorial, please head over to + the :doc:`Getting Help` section of the FAQ. + +Overview +======== + +A view is a "type" of web page in your Django application that generally serves +a specific function and has a specific template. For example, in a blog +application, you might have the following views: + +* Blog homepage -- displays the latest few entries. + +* Entry "detail" page -- permalink page for a single entry. + +* Year-based archive page -- displays all months with entries in the + given year. + +* Month-based archive page -- displays all days with entries in the + given month. + +* Day-based archive page -- displays all entries in the given day. + +* Comment action -- handles posting comments to a given entry. + +In our poll application, we'll have the following four views: + +* Question "index" page -- displays the latest few questions. + +* Question "detail" page -- displays a question text, with no results but + with a form to vote. + +* Question "results" page -- displays results for a particular question. + +* Vote action -- handles voting for a particular choice in a particular + question. + +In Django, web pages and other content are delivered by views. Each view is +represented by a Python function (or method, in the case of class-based views). +Django will choose a view by examining the URL that's requested (to be precise, +the part of the URL after the domain name). + +Now in your time on the web you may have come across such beauties as +``ME2/Sites/dirmod.htm?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B``. +You will be pleased to know that Django allows us much more elegant +*URL patterns* than that. + +A URL pattern is the general form of a URL - for example: +``/newsarchive///``. + +To get from a URL to a view, Django uses what are known as 'URLconfs'. A +URLconf maps URL patterns to views. + +This tutorial provides basic instruction in the use of URLconfs, and you can +refer to :doc:`/topics/http/urls` for more information. + +Writing more views +================== + +Now let's add a few more views to ``polls/views.py``. These views are +slightly different, because they take an argument: + +.. code-block:: python + :caption: ``polls/views.py`` + + def detail(request, question_id): + return HttpResponse("You're looking at question %s." % question_id) + + + def results(request, question_id): + response = "You're looking at the results of question %s." + return HttpResponse(response % question_id) + + + def vote(request, question_id): + return HttpResponse("You're voting on question %s." % question_id) + +Wire these new views into the ``polls.urls`` module by adding the following +:func:`~django.urls.path` calls: + +.. code-block:: python + :caption: ``polls/urls.py`` + + from django.urls import path + + from . import views + + urlpatterns = [ + # ex: /polls/ + path("", views.index, name="index"), + # ex: /polls/5/ + path("/", views.detail, name="detail"), + # ex: /polls/5/results/ + path("/results/", views.results, name="results"), + # ex: /polls/5/vote/ + path("/vote/", views.vote, name="vote"), + ] + +Take a look in your browser, at "/polls/34/". It'll run the ``detail()`` +method and display whatever ID you provide in the URL. Try +"/polls/34/results/" and "/polls/34/vote/" too -- these will display the +placeholder results and voting pages. + +When somebody requests a page from your website -- say, "/polls/34/", Django +will load the ``mysite.urls`` Python module because it's pointed to by the +:setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns`` +and traverses the patterns in order. After finding the match at ``'polls/'``, +it strips off the matching text (``"polls/"``) and sends the remaining text -- +``"34/"`` -- to the 'polls.urls' URLconf for further processing. There it +matches ``'/'``, resulting in a call to the ``detail()`` view +like so: + +.. code-block:: pycon + + detail(request=, question_id=34) + +The ``question_id=34`` part comes from ````. Using angle +brackets "captures" part of the URL and sends it as a keyword argument to the +view function. The ``question_id`` part of the string defines the name that +will be used to identify the matched pattern, and the ``int`` part is a +converter that determines what patterns should match this part of the URL path. +The colon (``:``) separates the converter and pattern name. + +Write views that actually do something +====================================== + +Each view is responsible for doing one of two things: returning an +:class:`~django.http.HttpResponse` object containing the content for the +requested page, or raising an exception such as :exc:`~django.http.Http404`. The +rest is up to you. + +Your view can read records from a database, or not. It can use a template +system such as Django's -- or a third-party Python template system -- or not. +It can generate a PDF file, output XML, create a ZIP file on the fly, anything +you want, using whatever Python libraries you want. + +All Django wants is that :class:`~django.http.HttpResponse`. Or an exception. + +Because it's convenient, let's use Django's own database API, which we covered +in :doc:`Tutorial 2 `. Here's one stab at a new ``index()`` +view, which displays the latest 5 poll questions in the system, separated by +commas, according to publication date: + +.. code-block:: python + :caption: ``polls/views.py`` + + from django.http import HttpResponse + + from .models import Question + + + def index(request): + latest_question_list = Question.objects.order_by("-pub_date")[:5] + output = ", ".join([q.question_text for q in latest_question_list]) + return HttpResponse(output) + + + # Leave the rest of the views (detail, results, vote) unchanged + +There's a problem here, though: the page's design is hard-coded in the view. If +you want to change the way the page looks, you'll have to edit this Python code. +So let's use Django's template system to separate the design from Python by +creating a template that the view can use. + +First, create a directory called ``templates`` in your ``polls`` directory. +Django will look for templates in there. + +Your project's :setting:`TEMPLATES` setting describes how Django will load and +render templates. The default settings file configures a ``DjangoTemplates`` +backend whose :setting:`APP_DIRS ` option is set to +``True``. By convention ``DjangoTemplates`` looks for a "templates" +subdirectory in each of the :setting:`INSTALLED_APPS`. + +Within the ``templates`` directory you have just created, create another +directory called ``polls``, and within that create a file called +``index.html``. In other words, your template should be at +``polls/templates/polls/index.html``. Because of how the ``app_directories`` +template loader works as described above, you can refer to this template within +Django as ``polls/index.html``. + +.. admonition:: Template namespacing + + Now we *might* be able to get away with putting our templates directly in + ``polls/templates`` (rather than creating another ``polls`` subdirectory), + but it would actually be a bad idea. Django will choose the first template + it finds whose name matches, and if you had a template with the same name + in a *different* application, Django would be unable to distinguish between + them. We need to be able to point Django at the right one, and the best + way to ensure this is by *namespacing* them. That is, by putting those + templates inside *another* directory named for the application itself. + +Put the following code in that template: + +.. code-block:: html+django + :caption: ``polls/templates/polls/index.html`` + + {% if latest_question_list %} + + {% else %} +

No polls are available.

+ {% endif %} + +.. note:: + + To make the tutorial shorter, all template examples use incomplete HTML. In + your own projects you should use `complete HTML documents`__. + +__ https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started#anatomy_of_an_html_document + +Now let's update our ``index`` view in ``polls/views.py`` to use the template: + +.. code-block:: python + :caption: ``polls/views.py`` + + from django.http import HttpResponse + from django.template import loader + + from .models import Question + + + def index(request): + latest_question_list = Question.objects.order_by("-pub_date")[:5] + template = loader.get_template("polls/index.html") + context = { + "latest_question_list": latest_question_list, + } + return HttpResponse(template.render(context, request)) + +That code loads the template called ``polls/index.html`` and passes it a +context. The context is a dictionary mapping template variable names to Python +objects. + +Load the page by pointing your browser at "/polls/", and you should see a +bulleted-list containing the "What's up" question from :doc:`Tutorial 2 +`. The link points to the question's detail page. + +A shortcut: :func:`~django.shortcuts.render` +-------------------------------------------- + +It's a very common idiom to load a template, fill a context and return an +:class:`~django.http.HttpResponse` object with the result of the rendered +template. Django provides a shortcut. Here's the full ``index()`` view, +rewritten: + +.. code-block:: python + :caption: ``polls/views.py`` + + from django.shortcuts import render + + from .models import Question + + + def index(request): + latest_question_list = Question.objects.order_by("-pub_date")[:5] + context = {"latest_question_list": latest_question_list} + return render(request, "polls/index.html", context) + +Note that once we've done this in all these views, we no longer need to import +:mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll +want to keep ``HttpResponse`` if you still have the stub methods for ``detail``, +``results``, and ``vote``). + +The :func:`~django.shortcuts.render` function takes the request object as its +first argument, a template name as its second argument and a dictionary as its +optional third argument. It returns an :class:`~django.http.HttpResponse` +object of the given template rendered with the given context. + +Raising a 404 error +=================== + +Now, let's tackle the question detail view -- the page that displays the question text +for a given poll. Here's the view: + +.. code-block:: python + :caption: ``polls/views.py`` + + from django.http import Http404 + from django.shortcuts import render + + from .models import Question + + + # ... + def detail(request, question_id): + try: + question = Question.objects.get(pk=question_id) + except Question.DoesNotExist: + raise Http404("Question does not exist") + return render(request, "polls/detail.html", {"question": question}) + +The new concept here: The view raises the :exc:`~django.http.Http404` exception +if a question with the requested ID doesn't exist. + +We'll discuss what you could put in that ``polls/detail.html`` template a bit +later, but if you'd like to quickly get the above example working, a file +containing just: + +.. code-block:: html+django + :caption: ``polls/templates/polls/detail.html`` + + {{ question }} + +will get you started for now. + +A shortcut: :func:`~django.shortcuts.get_object_or_404` +------------------------------------------------------- + +It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get` +and raise :exc:`~django.http.Http404` if the object doesn't exist. Django +provides a shortcut. Here's the ``detail()`` view, rewritten: + +.. code-block:: python + :caption: ``polls/views.py`` + + from django.shortcuts import get_object_or_404, render + + from .models import Question + + + # ... + def detail(request, question_id): + question = get_object_or_404(Question, pk=question_id) + return render(request, "polls/detail.html", {"question": question}) + +The :func:`~django.shortcuts.get_object_or_404` function takes a Django model +as its first argument and an arbitrary number of keyword arguments, which it +passes to the :meth:`~django.db.models.query.QuerySet.get` function of the +model's manager. It raises :exc:`~django.http.Http404` if the object doesn't +exist. + +.. admonition:: Philosophy + + Why do we use a helper function :func:`~django.shortcuts.get_object_or_404` + instead of automatically catching the + :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher + level, or having the model API raise :exc:`~django.http.Http404` instead of + :exc:`~django.core.exceptions.ObjectDoesNotExist`? + + Because that would couple the model layer to the view layer. One of the + foremost design goals of Django is to maintain loose coupling. Some + controlled coupling is introduced in the :mod:`django.shortcuts` module. + +There's also a :func:`~django.shortcuts.get_list_or_404` function, which works +just as :func:`~django.shortcuts.get_object_or_404` -- except using +:meth:`~django.db.models.query.QuerySet.filter` instead of +:meth:`~django.db.models.query.QuerySet.get`. It raises +:exc:`~django.http.Http404` if the list is empty. + +Use the template system +======================= + +Back to the ``detail()`` view for our poll application. Given the context +variable ``question``, here's what the ``polls/detail.html`` template might look +like: + +.. code-block:: html+django + :caption: ``polls/templates/polls/detail.html`` + +

{{ question.question_text }}

+
    + {% for choice in question.choice_set.all %} +
  • {{ choice.choice_text }}
  • + {% endfor %} +
+ +The template system uses dot-lookup syntax to access variable attributes. In +the example of ``{{ question.question_text }}``, first Django does a dictionary lookup +on the object ``question``. Failing that, it tries an attribute lookup -- which +works, in this case. If attribute lookup had failed, it would've tried a +list-index lookup. + +Method-calling happens in the :ttag:`{% for %}` loop: +``question.choice_set.all`` is interpreted as the Python code +``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is +suitable for use in the :ttag:`{% for %}` tag. + +See the :doc:`template guide ` for more about templates. + +Removing hardcoded URLs in templates +==================================== + +Remember, when we wrote the link to a question in the ``polls/index.html`` +template, the link was partially hardcoded like this: + +.. code-block:: html+django + +
  • {{ question.question_text }}
  • + +The problem with this hardcoded, tightly-coupled approach is that it becomes +challenging to change URLs on projects with a lot of templates. However, since +you defined the name argument in the :func:`~django.urls.path` functions in +the ``polls.urls`` module, you can remove a reliance on specific URL paths +defined in your url configurations by using the ``{% url %}`` template tag: + +.. code-block:: html+django + +
  • {{ question.question_text }}
  • + +The way this works is by looking up the URL definition as specified in the +``polls.urls`` module. You can see exactly where the URL name of 'detail' is +defined below:: + + ... + # the 'name' value as called by the {% url %} template tag + path("/", views.detail, name="detail"), + ... + +If you want to change the URL of the polls detail view to something else, +perhaps to something like ``polls/specifics/12/`` instead of doing it in the +template (or templates) you would change it in ``polls/urls.py``:: + + ... + # added the word 'specifics' + path("specifics//", views.detail, name="detail"), + ... + +Namespacing URL names +===================== + +The tutorial project has just one app, ``polls``. In real Django projects, +there might be five, ten, twenty apps or more. How does Django differentiate +the URL names between them? For example, the ``polls`` app has a ``detail`` +view, and so might an app on the same project that is for a blog. How does one +make it so that Django knows which app view to create for a url when using the +``{% url %}`` template tag? + +The answer is to add namespaces to your URLconf. In the ``polls/urls.py`` +file, go ahead and add an ``app_name`` to set the application namespace: + +.. code-block:: python + :caption: ``polls/urls.py`` + + from django.urls import path + + from . import views + + app_name = "polls" + urlpatterns = [ + path("", views.index, name="index"), + path("/", views.detail, name="detail"), + path("/results/", views.results, name="results"), + path("/vote/", views.vote, name="vote"), + ] + +Now change your ``polls/index.html`` template from: + +.. code-block:: html+django + :caption: ``polls/templates/polls/index.html`` + +
  • {{ question.question_text }}
  • + +to point at the namespaced detail view: + +.. code-block:: html+django + :caption: ``polls/templates/polls/index.html`` + +
  • {{ question.question_text }}
  • + +When you're comfortable with writing views, read :doc:`part 4 of this tutorial +` to learn the basics about form processing and generic +views. diff --git a/testbed/django__django/docs/intro/tutorial06.txt b/testbed/django__django/docs/intro/tutorial06.txt new file mode 100644 index 0000000000000000000000000000000000000000..312b585f29659e97b0c62bee1579af41161fdeef --- /dev/null +++ b/testbed/django__django/docs/intro/tutorial06.txt @@ -0,0 +1,133 @@ +===================================== +Writing your first Django app, part 6 +===================================== + +This tutorial begins where :doc:`Tutorial 5 ` left off. +We've built a tested web-poll application, and we'll now add a stylesheet and +an image. + +Aside from the HTML generated by the server, web applications generally need +to serve additional files — such as images, JavaScript, or CSS — necessary to +render the complete web page. In Django, we refer to these files as "static +files". + +For small projects, this isn't a big deal, because you can keep the static +files somewhere your web server can find it. However, in bigger projects -- +especially those comprised of multiple apps -- dealing with the multiple sets +of static files provided by each application starts to get tricky. + +That's what ``django.contrib.staticfiles`` is for: it collects static files +from each of your applications (and any other places you specify) into a +single location that can easily be served in production. + +.. admonition:: Where to get help: + + If you're having trouble going through this tutorial, please head over to + the :doc:`Getting Help` section of the FAQ. + +Customize your *app's* look and feel +==================================== + +First, create a directory called ``static`` in your ``polls`` directory. Django +will look for static files there, similarly to how Django finds templates +inside ``polls/templates/``. + +Django's :setting:`STATICFILES_FINDERS` setting contains a list +of finders that know how to discover static files from various +sources. One of the defaults is ``AppDirectoriesFinder`` which +looks for a "static" subdirectory in each of the +:setting:`INSTALLED_APPS`, like the one in ``polls`` we just created. The admin +site uses the same directory structure for its static files. + +Within the ``static`` directory you have just created, create another directory +called ``polls`` and within that create a file called ``style.css``. In other +words, your stylesheet should be at ``polls/static/polls/style.css``. Because +of how the ``AppDirectoriesFinder`` staticfile finder works, you can refer to +this static file in Django as ``polls/style.css``, similar to how you reference +the path for templates. + +.. admonition:: Static file namespacing + + Just like templates, we *might* be able to get away with putting our static + files directly in ``polls/static`` (rather than creating another ``polls`` + subdirectory), but it would actually be a bad idea. Django will choose the + first static file it finds whose name matches, and if you had a static file + with the same name in a *different* application, Django would be unable to + distinguish between them. We need to be able to point Django at the right + one, and the best way to ensure this is by *namespacing* them. That is, by + putting those static files inside *another* directory named for the + application itself. + +Put the following code in that stylesheet (``polls/static/polls/style.css``): + +.. code-block:: css + :caption: ``polls/static/polls/style.css`` + + li a { + color: green; + } + +Next, add the following at the top of ``polls/templates/polls/index.html``: + +.. code-block:: html+django + :caption: ``polls/templates/polls/index.html`` + + {% load static %} + + + +The ``{% static %}`` template tag generates the absolute URL of static files. + +That's all you need to do for development. + +Start the server (or restart it if it's already running): + +.. console:: + + $ python manage.py runserver + +Reload ``http://localhost:8000/polls/`` and you should see that the question +links are green (Django style!) which means that your stylesheet was properly +loaded. + +Adding a background-image +========================= + +Next, we'll create a subdirectory for images. Create an ``images`` subdirectory +in the ``polls/static/polls/`` directory. Inside this directory, add any image +file that you'd like to use as a background. For the purposes of this tutorial, +we're using a file named ``background.png``, which will have the full path +``polls/static/polls/images/background.png``. + +Then, add a reference to your image in your stylesheet +(``polls/static/polls/style.css``): + +.. code-block:: css + :caption: ``polls/static/polls/style.css`` + + body { + background: white url("images/background.png") no-repeat; + } + +Reload ``http://localhost:8000/polls/`` and you should see the background +loaded in the top left of the screen. + +.. warning:: + + The ``{% static %}`` template tag is not available for use in static files + which aren't generated by Django, like your stylesheet. You should always + use **relative paths** to link your static files between each other, + because then you can change :setting:`STATIC_URL` (used by the + :ttag:`static` template tag to generate its URLs) without having to modify + a bunch of paths in your static files as well. + +These are the **basics**. For more details on settings and other bits included +with the framework see +:doc:`the static files howto ` and +:doc:`the staticfiles reference `. :doc:`Deploying +static files ` discusses how to use static +files on a real server. + +When you're comfortable with the static files, read :doc:`part 7 of this +tutorial ` to learn how to customize Django's +automatically-generated admin site. diff --git a/testbed/django__django/docs/intro/whatsnext.txt b/testbed/django__django/docs/intro/whatsnext.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca55b12d7a0d57d400675b22b2fd16ab0205b323 --- /dev/null +++ b/testbed/django__django/docs/intro/whatsnext.txt @@ -0,0 +1,222 @@ +================= +What to read next +================= + +So you've read all the :doc:`introductory material ` and have +decided you'd like to keep using Django. We've only just scratched the surface +with this intro (in fact, if you've read every single word, you've read about +5% of the overall documentation). + +So what's next? + +Well, we've always been big fans of learning by doing. At this point you should +know enough to start a project of your own and start fooling around. As you need +to learn new tricks, come back to the documentation. + +We've put a lot of effort into making Django's documentation useful, clear and +as complete as possible. The rest of this document explains more about how the +documentation works so that you can get the most out of it. + +(Yes, this is documentation about documentation. Rest assured we have no plans +to write a document about how to read the document about documentation.) + +Finding documentation +===================== + +Django's got a *lot* of documentation -- almost 450,000 words and counting -- +so finding what you need can sometimes be tricky. A good place to start +is the :ref:`genindex`. We also recommend using the builtin search feature. + +Or you can just browse around! + +How the documentation is organized +================================== + +Django's main documentation is broken up into "chunks" designed to fill +different needs: + +* The :doc:`introductory material ` is designed for people new + to Django -- or to web development in general. It doesn't cover anything + in depth, but instead gives a high-level overview of how developing in + Django "feels". + +* The :doc:`topic guides `, on the other hand, dive deep into + individual parts of Django. There are complete guides to Django's + :doc:`model system `, :doc:`template engine + `, :doc:`forms framework `, and much + more. + + This is probably where you'll want to spend most of your time; if you work + your way through these guides you should come out knowing pretty much + everything there is to know about Django. + +* Web development is often broad, not deep -- problems span many domains. + We've written a set of :doc:`how-to guides ` that answer + common "How do I ...?" questions. Here you'll find information about + :doc:`generating PDFs with Django `, :doc:`writing + custom template tags `, and more. + + Answers to really common questions can also be found in the :doc:`FAQ + `. + +* The guides and how-to's don't cover every single class, function, and + method available in Django -- that would be overwhelming when you're + trying to learn. Instead, details about individual classes, functions, + methods, and modules are kept in the :doc:`reference `. This is + where you'll turn to find the details of a particular function or + whatever you need. + +* If you are interested in deploying a project for public use, our docs have + :doc:`several guides` for various deployment + setups as well as a :doc:`deployment checklist` + for some things you'll need to think about. + +* Finally, there's some "specialized" documentation not usually relevant to + most developers. This includes the :doc:`release notes ` and + :doc:`internals documentation ` for those who want to add + code to Django itself, and a :doc:`few other things that don't fit elsewhere + `. + + +How documentation is updated +============================ + +Just as the Django code base is developed and improved on a daily basis, our +documentation is consistently improving. We improve documentation for several +reasons: + +* To make content fixes, such as grammar/typo corrections. + +* To add information and/or examples to existing sections that need to be + expanded. + +* To document Django features that aren't yet documented. (The list of + such features is shrinking but exists nonetheless.) + +* To add documentation for new features as new features get added, or as + Django APIs or behaviors change. + +Django's documentation is kept in the same source control system as its code. It +lives in the :source:`docs` directory of our Git repository. Each document +online is a separate text file in the repository. + +Where to get it +=============== + +You can read Django documentation in several ways. They are, in order of +preference: + +On the web +---------- + +The most recent version of the Django documentation lives at +https://docs.djangoproject.com/en/dev/. These HTML pages are generated +automatically from the text files in source control. That means they reflect the +"latest and greatest" in Django -- they include the very latest corrections and +additions, and they discuss the latest Django features, which may only be +available to users of the Django development version. (See +:ref:`differences-between-doc-versions` below.) + +We encourage you to help improve the docs by submitting changes, corrections and +suggestions in the `ticket system`_. The Django developers actively monitor the +ticket system and use your feedback to improve the documentation for everybody. + +Note, however, that tickets should explicitly relate to the documentation, +rather than asking broad tech-support questions. If you need help with your +particular Django setup, try the |django-users| mailing list or the `#django +IRC channel`_ instead. + +.. _ticket system: https://code.djangoproject.com/ +.. _#django IRC channel: https://web.libera.chat/#django + +In plain text +------------- + +For offline reading, or just for convenience, you can read the Django +documentation in plain text. + +If you're using an official release of Django, the zipped package (tarball) of +the code includes a ``docs/`` directory, which contains all the documentation +for that release. + +If you're using the development version of Django (aka the main branch), the +``docs/`` directory contains all of the documentation. You can update your +Git checkout to get the latest changes. + +One low-tech way of taking advantage of the text documentation is by using the +Unix ``grep`` utility to search for a phrase in all of the documentation. For +example, this will show you each mention of the phrase "max_length" in any +Django document: + +.. console:: + + $ grep -r max_length /path/to/django/docs/ + +As HTML, locally +---------------- + +You can get a local copy of the HTML documentation following a few steps: + +* Django's documentation uses a system called Sphinx__ to convert from + plain text to HTML. You'll need to install Sphinx by either downloading + and installing the package from the Sphinx website, or with ``pip``: + + .. console:: + + $ python -m pip install Sphinx + +* Then, use the included ``Makefile`` to turn the documentation into HTML: + + .. code-block:: console + + $ cd path/to/django/docs + $ make html + + You'll need `GNU Make`__ installed for this. + + If you're on Windows you can alternatively use the included batch file: + + .. code-block:: bat + + cd path\to\django\docs + make.bat html + +* The HTML documentation will be placed in ``docs/_build/html``. + +__ https://www.sphinx-doc.org/ +__ https://www.gnu.org/software/make/ + +.. _differences-between-doc-versions: + +Differences between versions +============================ + +The text documentation in the main branch of the Git repository contains the +"latest and greatest" changes and additions. These changes include +documentation of new features targeted for Django's next :term:`feature +release `. For that reason, it's worth pointing out our policy +to highlight recent changes and additions to Django. + +We follow this policy: + +* The development documentation at https://docs.djangoproject.com/en/dev/ is + from the main branch. These docs correspond to the latest feature release, + plus whatever features have been added/changed in the framework since then. + +* As we add features to Django's development version, we update the + documentation in the same Git commit transaction. + +* To distinguish feature changes/additions in the docs, we use the phrase: + "New in Django Development version" for the version of Django that hasn't + been released yet, or "New in version X.Y" for released versions. + +* Documentation fixes and improvements may be backported to the last release + branch, at the discretion of the merger, however, once a version of Django is + :ref:`no longer supported`, that version of the + docs won't get any further updates. + +* The `main documentation web page`_ includes links to documentation for + previous versions. Be sure you are using the version of the docs + corresponding to the version of Django you are using! + +.. _main documentation web page: https://docs.djangoproject.com/en/dev/ diff --git a/testbed/django__django/docs/man/django-admin.1 b/testbed/django__django/docs/man/django-admin.1 new file mode 100644 index 0000000000000000000000000000000000000000..48ec5b1440c86ce4f17daab9ff057e53a69a842c --- /dev/null +++ b/testbed/django__django/docs/man/django-admin.1 @@ -0,0 +1,2826 @@ +.\" Man page generated from reStructuredText. +. +. +.nr rst2man-indent-level 0 +. +.de1 rstReportMargin +\\$1 \\n[an-margin] +level \\n[rst2man-indent-level] +level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] +- +\\n[rst2man-indent0] +\\n[rst2man-indent1] +\\n[rst2man-indent2] +.. +.de1 INDENT +.\" .rstReportMargin pre: +. RS \\$1 +. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] +. nr rst2man-indent-level +1 +.\" .rstReportMargin post: +.. +.de UNINDENT +. RE +.\" indent \\n[an-margin] +.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] +.nr rst2man-indent-level -1 +.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] +.in \\n[rst2man-indent\\n[rst2man-indent-level]]u +.. +.TH "DJANGO-ADMIN" "1" "January 15, 2023" "4.2" "Django" +.SH NAME +django-admin \- Utility script for the Django web framework +.sp +\fBdjango\-admin\fP is Django\(aqs command\-line utility for administrative tasks. +This document outlines all it can do. +.sp +In addition, \fBmanage.py\fP is automatically created in each Django project. It +does the same thing as \fBdjango\-admin\fP but also sets the +\fI\%DJANGO_SETTINGS_MODULE\fP environment variable so that it points to your +project\(aqs \fBsettings.py\fP file. +.sp +The \fBdjango\-admin\fP script should be on your system path if you installed +Django via \fBpip\fP\&. If it\(aqs not in your path, ensure you have your virtual +environment activated. +.sp +Generally, when working on a single Django project, it\(aqs easier to use +\fBmanage.py\fP than \fBdjango\-admin\fP\&. If you need to switch between multiple +Django settings files, use \fBdjango\-admin\fP with +\fI\%DJANGO_SETTINGS_MODULE\fP or the \fI\%\-\-settings\fP command line +option. +.sp +The command\-line examples throughout this document use \fBdjango\-admin\fP to +be consistent, but any example can use \fBmanage.py\fP or \fBpython \-m django\fP +just as well. +.SH USAGE +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +$ django\-admin [options] +$ manage.py [options] +$ python \-m django [options] +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +\fBcommand\fP should be one of the commands listed in this document. +\fBoptions\fP, which is optional, should be zero or more of the options available +for the given command. +.SS Getting runtime help +.INDENT 0.0 +.TP +.B django\-admin help +.UNINDENT +.sp +Run \fBdjango\-admin help\fP to display usage information and a list of the +commands provided by each application. +.sp +Run \fBdjango\-admin help \-\-commands\fP to display a list of all available +commands. +.sp +Run \fBdjango\-admin help \fP to display a description of the given +command and a list of its available options. +.SS App names +.sp +Many commands take a list of "app names." An "app name" is the basename of +the package containing your models. For example, if your \fI\%INSTALLED_APPS\fP +contains the string \fB\(aqmysite.blog\(aq\fP, the app name is \fBblog\fP\&. +.SS Determining the version +.INDENT 0.0 +.TP +.B django\-admin version +.UNINDENT +.sp +Run \fBdjango\-admin version\fP to display the current Django version. +.sp +The output follows the schema described in \fI\%PEP 440\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +1.4.dev17026 +1.4a1 +1.4 +.ft P +.fi +.UNINDENT +.UNINDENT +.SS Displaying debug output +.sp +Use \fI\%\-\-verbosity\fP, where it is supported, to specify the amount of +notification and debug information that \fBdjango\-admin\fP prints to the console. +.SH AVAILABLE COMMANDS +.SS \fBcheck\fP +.INDENT 0.0 +.TP +.B django\-admin check [app_label [app_label ...]] +.UNINDENT +.sp +Uses the \fI\%system check framework\fP to inspect the entire +Django project for common problems. +.sp +By default, all apps will be checked. You can check a subset of apps by +providing a list of app labels as arguments: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin check auth admin myapp +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-tag TAGS, \-t TAGS +.UNINDENT +.sp +The system check framework performs many different types of checks that are +\fI\%categorized with tags\fP\&. You can use these +tags to restrict the checks performed to just those in a particular category. +For example, to perform only models and compatibility checks, run: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin check \-\-tag models \-\-tag compatibility +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database to run checks requiring database access: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin check \-\-database default \-\-database other +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +By default, these checks will not be run. +.INDENT 0.0 +.TP +.B \-\-list\-tags +.UNINDENT +.sp +Lists all available tags. +.INDENT 0.0 +.TP +.B \-\-deploy +.UNINDENT +.sp +Activates some additional checks that are only relevant in a deployment setting. +.sp +You can use this option in your local development environment, but since your +local development settings module may not have many of your production settings, +you will probably want to point the \fBcheck\fP command at a different settings +module, either by setting the \fI\%DJANGO_SETTINGS_MODULE\fP environment +variable, or by passing the \fB\-\-settings\fP option: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin check \-\-deploy \-\-settings=production_settings +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Or you could run it directly on a production or staging deployment to verify +that the correct settings are in use (omitting \fB\-\-settings\fP). You could even +make it part of your integration test suite. +.INDENT 0.0 +.TP +.B \-\-fail\-level {CRITICAL,ERROR,WARNING,INFO,DEBUG} +.UNINDENT +.sp +Specifies the message level that will cause the command to exit with a non\-zero +status. Default is \fBERROR\fP\&. +.SS \fBcompilemessages\fP +.INDENT 0.0 +.TP +.B django\-admin compilemessages +.UNINDENT +.sp +Compiles \fB\&.po\fP files created by \fI\%makemessages\fP to \fB\&.mo\fP files for +use with the built\-in gettext support. See \fI\%Internationalization and localization\fP\&. +.INDENT 0.0 +.TP +.B \-\-locale LOCALE, \-l LOCALE +.UNINDENT +.sp +Specifies the locale(s) to process. If not provided, all locales are processed. +.INDENT 0.0 +.TP +.B \-\-exclude EXCLUDE, \-x EXCLUDE +.UNINDENT +.sp +Specifies the locale(s) to exclude from processing. If not provided, no locales +are excluded. +.INDENT 0.0 +.TP +.B \-\-use\-fuzzy, \-f +.UNINDENT +.sp +Includes \fI\%fuzzy translations\fP into compiled files. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin compilemessages \-\-locale=pt_BR +django\-admin compilemessages \-\-locale=pt_BR \-\-locale=fr \-f +django\-admin compilemessages \-l pt_BR +django\-admin compilemessages \-l pt_BR \-l fr \-\-use\-fuzzy +django\-admin compilemessages \-\-exclude=pt_BR +django\-admin compilemessages \-\-exclude=pt_BR \-\-exclude=fr +django\-admin compilemessages \-x pt_BR +django\-admin compilemessages \-x pt_BR \-x fr +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-ignore PATTERN, \-i PATTERN +.UNINDENT +.sp +Ignores directories matching the given \fI\%glob\fP\-style pattern. Use +multiple times to ignore more. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin compilemessages \-\-ignore=cache \-\-ignore=outdated/*/locale +.ft P +.fi +.UNINDENT +.UNINDENT +.SS \fBcreatecachetable\fP +.INDENT 0.0 +.TP +.B django\-admin createcachetable +.UNINDENT +.sp +Creates the cache tables for use with the database cache backend using the +information from your settings file. See \fI\%Django\(aqs cache framework\fP for more +information. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database in which the cache table(s) will be created. Defaults to +\fBdefault\fP\&. +.INDENT 0.0 +.TP +.B \-\-dry\-run +.UNINDENT +.sp +Prints the SQL that would be run without actually running it, so you can +customize it or use the migrations framework. +.SS \fBdbshell\fP +.INDENT 0.0 +.TP +.B django\-admin dbshell +.UNINDENT +.sp +Runs the command\-line client for the database engine specified in your +\fI\%ENGINE\fP setting, with the connection parameters +specified in your \fI\%USER\fP, \fI\%PASSWORD\fP, etc., settings. +.INDENT 0.0 +.IP \(bu 2 +For PostgreSQL, this runs the \fBpsql\fP command\-line client. +.IP \(bu 2 +For MySQL, this runs the \fBmysql\fP command\-line client. +.IP \(bu 2 +For SQLite, this runs the \fBsqlite3\fP command\-line client. +.IP \(bu 2 +For Oracle, this runs the \fBsqlplus\fP command\-line client. +.UNINDENT +.sp +This command assumes the programs are on your \fBPATH\fP so that a call to +the program name (\fBpsql\fP, \fBmysql\fP, \fBsqlite3\fP, \fBsqlplus\fP) will find the +program in the right place. There\(aqs no way to specify the location of the +program manually. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database onto which to open a shell. Defaults to \fBdefault\fP\&. +.INDENT 0.0 +.TP +.B \-\- ARGUMENTS +.UNINDENT +.sp +Any arguments following a \fB\-\-\fP divider will be passed on to the underlying +command\-line client. For example, with PostgreSQL you can use the \fBpsql\fP +command\(aqs \fB\-c\fP flag to execute a raw SQL query directly: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +$ django\-admin dbshell \-\- \-c \(aqselect current_user\(aq + current_user +\-\-\-\-\-\-\-\-\-\-\-\-\-\- + postgres +(1 row) +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +On MySQL/MariaDB, you can do this with the \fBmysql\fP command\(aqs \fB\-e\fP flag: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +$ django\-admin dbshell \-\- \-e "select user()" ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| user() | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +| djangonaut@localhost | ++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +\fBNOTE:\fP +.INDENT 0.0 +.INDENT 3.5 +Be aware that not all options set in the \fI\%OPTIONS\fP part of your +database configuration in \fI\%DATABASES\fP are passed to the +command\-line client, e.g. \fB\(aqisolation_level\(aq\fP\&. +.UNINDENT +.UNINDENT +.SS \fBdiffsettings\fP +.INDENT 0.0 +.TP +.B django\-admin diffsettings +.UNINDENT +.sp +Displays differences between the current settings file and Django\(aqs default +settings (or another settings file specified by \fI\%\-\-default\fP). +.sp +Settings that don\(aqt appear in the defaults are followed by \fB"###"\fP\&. For +example, the default settings don\(aqt define \fI\%ROOT_URLCONF\fP, so +\fI\%ROOT_URLCONF\fP is followed by \fB"###"\fP in the output of +\fBdiffsettings\fP\&. +.INDENT 0.0 +.TP +.B \-\-all +.UNINDENT +.sp +Displays all settings, even if they have Django\(aqs default value. Such settings +are prefixed by \fB"###"\fP\&. +.INDENT 0.0 +.TP +.B \-\-default MODULE +.UNINDENT +.sp +The settings module to compare the current settings against. Leave empty to +compare against Django\(aqs default settings. +.INDENT 0.0 +.TP +.B \-\-output {hash,unified} +.UNINDENT +.sp +Specifies the output format. Available values are \fBhash\fP and \fBunified\fP\&. +\fBhash\fP is the default mode that displays the output that\(aqs described above. +\fBunified\fP displays the output similar to \fBdiff \-u\fP\&. Default settings are +prefixed with a minus sign, followed by the changed setting prefixed with a +plus sign. +.SS \fBdumpdata\fP +.INDENT 0.0 +.TP +.B django\-admin dumpdata [app_label[.ModelName] [app_label[.ModelName] ...]] +.UNINDENT +.sp +Outputs to standard output all data in the database associated with the named +application(s). +.sp +If no application name is provided, all installed applications will be dumped. +.sp +The output of \fBdumpdata\fP can be used as input for \fI\%loaddata\fP\&. +.sp +When result of \fBdumpdata\fP is saved as a file, it can serve as a +\fI\%fixture\fP for +\fI\%tests\fP or as an +\fI\%initial data\fP\&. +.sp +Note that \fBdumpdata\fP uses the default manager on the model for selecting the +records to dump. If you\(aqre using a \fI\%custom manager\fP as +the default manager and it filters some of the available records, not all of the +objects will be dumped. +.INDENT 0.0 +.TP +.B \-\-all, \-a +.UNINDENT +.sp +Uses Django\(aqs base manager, dumping records which might otherwise be filtered +or modified by a custom manager. +.INDENT 0.0 +.TP +.B \-\-format FORMAT +.UNINDENT +.sp +Specifies the serialization format of the output. Defaults to JSON. Supported +formats are listed in \fI\%Serialization formats\fP\&. +.INDENT 0.0 +.TP +.B \-\-indent INDENT +.UNINDENT +.sp +Specifies the number of indentation spaces to use in the output. Defaults to +\fBNone\fP which displays all data on single line. +.INDENT 0.0 +.TP +.B \-\-exclude EXCLUDE, \-e EXCLUDE +.UNINDENT +.sp +Prevents specific applications or models (specified in the form of +\fBapp_label.ModelName\fP) from being dumped. If you specify a model name, then +only that model will be excluded, rather than the entire application. You can +also mix application names and model names. +.sp +If you want to exclude multiple applications, pass \fB\-\-exclude\fP more than +once: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin dumpdata \-\-exclude=auth \-\-exclude=contenttypes +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database from which data will be dumped. Defaults to \fBdefault\fP\&. +.INDENT 0.0 +.TP +.B \-\-natural\-foreign +.UNINDENT +.sp +Uses the \fBnatural_key()\fP model method to serialize any foreign key and +many\-to\-many relationship to objects of the type that defines the method. If +you\(aqre dumping \fBcontrib.auth\fP \fBPermission\fP objects or +\fBcontrib.contenttypes\fP \fBContentType\fP objects, you should probably use this +flag. See the \fI\%natural keys\fP +documentation for more details on this and the next option. +.INDENT 0.0 +.TP +.B \-\-natural\-primary +.UNINDENT +.sp +Omits the primary key in the serialized data of this object since it can be +calculated during deserialization. +.INDENT 0.0 +.TP +.B \-\-pks PRIMARY_KEYS +.UNINDENT +.sp +Outputs only the objects specified by a comma separated list of primary keys. +This is only available when dumping one model. By default, all the records of +the model are output. +.INDENT 0.0 +.TP +.B \-\-output OUTPUT, \-o OUTPUT +.UNINDENT +.sp +Specifies a file to write the serialized data to. By default, the data goes to +standard output. +.sp +When this option is set and \fB\-\-verbosity\fP is greater than 0 (the default), a +progress bar is shown in the terminal. +.SS Fixtures compression +.sp +The output file can be compressed with one of the \fBbz2\fP, \fBgz\fP, \fBlzma\fP, or +\fBxz\fP formats by ending the filename with the corresponding extension. +For example, to output the data as a compressed JSON file: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin dumpdata \-o mydata.json.gz +.ft P +.fi +.UNINDENT +.UNINDENT +.SS \fBflush\fP +.INDENT 0.0 +.TP +.B django\-admin flush +.UNINDENT +.sp +Removes all data from the database and re\-executes any post\-synchronization +handlers. The table of which migrations have been applied is not cleared. +.sp +If you would rather start from an empty database and rerun all migrations, you +should drop and recreate the database and then run \fI\%migrate\fP instead. +.INDENT 0.0 +.TP +.B \-\-noinput, \-\-no\-input +.UNINDENT +.sp +Suppresses all user prompts. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database to flush. Defaults to \fBdefault\fP\&. +.SS \fBinspectdb\fP +.INDENT 0.0 +.TP +.B django\-admin inspectdb [table [table ...]] +.UNINDENT +.sp +Introspects the database tables in the database pointed\-to by the +\fI\%NAME\fP setting and outputs a Django model module (a \fBmodels.py\fP +file) to standard output. +.sp +You may choose what tables or views to inspect by passing their names as +arguments. If no arguments are provided, models are created for views only if +the \fI\%\-\-include\-views\fP option is used. Models for partition tables are +created on PostgreSQL if the \fI\%\-\-include\-partitions\fP option is used. +.sp +Use this if you have a legacy database with which you\(aqd like to use Django. +The script will inspect the database and create a model for each table within +it. +.sp +As you might expect, the created models will have an attribute for every field +in the table. Note that \fBinspectdb\fP has a few special cases in its field\-name +output: +.INDENT 0.0 +.IP \(bu 2 +If \fBinspectdb\fP cannot map a column\(aqs type to a model field type, it\(aqll +use \fBTextField\fP and will insert the Python comment +\fB\(aqThis field type is a guess.\(aq\fP next to the field in the generated +model. The recognized fields may depend on apps listed in +\fI\%INSTALLED_APPS\fP\&. For example, \fI\%django.contrib.postgres\fP adds +recognition for several PostgreSQL\-specific field types. +.IP \(bu 2 +If the database column name is a Python reserved word (such as +\fB\(aqpass\(aq\fP, \fB\(aqclass\(aq\fP or \fB\(aqfor\(aq\fP), \fBinspectdb\fP will append +\fB\(aq_field\(aq\fP to the attribute name. For example, if a table has a column +\fB\(aqfor\(aq\fP, the generated model will have a field \fB\(aqfor_field\(aq\fP, with +the \fBdb_column\fP attribute set to \fB\(aqfor\(aq\fP\&. \fBinspectdb\fP will insert +the Python comment +\fB\(aqField renamed because it was a Python reserved word.\(aq\fP next to the +field. +.UNINDENT +.sp +This feature is meant as a shortcut, not as definitive model generation. After +you run it, you\(aqll want to look over the generated models yourself to make +customizations. In particular, you\(aqll need to rearrange models\(aq order, so that +models that refer to other models are ordered properly. +.sp +Django doesn\(aqt create database defaults when a +\fI\%default\fP is specified on a model field. +Similarly, database defaults aren\(aqt translated to model field defaults or +detected in any fashion by \fBinspectdb\fP\&. +.sp +By default, \fBinspectdb\fP creates unmanaged models. That is, \fBmanaged = False\fP +in the model\(aqs \fBMeta\fP class tells Django not to manage each table\(aqs creation, +modification, and deletion. If you do want to allow Django to manage the +table\(aqs lifecycle, you\(aqll need to change the +\fI\%managed\fP option to \fBTrue\fP (or remove +it because \fBTrue\fP is its default value). +.SS Database\-specific notes +.SS Oracle +.INDENT 0.0 +.IP \(bu 2 +Models are created for materialized views if \fI\%\-\-include\-views\fP is +used. +.UNINDENT +.SS PostgreSQL +.INDENT 0.0 +.IP \(bu 2 +Models are created for foreign tables. +.IP \(bu 2 +Models are created for materialized views if +\fI\%\-\-include\-views\fP is used. +.IP \(bu 2 +Models are created for partition tables if +\fI\%\-\-include\-partitions\fP is used. +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database to introspect. Defaults to \fBdefault\fP\&. +.INDENT 0.0 +.TP +.B \-\-include\-partitions +.UNINDENT +.sp +If this option is provided, models are also created for partitions. +.sp +Only support for PostgreSQL is implemented. +.INDENT 0.0 +.TP +.B \-\-include\-views +.UNINDENT +.sp +If this option is provided, models are also created for database views. +.SS \fBloaddata\fP +.INDENT 0.0 +.TP +.B django\-admin loaddata fixture [fixture ...] +.UNINDENT +.sp +Searches for and loads the contents of the named +\fI\%fixture\fP into the database. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database into which the data will be loaded. Defaults to +\fBdefault\fP\&. +.INDENT 0.0 +.TP +.B \-\-ignorenonexistent, \-i +.UNINDENT +.sp +Ignores fields and models that may have been removed since the fixture was +originally generated. +.INDENT 0.0 +.TP +.B \-\-app APP_LABEL +.UNINDENT +.sp +Specifies a single app to look for fixtures in rather than looking in all apps. +.INDENT 0.0 +.TP +.B \-\-format FORMAT +.UNINDENT +.sp +Specifies the \fI\%serialization format\fP (e.g., +\fBjson\fP or \fBxml\fP) for fixtures \fI\%read from stdin\fP\&. +.INDENT 0.0 +.TP +.B \-\-exclude EXCLUDE, \-e EXCLUDE +.UNINDENT +.sp +Excludes loading the fixtures from the given applications and/or models (in the +form of \fBapp_label\fP or \fBapp_label.ModelName\fP). Use the option multiple +times to exclude more than one app or model. +.SS Loading fixtures from \fBstdin\fP +.sp +You can use a dash as the fixture name to load input from \fBsys.stdin\fP\&. For +example: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin loaddata \-\-format=json \- +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +When reading from \fBstdin\fP, the \fI\%\-\-format\fP option +is required to specify the \fI\%serialization format\fP +of the input (e.g., \fBjson\fP or \fBxml\fP). +.sp +Loading from \fBstdin\fP is useful with standard input and output redirections. +For example: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin dumpdata \-\-format=json \-\-database=test app_label.ModelName | django\-admin loaddata \-\-format=json \-\-database=prod \- +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +The \fI\%dumpdata\fP command can be used to generate input for \fBloaddata\fP\&. +.sp +\fBSEE ALSO:\fP +.INDENT 0.0 +.INDENT 3.5 +For more detail about fixtures see the \fI\%Fixtures\fP topic. +.UNINDENT +.UNINDENT +.SS \fBmakemessages\fP +.INDENT 0.0 +.TP +.B django\-admin makemessages +.UNINDENT +.sp +Runs over the entire source tree of the current directory and pulls out all +strings marked for translation. It creates (or updates) a message file in the +conf/locale (in the Django tree) or locale (for project and application) +directory. After making changes to the messages files you need to compile them +with \fI\%compilemessages\fP for use with the builtin gettext support. See +the \fI\%i18n documentation\fP for details. +.sp +This command doesn\(aqt require configured settings. However, when settings aren\(aqt +configured, the command can\(aqt ignore the \fI\%MEDIA_ROOT\fP and +\fI\%STATIC_ROOT\fP directories or include \fI\%LOCALE_PATHS\fP\&. +.INDENT 0.0 +.TP +.B \-\-all, \-a +.UNINDENT +.sp +Updates the message files for all available languages. +.INDENT 0.0 +.TP +.B \-\-extension EXTENSIONS, \-e EXTENSIONS +.UNINDENT +.sp +Specifies a list of file extensions to examine (default: \fBhtml\fP, \fBtxt\fP, +\fBpy\fP or \fBjs\fP if \fI\%\-\-domain\fP is \fBjs\fP). +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin makemessages \-\-locale=de \-\-extension xhtml +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Separate multiple extensions with commas or use \fB\-e\fP or \fB\-\-extension\fP +multiple times: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin makemessages \-\-locale=de \-\-extension=html,txt \-\-extension xml +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-locale LOCALE, \-l LOCALE +.UNINDENT +.sp +Specifies the locale(s) to process. +.INDENT 0.0 +.TP +.B \-\-exclude EXCLUDE, \-x EXCLUDE +.UNINDENT +.sp +Specifies the locale(s) to exclude from processing. If not provided, no locales +are excluded. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin makemessages \-\-locale=pt_BR +django\-admin makemessages \-\-locale=pt_BR \-\-locale=fr +django\-admin makemessages \-l pt_BR +django\-admin makemessages \-l pt_BR \-l fr +django\-admin makemessages \-\-exclude=pt_BR +django\-admin makemessages \-\-exclude=pt_BR \-\-exclude=fr +django\-admin makemessages \-x pt_BR +django\-admin makemessages \-x pt_BR \-x fr +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-domain DOMAIN, \-d DOMAIN +.UNINDENT +.sp +Specifies the domain of the messages files. Supported options are: +.INDENT 0.0 +.IP \(bu 2 +\fBdjango\fP for all \fB*.py\fP, \fB*.html\fP and \fB*.txt\fP files (default) +.IP \(bu 2 +\fBdjangojs\fP for \fB*.js\fP files +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-symlinks, \-s +.UNINDENT +.sp +Follows symlinks to directories when looking for new translation strings. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin makemessages \-\-locale=de \-\-symlinks +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-ignore PATTERN, \-i PATTERN +.UNINDENT +.sp +Ignores files or directories matching the given \fI\%glob\fP\-style pattern. Use +multiple times to ignore more. +.sp +These patterns are used by default: \fB\(aqCVS\(aq\fP, \fB\(aq.*\(aq\fP, \fB\(aq*~\(aq\fP, \fB\(aq*.pyc\(aq\fP\&. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin makemessages \-\-locale=en_US \-\-ignore=apps/* \-\-ignore=secret/*.html +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-no\-default\-ignore +.UNINDENT +.sp +Disables the default values of \fB\-\-ignore\fP\&. +.INDENT 0.0 +.TP +.B \-\-no\-wrap +.UNINDENT +.sp +Disables breaking long message lines into several lines in language files. +.INDENT 0.0 +.TP +.B \-\-no\-location +.UNINDENT +.sp +Suppresses writing \(aq\fB#: filename:line\fP’ comment lines in language files. +Using this option makes it harder for technically skilled translators to +understand each message\(aqs context. +.INDENT 0.0 +.TP +.B \-\-add\-location [{full,file,never}] +.UNINDENT +.sp +Controls \fB#: filename:line\fP comment lines in language files. If the option +is: +.INDENT 0.0 +.IP \(bu 2 +\fBfull\fP (the default if not given): the lines include both file name and +line number. +.IP \(bu 2 +\fBfile\fP: the line number is omitted. +.IP \(bu 2 +\fBnever\fP: the lines are suppressed (same as \fI\%\-\-no\-location\fP). +.UNINDENT +.sp +Requires \fBgettext\fP 0.19 or newer. +.INDENT 0.0 +.TP +.B \-\-keep\-pot +.UNINDENT +.sp +Prevents deleting the temporary \fB\&.pot\fP files generated before creating the +\fB\&.po\fP file. This is useful for debugging errors which may prevent the final +language files from being created. +.sp +\fBSEE ALSO:\fP +.INDENT 0.0 +.INDENT 3.5 +See \fI\%Customizing the makemessages command\fP for instructions on how to customize +the keywords that \fI\%makemessages\fP passes to \fBxgettext\fP\&. +.UNINDENT +.UNINDENT +.SS \fBmakemigrations\fP +.INDENT 0.0 +.TP +.B django\-admin makemigrations [app_label [app_label ...]] +.UNINDENT +.sp +Creates new migrations based on the changes detected to your models. +Migrations, their relationship with apps and more are covered in depth in +\fI\%the migrations documentation\fP\&. +.sp +Providing one or more app names as arguments will limit the migrations created +to the app(s) specified and any dependencies needed (the table at the other end +of a \fBForeignKey\fP, for example). +.sp +To add migrations to an app that doesn\(aqt have a \fBmigrations\fP directory, run +\fBmakemigrations\fP with the app\(aqs \fBapp_label\fP\&. +.INDENT 0.0 +.TP +.B \-\-noinput, \-\-no\-input +.UNINDENT +.sp +Suppresses all user prompts. If a suppressed prompt cannot be resolved +automatically, the command will exit with error code 3. +.INDENT 0.0 +.TP +.B \-\-empty +.UNINDENT +.sp +Outputs an empty migration for the specified apps, for manual editing. This is +for advanced users and should not be used unless you are familiar with the +migration format, migration operations, and the dependencies between your +migrations. +.INDENT 0.0 +.TP +.B \-\-dry\-run +.UNINDENT +.sp +Shows what migrations would be made without actually writing any migrations +files to disk. Using this option along with \fB\-\-verbosity 3\fP will also show +the complete migrations files that would be written. +.INDENT 0.0 +.TP +.B \-\-merge +.UNINDENT +.sp +Enables fixing of migration conflicts. +.INDENT 0.0 +.TP +.B \-\-name NAME, \-n NAME +.UNINDENT +.sp +Allows naming the generated migration(s) instead of using a generated name. The +name must be a valid Python \fI\%identifier\fP\&. +.INDENT 0.0 +.TP +.B \-\-no\-header +.UNINDENT +.sp +Generate migration files without Django version and timestamp header. +.INDENT 0.0 +.TP +.B \-\-check +.UNINDENT +.sp +Makes \fBmakemigrations\fP exit with a non\-zero status when model changes without +migrations are detected. +.sp +In older versions, the missing migrations were also created when using the +\fB\-\-check\fP option. + +.INDENT 0.0 +.TP +.B \-\-scriptable +.UNINDENT +.sp + +.sp +Diverts log output and input prompts to \fBstderr\fP, writing only paths of +generated migration files to \fBstdout\fP\&. +.INDENT 0.0 +.TP +.B \-\-update +.UNINDENT +.sp + +.sp +Merges model changes into the latest migration and optimize the resulting +operations. +.SS \fBmigrate\fP +.INDENT 0.0 +.TP +.B django\-admin migrate [app_label] [migration_name] +.UNINDENT +.sp +Synchronizes the database state with the current set of models and migrations. +Migrations, their relationship with apps and more are covered in depth in +\fI\%the migrations documentation\fP\&. +.sp +The behavior of this command changes depending on the arguments provided: +.INDENT 0.0 +.IP \(bu 2 +No arguments: All apps have all of their migrations run. +.IP \(bu 2 +\fB\fP: The specified app has its migrations run, up to the most +recent migration. This may involve running other apps\(aq migrations too, due +to dependencies. +.IP \(bu 2 +\fB \fP: Brings the database schema to a state where +the named migration is applied, but no later migrations in the same app are +applied. This may involve unapplying migrations if you have previously +migrated past the named migration. You can use a prefix of the migration +name, e.g. \fB0001\fP, as long as it\(aqs unique for the given app name. Use the +name \fBzero\fP to migrate all the way back i.e. to revert all applied +migrations for an app. +.UNINDENT +.sp +\fBWARNING:\fP +.INDENT 0.0 +.INDENT 3.5 +When unapplying migrations, all dependent migrations will also be +unapplied, regardless of \fB\fP\&. You can use \fB\-\-plan\fP to check +which migrations will be unapplied. +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database to migrate. Defaults to \fBdefault\fP\&. +.INDENT 0.0 +.TP +.B \-\-fake +.UNINDENT +.sp +Marks the migrations up to the target one (following the rules above) as +applied, but without actually running the SQL to change your database schema. +.sp +This is intended for advanced users to manipulate the +current migration state directly if they\(aqre manually applying changes; +be warned that using \fB\-\-fake\fP runs the risk of putting the migration state +table into a state where manual recovery will be needed to make migrations +run correctly. +.INDENT 0.0 +.TP +.B \-\-fake\-initial +.UNINDENT +.sp +Allows Django to skip an app\(aqs initial migration if all database tables with +the names of all models created by all +\fI\%CreateModel\fP operations in that +migration already exist. This option is intended for use when first running +migrations against a database that preexisted the use of migrations. This +option does not, however, check for matching database schema beyond matching +table names and so is only safe to use if you are confident that your existing +schema matches what is recorded in your initial migration. +.INDENT 0.0 +.TP +.B \-\-plan +.UNINDENT +.sp +Shows the migration operations that will be performed for the given \fBmigrate\fP +command. +.INDENT 0.0 +.TP +.B \-\-run\-syncdb +.UNINDENT +.sp +Allows creating tables for apps without migrations. While this isn\(aqt +recommended, the migrations framework is sometimes too slow on large projects +with hundreds of models. +.INDENT 0.0 +.TP +.B \-\-noinput, \-\-no\-input +.UNINDENT +.sp +Suppresses all user prompts. An example prompt is asking about removing stale +content types. +.INDENT 0.0 +.TP +.B \-\-check +.UNINDENT +.sp +Makes \fBmigrate\fP exit with a non\-zero status when unapplied migrations are +detected. +.INDENT 0.0 +.TP +.B \-\-prune +.UNINDENT +.sp + +.sp +Deletes nonexistent migrations from the \fBdjango_migrations\fP table. This is +useful when migration files replaced by a squashed migration have been removed. +See \fI\%Squashing migrations\fP for more details. +.SS \fBoptimizemigration\fP +.sp + +.INDENT 0.0 +.TP +.B django\-admin optimizemigration app_label migration_name +.UNINDENT +.sp +Optimizes the operations for the named migration and overrides the existing +file. If the migration contains functions that must be manually copied, the +command creates a new migration file suffixed with \fB_optimized\fP that is meant +to replace the named migration. +.INDENT 0.0 +.TP +.B \-\-check +.UNINDENT +.sp +Makes \fBoptimizemigration\fP exit with a non\-zero status when a migration can be +optimized. +.SS \fBrunserver\fP +.INDENT 0.0 +.TP +.B django\-admin runserver [addrport] +.UNINDENT +.sp +Starts a lightweight development web server on the local machine. By default, +the server runs on port 8000 on the IP address \fB127.0.0.1\fP\&. You can pass in an +IP address and port number explicitly. +.sp +If you run this script as a user with normal privileges (recommended), you +might not have access to start a port on a low port number. Low port numbers +are reserved for the superuser (root). +.sp +This server uses the WSGI application object specified by the +\fI\%WSGI_APPLICATION\fP setting. +.sp +DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through +security audits or performance tests. (And that\(aqs how it\(aqs gonna stay. We\(aqre in +the business of making web frameworks, not web servers, so improving this +server to be able to handle a production environment is outside the scope of +Django.) +.sp +The development server automatically reloads Python code for each request, as +needed. You don\(aqt need to restart the server for code changes to take effect. +However, some actions like adding files don\(aqt trigger a restart, so you\(aqll +have to restart the server in these cases. +.sp +If you\(aqre using Linux or MacOS and install both \fI\%pywatchman\fP and the +\fI\%Watchman\fP service, kernel signals will be used to autoreload the server +(rather than polling file modification timestamps each second). This offers +better performance on large projects, reduced response time after code changes, +more robust change detection, and a reduction in power usage. Django supports +\fBpywatchman\fP 1.2.0 and higher. +.INDENT 0.0 +.INDENT 3.5 +.IP "Large directories with many files may cause performance issues" +.sp +When using Watchman with a project that includes large non\-Python +directories like \fBnode_modules\fP, it\(aqs advisable to ignore this directory +for optimal performance. See the \fI\%watchman documentation\fP for information +on how to do this. +.UNINDENT +.UNINDENT +.INDENT 0.0 +.INDENT 3.5 +.IP "Watchman timeout" +.INDENT 0.0 +.TP +.B DJANGO_WATCHMAN_TIMEOUT +.UNINDENT +.sp +The default timeout of \fBWatchman\fP client is 5 seconds. You can change it +by setting the \fI\%DJANGO_WATCHMAN_TIMEOUT\fP environment variable. +.UNINDENT +.UNINDENT +.sp +When you start the server, and each time you change Python code while the +server is running, the system check framework will check your entire Django +project for some common errors (see the \fI\%check\fP command). If any +errors are found, they will be printed to standard output. You can use the +\fB\-\-skip\-checks\fP option to skip running system checks. +.sp +You can run as many concurrent servers as you want, as long as they\(aqre on +separate ports by executing \fBdjango\-admin runserver\fP more than once. +.sp +Note that the default IP address, \fB127.0.0.1\fP, is not accessible from other +machines on your network. To make your development server viewable to other +machines on the network, use its own IP address (e.g. \fB192.168.2.1\fP), \fB0\fP +(shortcut for \fB0.0.0.0\fP), \fB0.0.0.0\fP, or \fB::\fP (with IPv6 enabled). +.sp +You can provide an IPv6 address surrounded by brackets +(e.g. \fB[200a::1]:8000\fP). This will automatically enable IPv6 support. +.sp +A hostname containing ASCII\-only characters can also be used. +.sp +If the \fI\%staticfiles\fP contrib app is enabled +(default in new projects) the \fI\%runserver\fP command will be overridden +with its own \fI\%runserver\fP command. +.sp +Logging of each request and response of the server is sent to the +\fI\%django.server\fP logger. +.INDENT 0.0 +.TP +.B \-\-noreload +.UNINDENT +.sp +Disables the auto\-reloader. This means any Python code changes you make while +the server is running will \fInot\fP take effect if the particular Python modules +have already been loaded into memory. +.INDENT 0.0 +.TP +.B \-\-nothreading +.UNINDENT +.sp +Disables use of threading in the development server. The server is +multithreaded by default. +.INDENT 0.0 +.TP +.B \-\-ipv6, \-6 +.UNINDENT +.sp +Uses IPv6 for the development server. This changes the default IP address from +\fB127.0.0.1\fP to \fB::1\fP\&. +.SS Examples of using different ports and addresses +.sp +Port 8000 on IP address \fB127.0.0.1\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 8000 on IP address \fB1.2.3.4\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver 1.2.3.4:8000 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 7000 on IP address \fB127.0.0.1\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver 7000 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 7000 on IP address \fB1.2.3.4\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver 1.2.3.4:7000 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 8000 on IPv6 address \fB::1\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver \-6 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 7000 on IPv6 address \fB::1\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver \-6 7000 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 7000 on IPv6 address \fB2001:0db8:1234:5678::9\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver [2001:0db8:1234:5678::9]:7000 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 8000 on IPv4 address of host \fBlocalhost\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver localhost:8000 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Port 8000 on IPv6 address of host \fBlocalhost\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver \-6 localhost:8000 +.ft P +.fi +.UNINDENT +.UNINDENT +.SS Serving static files with the development server +.sp +By default, the development server doesn\(aqt serve any static files for your site +(such as CSS files, images, things under \fI\%MEDIA_URL\fP and so forth). If +you want to configure Django to serve static media, read +\fI\%How to manage static files (e.g. images, JavaScript, CSS)\fP\&. +.SS \fBsendtestemail\fP +.INDENT 0.0 +.TP +.B django\-admin sendtestemail [email [email ...]] +.UNINDENT +.sp +Sends a test email (to confirm email sending through Django is working) to the +recipient(s) specified. For example: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin sendtestemail foo@example.com bar@example.com +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +There are a couple of options, and you may use any combination of them +together: +.INDENT 0.0 +.TP +.B \-\-managers +.UNINDENT +.sp +Mails the email addresses specified in \fI\%MANAGERS\fP using +\fI\%mail_managers()\fP\&. +.INDENT 0.0 +.TP +.B \-\-admins +.UNINDENT +.sp +Mails the email addresses specified in \fI\%ADMINS\fP using +\fI\%mail_admins()\fP\&. +.SS \fBshell\fP +.INDENT 0.0 +.TP +.B django\-admin shell +.UNINDENT +.sp +Starts the Python interactive interpreter. +.INDENT 0.0 +.TP +.B \-\-interface {ipython,bpython,python}, \-i {ipython,bpython,python} +.UNINDENT +.sp +Specifies the shell to use. By default, Django will use \fI\%IPython\fP or \fI\%bpython\fP if +either is installed. If both are installed, specify which one you want like so: +.sp +IPython: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin shell \-i ipython +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +bpython: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin shell \-i bpython +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +If you have a "rich" shell installed but want to force use of the "plain" +Python interpreter, use \fBpython\fP as the interface name, like so: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin shell \-i python +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-nostartup +.UNINDENT +.sp +Disables reading the startup script for the "plain" Python interpreter. By +default, the script pointed to by the \fI\%PYTHONSTARTUP\fP environment +variable or the \fB~/.pythonrc.py\fP script is read. +.INDENT 0.0 +.TP +.B \-\-command COMMAND, \-c COMMAND +.UNINDENT +.sp +Lets you pass a command as a string to execute it as Django, like so: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin shell \-\-command="import django; print(django.__version__)" +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +You can also pass code in on standard input to execute it. For example: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +$ django\-admin shell < import django +> print(django.__version__) +> EOF +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +On Windows, the REPL is output due to implementation limits of +\fI\%select.select()\fP on that platform. +.SS \fBshowmigrations\fP +.INDENT 0.0 +.TP +.B django\-admin showmigrations [app_label [app_label ...]] +.UNINDENT +.sp +Shows all migrations in a project. You can choose from one of two formats: +.INDENT 0.0 +.TP +.B \-\-list, \-l +.UNINDENT +.sp +Lists all of the apps Django knows about, the migrations available for each +app, and whether or not each migration is applied (marked by an \fB[X]\fP next to +the migration name). For a \fB\-\-verbosity\fP of 2 and above, the applied +datetimes are also shown. +.sp +Apps without migrations are also listed, but have \fB(no migrations)\fP printed +under them. +.sp +This is the default output format. +.INDENT 0.0 +.TP +.B \-\-plan, \-p +.UNINDENT +.sp +Shows the migration plan Django will follow to apply migrations. Like +\fB\-\-list\fP, applied migrations are marked by an \fB[X]\fP\&. For a \fB\-\-verbosity\fP +of 2 and above, all dependencies of a migration will also be shown. +.sp +\fBapp_label\fPs arguments limit the output, however, dependencies of provided +apps may also be included. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database to examine. Defaults to \fBdefault\fP\&. +.SS \fBsqlflush\fP +.INDENT 0.0 +.TP +.B django\-admin sqlflush +.UNINDENT +.sp +Prints the SQL statements that would be executed for the \fI\%flush\fP +command. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database for which to print the SQL. Defaults to \fBdefault\fP\&. +.SS \fBsqlmigrate\fP +.INDENT 0.0 +.TP +.B django\-admin sqlmigrate app_label migration_name +.UNINDENT +.sp +Prints the SQL for the named migration. This requires an active database +connection, which it will use to resolve constraint names; this means you must +generate the SQL against a copy of the database you wish to later apply it on. +.sp +Note that \fBsqlmigrate\fP doesn\(aqt colorize its output. +.INDENT 0.0 +.TP +.B \-\-backwards +.UNINDENT +.sp +Generates the SQL for unapplying the migration. By default, the SQL created is +for running the migration in the forwards direction. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database for which to generate the SQL. Defaults to \fBdefault\fP\&. +.SS \fBsqlsequencereset\fP +.INDENT 0.0 +.TP +.B django\-admin sqlsequencereset app_label [app_label ...] +.UNINDENT +.sp +Prints the SQL statements for resetting sequences for the given app name(s). +.sp +Sequences are indexes used by some database engines to track the next available +number for automatically incremented fields. +.sp +Use this command to generate SQL which will fix cases where a sequence is out +of sync with its automatically incremented field data. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database for which to print the SQL. Defaults to \fBdefault\fP\&. +.SS \fBsquashmigrations\fP +.INDENT 0.0 +.TP +.B django\-admin squashmigrations app_label [start_migration_name] migration_name +.UNINDENT +.sp +Squashes the migrations for \fBapp_label\fP up to and including \fBmigration_name\fP +down into fewer migrations, if possible. The resulting squashed migrations +can live alongside the unsquashed ones safely. For more information, +please read \fI\%Squashing migrations\fP\&. +.sp +When \fBstart_migration_name\fP is given, Django will only include migrations +starting from and including this migration. This helps to mitigate the +squashing limitation of \fI\%RunPython\fP and +\fI\%django.db.migrations.operations.RunSQL\fP migration operations. +.INDENT 0.0 +.TP +.B \-\-no\-optimize +.UNINDENT +.sp +Disables the optimizer when generating a squashed migration. By default, Django +will try to optimize the operations in your migrations to reduce the size of +the resulting file. Use this option if this process is failing or creating +incorrect migrations, though please also file a Django bug report about the +behavior, as optimization is meant to be safe. +.INDENT 0.0 +.TP +.B \-\-noinput, \-\-no\-input +.UNINDENT +.sp +Suppresses all user prompts. +.INDENT 0.0 +.TP +.B \-\-squashed\-name SQUASHED_NAME +.UNINDENT +.sp +Sets the name of the squashed migration. When omitted, the name is based on the +first and last migration, with \fB_squashed_\fP in between. +.INDENT 0.0 +.TP +.B \-\-no\-header +.UNINDENT +.sp +Generate squashed migration file without Django version and timestamp header. +.SS \fBstartapp\fP +.INDENT 0.0 +.TP +.B django\-admin startapp name [directory] +.UNINDENT +.sp +Creates a Django app directory structure for the given app name in the current +directory or the given destination. +.sp +By default, \fI\%the new directory\fP contains a +\fBmodels.py\fP file and other app template files. If only the app name is given, +the app directory will be created in the current working directory. +.sp +If the optional destination is provided, Django will use that existing +directory rather than creating a new one. You can use \(aq.\(aq to denote the current +working directory. +.sp +For example: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin startapp myapp /Users/jezdez/Code/myapp +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-template TEMPLATE +.UNINDENT +.sp +Provides the path to a directory with a custom app template file, or a path to +an uncompressed archive (\fB\&.tar\fP) or a compressed archive (\fB\&.tar.gz\fP, +\fB\&.tar.bz2\fP, \fB\&.tar.xz\fP, \fB\&.tar.lzma\fP, \fB\&.tgz\fP, \fB\&.tbz2\fP, \fB\&.txz\fP, +\fB\&.tlz\fP, \fB\&.zip\fP) containing the app template files. +.sp +For example, this would look for an app template in the given directory when +creating the \fBmyapp\fP app: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin startapp \-\-template=/Users/jezdez/Code/my_app_template myapp +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Django will also accept URLs (\fBhttp\fP, \fBhttps\fP, \fBftp\fP) to compressed +archives with the app template files, downloading and extracting them on the +fly. +.sp +For example, taking advantage of GitHub\(aqs feature to expose repositories as +zip files, you can use a URL like: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin startapp \-\-template=https://github.com/githubuser/django\-app\-template/archive/main.zip myapp +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-extension EXTENSIONS, \-e EXTENSIONS +.UNINDENT +.sp +Specifies which file extensions in the app template should be rendered with the +template engine. Defaults to \fBpy\fP\&. +.INDENT 0.0 +.TP +.B \-\-name FILES, \-n FILES +.UNINDENT +.sp +Specifies which files in the app template (in addition to those matching +\fB\-\-extension\fP) should be rendered with the template engine. Defaults to an +empty list. +.INDENT 0.0 +.TP +.B \-\-exclude DIRECTORIES, \-x DIRECTORIES +.UNINDENT +.sp +Specifies which directories in the app template should be excluded, in addition +to \fB\&.git\fP and \fB__pycache__\fP\&. If this option is not provided, directories +named \fB__pycache__\fP or starting with \fB\&.\fP will be excluded. +.sp +The \fI\%template context\fP used for all matching +files is: +.INDENT 0.0 +.IP \(bu 2 +Any option passed to the \fBstartapp\fP command (among the command\(aqs supported +options) +.IP \(bu 2 +\fBapp_name\fP \-\- the app name as passed to the command +.IP \(bu 2 +\fBapp_directory\fP \-\- the full path of the newly created app +.IP \(bu 2 +\fBcamel_case_app_name\fP \-\- the app name in camel case format +.IP \(bu 2 +\fBdocs_version\fP \-\- the version of the documentation: \fB\(aqdev\(aq\fP or \fB\(aq1.x\(aq\fP +.IP \(bu 2 +\fBdjango_version\fP \-\- the version of Django, e.g. \fB\(aq2.0.3\(aq\fP +.UNINDENT +.sp +\fBWARNING:\fP +.INDENT 0.0 +.INDENT 3.5 +When the app template files are rendered with the Django template +engine (by default all \fB*.py\fP files), Django will also replace all +stray template variables contained. For example, if one of the Python files +contains a docstring explaining a particular feature related +to template rendering, it might result in an incorrect example. +.sp +To work around this problem, you can use the \fI\%templatetag\fP +template tag to "escape" the various parts of the template syntax. +.sp +In addition, to allow Python template files that contain Django template +language syntax while also preventing packaging systems from trying to +byte\-compile invalid \fB*.py\fP files, template files ending with \fB\&.py\-tpl\fP +will be renamed to \fB\&.py\fP\&. +.UNINDENT +.UNINDENT +.sp +\fBWARNING:\fP +.INDENT 0.0 +.INDENT 3.5 +The contents of custom app (or project) templates should always be +audited before use: Such templates define code that will become +part of your project, and this means that such code will be trusted +as much as any app you install, or code you write yourself. +Further, even rendering the templates is, effectively, executing +code that was provided as input to the management command. The +Django template language may provide wide access into the system, +so make sure any custom template you use is worthy of your trust. +.UNINDENT +.UNINDENT +.SS \fBstartproject\fP +.INDENT 0.0 +.TP +.B django\-admin startproject name [directory] +.UNINDENT +.sp +Creates a Django project directory structure for the given project name in +the current directory or the given destination. +.sp +By default, \fI\%the new directory\fP contains +\fBmanage.py\fP and a project package (containing a \fBsettings.py\fP and other +files). +.sp +If only the project name is given, both the project directory and project +package will be named \fB\fP and the project directory +will be created in the current working directory. +.sp +If the optional destination is provided, Django will use that existing +directory as the project directory, and create \fBmanage.py\fP and the project +package within it. Use \(aq.\(aq to denote the current working directory. +.sp +For example: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin startproject myproject /Users/jezdez/Code/myproject_repo +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-template TEMPLATE +.UNINDENT +.sp +Specifies a directory, file path, or URL of a custom project template. See the +\fI\%startapp \-\-template\fP documentation for examples and usage. +.INDENT 0.0 +.TP +.B \-\-extension EXTENSIONS, \-e EXTENSIONS +.UNINDENT +.sp +Specifies which file extensions in the project template should be rendered with +the template engine. Defaults to \fBpy\fP\&. +.INDENT 0.0 +.TP +.B \-\-name FILES, \-n FILES +.UNINDENT +.sp +Specifies which files in the project template (in addition to those matching +\fB\-\-extension\fP) should be rendered with the template engine. Defaults to an +empty list. +.INDENT 0.0 +.TP +.B \-\-exclude DIRECTORIES, \-x DIRECTORIES +.UNINDENT +.sp +Specifies which directories in the project template should be excluded, in +addition to \fB\&.git\fP and \fB__pycache__\fP\&. If this option is not provided, +directories named \fB__pycache__\fP or starting with \fB\&.\fP will be excluded. +.sp +The \fI\%template context\fP used is: +.INDENT 0.0 +.IP \(bu 2 +Any option passed to the \fBstartproject\fP command (among the command\(aqs +supported options) +.IP \(bu 2 +\fBproject_name\fP \-\- the project name as passed to the command +.IP \(bu 2 +\fBproject_directory\fP \-\- the full path of the newly created project +.IP \(bu 2 +\fBsecret_key\fP \-\- a random key for the \fI\%SECRET_KEY\fP setting +.IP \(bu 2 +\fBdocs_version\fP \-\- the version of the documentation: \fB\(aqdev\(aq\fP or \fB\(aq1.x\(aq\fP +.IP \(bu 2 +\fBdjango_version\fP \-\- the version of Django, e.g. \fB\(aq2.0.3\(aq\fP +.UNINDENT +.sp +Please also see the \fI\%rendering warning\fP and +\fI\%trusted code warning\fP as mentioned for +\fI\%startapp\fP\&. +.SS \fBtest\fP +.INDENT 0.0 +.TP +.B django\-admin test [test_label [test_label ...]] +.UNINDENT +.sp +Runs tests for all installed apps. See \fI\%Testing in Django\fP for more +information. +.INDENT 0.0 +.TP +.B \-\-failfast +.UNINDENT +.sp +Stops running tests and reports the failure immediately after a test fails. +.INDENT 0.0 +.TP +.B \-\-testrunner TESTRUNNER +.UNINDENT +.sp +Controls the test runner class that is used to execute tests. This value +overrides the value provided by the \fI\%TEST_RUNNER\fP setting. +.INDENT 0.0 +.TP +.B \-\-noinput, \-\-no\-input +.UNINDENT +.sp +Suppresses all user prompts. A typical prompt is a warning about deleting an +existing test database. +.SS Test runner options +.sp +The \fBtest\fP command receives options on behalf of the specified +\fI\%\-\-testrunner\fP\&. These are the options of the default test runner: +\fI\%DiscoverRunner\fP\&. +.INDENT 0.0 +.TP +.B \-\-keepdb +.UNINDENT +.sp +Preserves the test database between test runs. This has the advantage of +skipping both the create and destroy actions which can greatly decrease the +time to run tests, especially those in a large test suite. If the test database +does not exist, it will be created on the first run and then preserved for each +subsequent run. Unless the \fI\%MIGRATE\fP test setting is +\fBFalse\fP, any unapplied migrations will also be applied to the test database +before running the test suite. +.INDENT 0.0 +.TP +.B \-\-shuffle [SEED] +.UNINDENT +.sp +Randomizes the order of tests before running them. This can help detect tests +that aren\(aqt properly isolated. The test order generated by this option is a +deterministic function of the integer seed given. When no seed is passed, a +seed is chosen randomly and printed to the console. To repeat a particular test +order, pass a seed. The test orders generated by this option preserve Django\(aqs +\fI\%guarantees on test order\fP\&. They also keep tests grouped +by test case class. +.sp +The shuffled orderings also have a special consistency property useful when +narrowing down isolation issues. Namely, for a given seed and when running a +subset of tests, the new order will be the original shuffling restricted to the +smaller set. Similarly, when adding tests while keeping the seed the same, the +order of the original tests will be the same in the new order. +.INDENT 0.0 +.TP +.B \-\-reverse, \-r +.UNINDENT +.sp +Sorts test cases in the opposite execution order. This may help in debugging +the side effects of tests that aren\(aqt properly isolated. \fI\%Grouping by test +class\fP is preserved when using this option. This can be used +in conjunction with \fB\-\-shuffle\fP to reverse the order for a particular seed. +.INDENT 0.0 +.TP +.B \-\-debug\-mode +.UNINDENT +.sp +Sets the \fI\%DEBUG\fP setting to \fBTrue\fP prior to running tests. This may +help troubleshoot test failures. +.INDENT 0.0 +.TP +.B \-\-debug\-sql, \-d +.UNINDENT +.sp +Enables \fI\%SQL logging\fP for failing tests. If +\fB\-\-verbosity\fP is \fB2\fP, then queries in passing tests are also output. +.INDENT 0.0 +.TP +.B \-\-parallel [N] +.UNINDENT +.INDENT 0.0 +.TP +.B DJANGO_TEST_PROCESSES +.UNINDENT +.sp +Runs tests in separate parallel processes. Since modern processors have +multiple cores, this allows running tests significantly faster. +.sp +Using \fB\-\-parallel\fP without a value, or with the value \fBauto\fP, runs one test +process per core according to \fI\%multiprocessing.cpu_count()\fP\&. You can +override this by passing the desired number of processes, e.g. +\fB\-\-parallel 4\fP, or by setting the \fI\%DJANGO_TEST_PROCESSES\fP environment +variable. +.sp +Django distributes test cases — \fI\%unittest.TestCase\fP subclasses — to +subprocesses. If there are fewer test cases than configured processes, Django +will reduce the number of processes accordingly. +.sp +Each process gets its own database. You must ensure that different test cases +don\(aqt access the same resources. For instance, test cases that touch the +filesystem should create a temporary directory for their own use. +.sp +\fBNOTE:\fP +.INDENT 0.0 +.INDENT 3.5 +If you have test classes that cannot be run in parallel, you can use +\fBSerializeMixin\fP to run them sequentially. See \fI\%Enforce running test +classes sequentially\fP\&. +.UNINDENT +.UNINDENT +.sp +This option requires the third\-party \fBtblib\fP package to display tracebacks +correctly: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +$ python \-m pip install tblib +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +This feature isn\(aqt available on Windows. It doesn\(aqt work with the Oracle +database backend either. +.sp +If you want to use \fI\%pdb\fP while debugging tests, you must disable parallel +execution (\fB\-\-parallel=1\fP). You\(aqll see something like \fBbdb.BdbQuit\fP if you +don\(aqt. +.sp +\fBWARNING:\fP +.INDENT 0.0 +.INDENT 3.5 +When test parallelization is enabled and a test fails, Django may be +unable to display the exception traceback. This can make debugging +difficult. If you encounter this problem, run the affected test without +parallelization to see the traceback of the failure. +.sp +This is a known limitation. It arises from the need to serialize objects +in order to exchange them between processes. See +\fI\%What can be pickled and unpickled?\fP for details. +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-tag TAGS +.UNINDENT +.sp +Runs only tests \fI\%marked with the specified tags\fP\&. +May be specified multiple times and combined with \fI\%test \-\-exclude\-tag\fP\&. +.sp +Tests that fail to load are always considered matching. +.INDENT 0.0 +.TP +.B \-\-exclude\-tag EXCLUDE_TAGS +.UNINDENT +.sp +Excludes tests \fI\%marked with the specified tags\fP\&. +May be specified multiple times and combined with \fI\%test \-\-tag\fP\&. +.INDENT 0.0 +.TP +.B \-k TEST_NAME_PATTERNS +.UNINDENT +.sp +Runs test methods and classes matching test name patterns, in the same way as +\fI\%unittest\(aqs \-k option\fP\&. Can be specified multiple times. +.INDENT 0.0 +.TP +.B \-\-pdb +.UNINDENT +.sp +Spawns a \fBpdb\fP debugger at each test error or failure. If you have it +installed, \fBipdb\fP is used instead. +.INDENT 0.0 +.TP +.B \-\-buffer, \-b +.UNINDENT +.sp +Discards output (\fBstdout\fP and \fBstderr\fP) for passing tests, in the same way +as \fI\%unittest\(aqs \-\-buffer option\fP\&. +.INDENT 0.0 +.TP +.B \-\-no\-faulthandler +.UNINDENT +.sp +Django automatically calls \fI\%faulthandler.enable()\fP when starting the +tests, which allows it to print a traceback if the interpreter crashes. Pass +\fB\-\-no\-faulthandler\fP to disable this behavior. +.INDENT 0.0 +.TP +.B \-\-timing +.UNINDENT +.sp +Outputs timings, including database setup and total run time. +.SS \fBtestserver\fP +.INDENT 0.0 +.TP +.B django\-admin testserver [fixture [fixture ...]] +.UNINDENT +.sp +Runs a Django development server (as in \fI\%runserver\fP) using data from +the given fixture(s). +.sp +For example, this command: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin testserver mydata.json +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +\&...would perform the following steps: +.INDENT 0.0 +.IP 1. 3 +Create a test database, as described in \fI\%The test database\fP\&. +.IP 2. 3 +Populate the test database with fixture data from the given fixtures. +(For more on fixtures, see the documentation for \fI\%loaddata\fP above.) +.IP 3. 3 +Runs the Django development server (as in \fI\%runserver\fP), pointed at +this newly created test database instead of your production database. +.UNINDENT +.sp +This is useful in a number of ways: +.INDENT 0.0 +.IP \(bu 2 +When you\(aqre writing \fI\%unit tests\fP of how your views +act with certain fixture data, you can use \fBtestserver\fP to interact with +the views in a web browser, manually. +.IP \(bu 2 +Let\(aqs say you\(aqre developing your Django application and have a "pristine" +copy of a database that you\(aqd like to interact with. You can dump your +database to a \fI\%fixture\fP (using the +\fI\%dumpdata\fP command, explained above), then use \fBtestserver\fP to run +your web application with that data. With this arrangement, you have the +flexibility of messing up your data in any way, knowing that whatever data +changes you\(aqre making are only being made to a test database. +.UNINDENT +.sp +Note that this server does \fInot\fP automatically detect changes to your Python +source code (as \fI\%runserver\fP does). It does, however, detect changes to +templates. +.INDENT 0.0 +.TP +.B \-\-addrport ADDRPORT +.UNINDENT +.sp +Specifies a different port, or IP address and port, from the default of +\fB127.0.0.1:8000\fP\&. This value follows exactly the same format and serves +exactly the same function as the argument to the \fI\%runserver\fP command. +.sp +Examples: +.sp +To run the test server on port 7000 with \fBfixture1\fP and \fBfixture2\fP: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin testserver \-\-addrport 7000 fixture1 fixture2 +django\-admin testserver fixture1 fixture2 \-\-addrport 7000 +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +(The above statements are equivalent. We include both of them to demonstrate +that it doesn\(aqt matter whether the options come before or after the fixture +arguments.) +.sp +To run on 1.2.3.4:7000 with a \fBtest\fP fixture: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin testserver \-\-addrport 1.2.3.4:7000 test +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-noinput, \-\-no\-input +.UNINDENT +.sp +Suppresses all user prompts. A typical prompt is a warning about deleting an +existing test database. +.SH COMMANDS PROVIDED BY APPLICATIONS +.sp +Some commands are only available when the \fBdjango.contrib\fP application that +\fI\%implements\fP them has been +\fI\%enabled\fP\&. This section describes them grouped by +their application. +.SS \fBdjango.contrib.auth\fP +.SS \fBchangepassword\fP +.INDENT 0.0 +.TP +.B django\-admin changepassword [] +.UNINDENT +.sp +This command is only available if Django\(aqs \fI\%authentication system\fP (\fBdjango.contrib.auth\fP) is installed. +.sp +Allows changing a user\(aqs password. It prompts you to enter a new password twice +for the given user. If the entries are identical, this immediately becomes the +new password. If you do not supply a user, the command will attempt to change +the password whose username matches the current user. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database to query for the user. Defaults to \fBdefault\fP\&. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin changepassword ringo +.ft P +.fi +.UNINDENT +.UNINDENT +.SS \fBcreatesuperuser\fP +.INDENT 0.0 +.TP +.B django\-admin createsuperuser +.UNINDENT +.INDENT 0.0 +.TP +.B DJANGO_SUPERUSER_PASSWORD +.UNINDENT +.sp +This command is only available if Django\(aqs \fI\%authentication system\fP (\fBdjango.contrib.auth\fP) is installed. +.sp +Creates a superuser account (a user who has all permissions). This is +useful if you need to create an initial superuser account or if you need to +programmatically generate superuser accounts for your site(s). +.sp +When run interactively, this command will prompt for a password for +the new superuser account. When run non\-interactively, you can provide +a password by setting the \fI\%DJANGO_SUPERUSER_PASSWORD\fP environment +variable. Otherwise, no password will be set, and the superuser account will +not be able to log in until a password has been manually set for it. +.sp +In non\-interactive mode, the +\fI\%USERNAME_FIELD\fP and required +fields (listed in +\fI\%REQUIRED_FIELDS\fP) fall back to +\fBDJANGO_SUPERUSER_\fP environment variables, unless they +are overridden by a command line argument. For example, to provide an \fBemail\fP +field, you can use \fBDJANGO_SUPERUSER_EMAIL\fP environment variable. +.INDENT 0.0 +.TP +.B \-\-noinput, \-\-no\-input +.UNINDENT +.sp +Suppresses all user prompts. If a suppressed prompt cannot be resolved +automatically, the command will exit with error code 1. +.INDENT 0.0 +.TP +.B \-\-username USERNAME +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-email EMAIL +.UNINDENT +.sp +The username and email address for the new account can be supplied by +using the \fB\-\-username\fP and \fB\-\-email\fP arguments on the command +line. If either of those is not supplied, \fBcreatesuperuser\fP will prompt for +it when running interactively. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database into which the superuser object will be saved. +.sp +You can subclass the management command and override \fBget_input_data()\fP if you +want to customize data input and validation. Consult the source code for +details on the existing implementation and the method\(aqs parameters. For example, +it could be useful if you have a \fBForeignKey\fP in +\fI\%REQUIRED_FIELDS\fP and want to +allow creating an instance instead of entering the primary key of an existing +instance. +.SS \fBdjango.contrib.contenttypes\fP +.SS \fBremove_stale_contenttypes\fP +.INDENT 0.0 +.TP +.B django\-admin remove_stale_contenttypes +.UNINDENT +.sp +This command is only available if Django\(aqs \fI\%contenttypes app\fP (\fI\%django.contrib.contenttypes\fP) is installed. +.sp +Deletes stale content types (from deleted models) in your database. Any objects +that depend on the deleted content types will also be deleted. A list of +deleted objects will be displayed before you confirm it\(aqs okay to proceed with +the deletion. +.INDENT 0.0 +.TP +.B \-\-database DATABASE +.UNINDENT +.sp +Specifies the database to use. Defaults to \fBdefault\fP\&. +.INDENT 0.0 +.TP +.B \-\-include\-stale\-apps +.UNINDENT +.sp +Deletes stale content types including ones from previously installed apps that +have been removed from \fI\%INSTALLED_APPS\fP\&. Defaults to \fBFalse\fP\&. +.SS \fBdjango.contrib.gis\fP +.SS \fBogrinspect\fP +.sp +This command is only available if \fI\%GeoDjango\fP +(\fBdjango.contrib.gis\fP) is installed. +.sp +Please refer to its \fI\%description\fP in the GeoDjango +documentation. +.SS \fBdjango.contrib.sessions\fP +.SS \fBclearsessions\fP +.INDENT 0.0 +.TP +.B django\-admin clearsessions +.UNINDENT +.sp +Can be run as a cron job or directly to clean out expired sessions. +.SS \fBdjango.contrib.sitemaps\fP +.SS \fBping_google\fP +.sp +This command is only available if the \fI\%Sitemaps framework\fP (\fBdjango.contrib.sitemaps\fP) is installed. +.sp +Please refer to its \fI\%description\fP in the Sitemaps +documentation. +.SS \fBdjango.contrib.staticfiles\fP +.SS \fBcollectstatic\fP +.sp +This command is only available if the \fI\%static files application\fP (\fBdjango.contrib.staticfiles\fP) is installed. +.sp +Please refer to its \fI\%description\fP in the +\fI\%staticfiles\fP documentation. +.SS \fBfindstatic\fP +.sp +This command is only available if the \fI\%static files application\fP (\fBdjango.contrib.staticfiles\fP) is installed. +.sp +Please refer to its \fI\%description\fP in the \fI\%staticfiles\fP documentation. +.SH DEFAULT OPTIONS +.sp +Although some commands may allow their own custom options, every command +allows for the following options by default: +.INDENT 0.0 +.TP +.B \-\-pythonpath PYTHONPATH +.UNINDENT +.sp +Adds the given filesystem path to the Python \fI\%import search path\fP\&. If this +isn\(aqt provided, \fBdjango\-admin\fP will use the \fI\%PYTHONPATH\fP environment +variable. +.sp +This option is unnecessary in \fBmanage.py\fP, because it takes care of setting +the Python path for you. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin migrate \-\-pythonpath=\(aq/home/djangoprojects/myproject\(aq +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-settings SETTINGS +.UNINDENT +.sp +Specifies the settings module to use. The settings module should be in Python +package syntax, e.g. \fBmysite.settings\fP\&. If this isn\(aqt provided, +\fBdjango\-admin\fP will use the \fI\%DJANGO_SETTINGS_MODULE\fP environment +variable. +.sp +This option is unnecessary in \fBmanage.py\fP, because it uses +\fBsettings.py\fP from the current project by default. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin migrate \-\-settings=mysite.settings +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-traceback +.UNINDENT +.sp +Displays a full stack trace when a \fI\%CommandError\fP +is raised. By default, \fBdjango\-admin\fP will show an error message when a +\fBCommandError\fP occurs and a full stack trace for any other exception. +.sp +This option is ignored by \fI\%runserver\fP\&. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin migrate \-\-traceback +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-verbosity {0,1,2,3}, \-v {0,1,2,3} +.UNINDENT +.sp +Specifies the amount of notification and debug information that a command +should print to the console. +.INDENT 0.0 +.IP \(bu 2 +\fB0\fP means no output. +.IP \(bu 2 +\fB1\fP means normal output (default). +.IP \(bu 2 +\fB2\fP means verbose output. +.IP \(bu 2 +\fB3\fP means \fIvery\fP verbose output. +.UNINDENT +.sp +This option is ignored by \fI\%runserver\fP\&. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin migrate \-\-verbosity 2 +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-no\-color +.UNINDENT +.sp +Disables colorized command output. Some commands format their output to be +colorized. For example, errors will be printed to the console in red and SQL +statements will be syntax highlighted. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin runserver \-\-no\-color +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B \-\-force\-color +.UNINDENT +.sp +Forces colorization of the command output if it would otherwise be disabled +as discussed in \fI\%Syntax coloring\fP\&. For example, you may want to pipe +colored output to another command. +.INDENT 0.0 +.TP +.B \-\-skip\-checks +.UNINDENT +.sp +Skips running system checks prior to running the command. This option is only +available if the +\fI\%requires_system_checks\fP command +attribute is not an empty list or tuple. +.sp +Example usage: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin migrate \-\-skip\-checks +.ft P +.fi +.UNINDENT +.UNINDENT +.SH EXTRA NICETIES +.SS Syntax coloring +.INDENT 0.0 +.TP +.B DJANGO_COLORS +.UNINDENT +.sp +The \fBdjango\-admin\fP / \fBmanage.py\fP commands will use pretty +color\-coded output if your terminal supports ANSI\-colored output. It +won\(aqt use the color codes if you\(aqre piping the command\(aqs output to +another program unless the \fI\%\-\-force\-color\fP option is used. +.SS Windows support +.sp +On Windows 10, the \fI\%Windows Terminal\fP application, \fI\%VS Code\fP, and PowerShell +(where virtual terminal processing is enabled) allow colored output, and are +supported by default. +.sp +Under Windows, the legacy \fBcmd.exe\fP native console doesn\(aqt support ANSI +escape sequences so by default there is no color output. In this case either of +two third\-party libraries are needed: +.INDENT 0.0 +.IP \(bu 2 +Install \fI\%colorama\fP, a Python package that translates ANSI color codes into +Windows API calls. Django commands will detect its presence and will make use +of its services to color output just like on Unix\-based platforms. +\fBcolorama\fP can be installed via pip: +.INDENT 2.0 +.INDENT 3.5 +.sp +.nf +.ft C +\&...\e> py \-m pip install colorama +.ft P +.fi +.UNINDENT +.UNINDENT +.IP \(bu 2 +Install \fI\%ANSICON\fP, a third\-party tool that allows \fBcmd.exe\fP to process +ANSI color codes. Django commands will detect its presence and will make use +of its services to color output just like on Unix\-based platforms. +.UNINDENT +.sp +Other modern terminal environments on Windows, that support terminal colors, +but which are not automatically detected as supported by Django, may "fake" the +installation of \fBANSICON\fP by setting the appropriate environmental variable, +\fBANSICON="on"\fP\&. +.SS Custom colors +.sp +The colors used for syntax highlighting can be customized. Django +ships with three color palettes: +.INDENT 0.0 +.IP \(bu 2 +\fBdark\fP, suited to terminals that show white text on a black +background. This is the default palette. +.IP \(bu 2 +\fBlight\fP, suited to terminals that show black text on a white +background. +.IP \(bu 2 +\fBnocolor\fP, which disables syntax highlighting. +.UNINDENT +.sp +You select a palette by setting a \fI\%DJANGO_COLORS\fP environment +variable to specify the palette you want to use. For example, to +specify the \fBlight\fP palette under a Unix or OS/X BASH shell, you +would run the following at a command prompt: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +export DJANGO_COLORS="light" +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +You can also customize the colors that are used. Django specifies a +number of roles in which color is used: +.INDENT 0.0 +.IP \(bu 2 +\fBerror\fP \- A major error. +.IP \(bu 2 +\fBnotice\fP \- A minor error. +.IP \(bu 2 +\fBsuccess\fP \- A success. +.IP \(bu 2 +\fBwarning\fP \- A warning. +.IP \(bu 2 +\fBsql_field\fP \- The name of a model field in SQL. +.IP \(bu 2 +\fBsql_coltype\fP \- The type of a model field in SQL. +.IP \(bu 2 +\fBsql_keyword\fP \- An SQL keyword. +.IP \(bu 2 +\fBsql_table\fP \- The name of a model in SQL. +.IP \(bu 2 +\fBhttp_info\fP \- A 1XX HTTP Informational server response. +.IP \(bu 2 +\fBhttp_success\fP \- A 2XX HTTP Success server response. +.IP \(bu 2 +\fBhttp_not_modified\fP \- A 304 HTTP Not Modified server response. +.IP \(bu 2 +\fBhttp_redirect\fP \- A 3XX HTTP Redirect server response other than 304. +.IP \(bu 2 +\fBhttp_not_found\fP \- A 404 HTTP Not Found server response. +.IP \(bu 2 +\fBhttp_bad_request\fP \- A 4XX HTTP Bad Request server response other than 404. +.IP \(bu 2 +\fBhttp_server_error\fP \- A 5XX HTTP Server Error response. +.IP \(bu 2 +\fBmigrate_heading\fP \- A heading in a migrations management command. +.IP \(bu 2 +\fBmigrate_label\fP \- A migration name. +.UNINDENT +.sp +Each of these roles can be assigned a specific foreground and +background color, from the following list: +.INDENT 0.0 +.IP \(bu 2 +\fBblack\fP +.IP \(bu 2 +\fBred\fP +.IP \(bu 2 +\fBgreen\fP +.IP \(bu 2 +\fByellow\fP +.IP \(bu 2 +\fBblue\fP +.IP \(bu 2 +\fBmagenta\fP +.IP \(bu 2 +\fBcyan\fP +.IP \(bu 2 +\fBwhite\fP +.UNINDENT +.sp +Each of these colors can then be modified by using the following +display options: +.INDENT 0.0 +.IP \(bu 2 +\fBbold\fP +.IP \(bu 2 +\fBunderscore\fP +.IP \(bu 2 +\fBblink\fP +.IP \(bu 2 +\fBreverse\fP +.IP \(bu 2 +\fBconceal\fP +.UNINDENT +.sp +A color specification follows one of the following patterns: +.INDENT 0.0 +.IP \(bu 2 +\fBrole=fg\fP +.IP \(bu 2 +\fBrole=fg/bg\fP +.IP \(bu 2 +\fBrole=fg,option,option\fP +.IP \(bu 2 +\fBrole=fg/bg,option,option\fP +.UNINDENT +.sp +where \fBrole\fP is the name of a valid color role, \fBfg\fP is the +foreground color, \fBbg\fP is the background color and each \fBoption\fP +is one of the color modifying options. Multiple color specifications +are then separated by a semicolon. For example: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +would specify that errors be displayed using blinking yellow on blue, +and notices displayed using magenta. All other color roles would be +left uncolored. +.sp +Colors can also be specified by extending a base palette. If you put +a palette name in a color specification, all the colors implied by that +palette will be loaded. So: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +export DJANGO_COLORS="light;error=yellow/blue,blink;notice=magenta" +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +would specify the use of all the colors in the light color palette, +\fIexcept\fP for the colors for errors and notices which would be +overridden as specified. +.SS Bash completion +.sp +If you use the Bash shell, consider installing the Django bash completion +script, which lives in \fI\%extras/django_bash_completion\fP in the Django source +distribution. It enables tab\-completion of \fBdjango\-admin\fP and +\fBmanage.py\fP commands, so you can, for instance... +.INDENT 0.0 +.IP \(bu 2 +Type \fBdjango\-admin\fP\&. +.IP \(bu 2 +Press [TAB] to see all available options. +.IP \(bu 2 +Type \fBsql\fP, then [TAB], to see all available options whose names start +with \fBsql\fP\&. +.UNINDENT +.sp +See \fI\%How to create custom django\-admin commands\fP for how to add customized actions. +.SS Black formatting +.sp + +.sp +The Python files created by \fI\%startproject\fP, \fI\%startapp\fP, +\fI\%optimizemigration\fP, \fI\%makemigrations\fP, and +\fI\%squashmigrations\fP are formatted using the \fBblack\fP command if it is +present on your \fBPATH\fP\&. +.sp +If you have \fBblack\fP globally installed, but do not wish it used for the +current project, you can set the \fBPATH\fP explicitly: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +PATH=path/to/venv/bin django\-admin makemigrations +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +For commands using \fBstdout\fP you can pipe the output to \fBblack\fP if needed: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +django\-admin inspectdb | black \- +.ft P +.fi +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B django.core.management.call_command(name, *args, **options) +.UNINDENT +.sp +To call a management command from code use \fBcall_command\fP\&. +.INDENT 0.0 +.TP +.B \fBname\fP +the name of the command to call or a command object. Passing the name is +preferred unless the object is required for testing. +.TP +.B \fB*args\fP +a list of arguments accepted by the command. Arguments are passed to the +argument parser, so you can use the same style as you would on the command +line. For example, \fBcall_command(\(aqflush\(aq, \(aq\-\-verbosity=0\(aq)\fP\&. +.TP +.B \fB**options\fP +named options accepted on the command\-line. Options are passed to the command +without triggering the argument parser, which means you\(aqll need to pass the +correct type. For example, \fBcall_command(\(aqflush\(aq, verbosity=0)\fP (zero must +be an integer rather than a string). +.UNINDENT +.sp +Examples: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +from django.core import management +from django.core.management.commands import loaddata + +management.call_command(\(aqflush\(aq, verbosity=0, interactive=False) +management.call_command(\(aqloaddata\(aq, \(aqtest_data\(aq, verbosity=0) +management.call_command(loaddata.Command(), \(aqtest_data\(aq, verbosity=0) +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Note that command options that take no arguments are passed as keywords +with \fBTrue\fP or \fBFalse\fP, as you can see with the \fBinteractive\fP option above. +.sp +Named arguments can be passed by using either one of the following syntaxes: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +# Similar to the command line +management.call_command(\(aqdumpdata\(aq, \(aq\-\-natural\-foreign\(aq) + +# Named argument similar to the command line minus the initial dashes and +# with internal dashes replaced by underscores +management.call_command(\(aqdumpdata\(aq, natural_foreign=True) + +# \(gause_natural_foreign_keys\(ga is the option destination variable +management.call_command(\(aqdumpdata\(aq, use_natural_foreign_keys=True) +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +Some command options have different names when using \fBcall_command()\fP instead +of \fBdjango\-admin\fP or \fBmanage.py\fP\&. For example, \fBdjango\-admin +createsuperuser \-\-no\-input\fP translates to \fBcall_command(\(aqcreatesuperuser\(aq, +interactive=False)\fP\&. To find what keyword argument name to use for +\fBcall_command()\fP, check the command\(aqs source code for the \fBdest\fP argument +passed to \fBparser.add_argument()\fP\&. +.sp +Command options which take multiple options are passed a list: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +management.call_command(\(aqdumpdata\(aq, exclude=[\(aqcontenttypes\(aq, \(aqauth\(aq]) +.ft P +.fi +.UNINDENT +.UNINDENT +.sp +The return value of the \fBcall_command()\fP function is the same as the return +value of the \fBhandle()\fP method of the command. +.SH OUTPUT REDIRECTION +.sp +Note that you can redirect standard output and error streams as all commands +support the \fBstdout\fP and \fBstderr\fP options. For example, you could write: +.INDENT 0.0 +.INDENT 3.5 +.sp +.nf +.ft C +with open(\(aq/path/to/command_output\(aq, \(aqw\(aq) as f: + management.call_command(\(aqdumpdata\(aq, stdout=f) +.ft P +.fi +.UNINDENT +.UNINDENT +.SH AUTHOR +Django Software Foundation +.SH COPYRIGHT +Django Software Foundation and contributors +.\" Generated by docutils manpage writer. +. diff --git a/testbed/django__django/docs/misc/design-philosophies.txt b/testbed/django__django/docs/misc/design-philosophies.txt new file mode 100644 index 0000000000000000000000000000000000000000..207685d5569b0710aa43e4a1be8f07be3de1539f --- /dev/null +++ b/testbed/django__django/docs/misc/design-philosophies.txt @@ -0,0 +1,331 @@ +=================== +Design philosophies +=================== + +This document explains some of the fundamental philosophies Django's developers +have used in creating the framework. Its goal is to explain the past and guide +the future. + +Overall +======= + +.. _loose-coupling: + +Loose coupling +-------------- + +.. index:: coupling; loose + +A fundamental goal of Django's stack is `loose coupling and tight cohesion`_. +The various layers of the framework shouldn't "know" about each other unless +absolutely necessary. + +For example, the template system knows nothing about web requests, the database +layer knows nothing about data display and the view system doesn't care which +template system a programmer uses. + +Although Django comes with a full stack for convenience, the pieces of the +stack are independent of another wherever possible. + +.. _`loose coupling and tight cohesion`: http://wiki.c2.com/?CouplingAndCohesion + +.. _less-code: + +Less code +--------- + +Django apps should use as little code as possible; they should lack boilerplate. +Django should take full advantage of Python's dynamic capabilities, such as +introspection. + +.. _quick-development: + +Quick development +----------------- + +The point of a web framework in the 21st century is to make the tedious aspects +of web development fast. Django should allow for incredibly quick web +development. + +.. _dry: + +Don't repeat yourself (DRY) +--------------------------- + +.. index:: + single: DRY + single: Don't repeat yourself + +Every distinct concept and/or piece of data should live in one, and only one, +place. Redundancy is bad. Normalization is good. + +The framework, within reason, should deduce as much as possible from as little +as possible. + +.. seealso:: + + The `discussion of DRY on the Portland Pattern Repository`__ + + __ http://wiki.c2.com/?DontRepeatYourself + +.. _explicit-is-better-than-implicit: + +Explicit is better than implicit +-------------------------------- + +This is a core Python principle listed in :pep:`20`, and it means Django +shouldn't do too much "magic." Magic shouldn't happen unless there's a really +good reason for it. Magic is worth using only if it creates a huge convenience +unattainable in other ways, and it isn't implemented in a way that confuses +developers who are trying to learn how to use the feature. + +.. _consistency: + +Consistency +----------- + +The framework should be consistent at all levels. Consistency applies to +everything from low-level (the Python coding style used) to high-level (the +"experience" of using Django). + +Models +====== + +Explicit is better than implicit +-------------------------------- + +Fields shouldn't assume certain behaviors based solely on the name of the +field. This requires too much knowledge of the system and is prone to errors. +Instead, behaviors should be based on keyword arguments and, in some cases, on +the type of the field. + +Include all relevant domain logic +--------------------------------- + +Models should encapsulate every aspect of an "object," following Martin +Fowler's `Active Record`_ design pattern. + +This is why both the data represented by a model and information about +it (its human-readable name, options like default ordering, etc.) are +defined in the model class; all the information needed to understand a +given model should be stored *in* the model. + +.. _`Active Record`: https://www.martinfowler.com/eaaCatalog/activeRecord.html + +Database API +============ + +The core goals of the database API are: + +SQL efficiency +-------------- + +It should execute SQL statements as few times as possible, and it should +optimize statements internally. + +This is why developers need to call ``save()`` explicitly, rather than the +framework saving things behind the scenes silently. + +This is also why the ``select_related()`` ``QuerySet`` method exists. It's an +optional performance booster for the common case of selecting "every related +object." + +Terse, powerful syntax +---------------------- + +The database API should allow rich, expressive statements in as little syntax +as possible. It should not rely on importing other modules or helper objects. + +Joins should be performed automatically, behind the scenes, when necessary. + +Every object should be able to access every related object, systemwide. This +access should work both ways. + +Option to drop into raw SQL easily, when needed +----------------------------------------------- + +The database API should realize it's a shortcut but not necessarily an +end-all-be-all. The framework should make it easy to write custom SQL -- entire +statements, or just custom ``WHERE`` clauses as custom parameters to API calls. + +URL design +========== + +Loose coupling +-------------- + +URLs in a Django app should not be coupled to the underlying Python code. Tying +URLs to Python function names is a Bad And Ugly Thing. + +Along these lines, the Django URL system should allow URLs for the same app to +be different in different contexts. For example, one site may put stories at +``/stories/``, while another may use ``/news/``. + +Infinite flexibility +-------------------- + +URLs should be as flexible as possible. Any conceivable URL design should be +allowed. + +Encourage best practices +------------------------ + +The framework should make it just as easy (or even easier) for a developer to +design pretty URLs than ugly ones. + +File extensions in web-page URLs should be avoided. + +Vignette-style commas in URLs deserve severe punishment. + +.. _definitive-urls: + +Definitive URLs +--------------- + +.. index:: urls; definitive + +Technically, ``foo.com/bar`` and ``foo.com/bar/`` are two different URLs, and +search-engine robots (and some web traffic-analyzing tools) would treat them as +separate pages. Django should make an effort to "normalize" URLs so that +search-engine robots don't get confused. + +This is the reasoning behind the :setting:`APPEND_SLASH` setting. + +Template system +=============== + +.. _separation-of-logic-and-presentation: + +Separate logic from presentation +-------------------------------- + +We see a template system as a tool that controls presentation and +presentation-related logic -- and that's it. The template system shouldn't +support functionality that goes beyond this basic goal. + +Discourage redundancy +--------------------- + +The majority of dynamic websites use some sort of common sitewide design -- +a common header, footer, navigation bar, etc. The Django template system should +make it easy to store those elements in a single place, eliminating duplicate +code. + +This is the philosophy behind :ref:`template inheritance +`. + +Be decoupled from HTML +---------------------- + +The template system shouldn't be designed so that it only outputs HTML. It +should be equally good at generating other text-based formats, or just plain +text. + +XML should not be used for template languages +--------------------------------------------- + +.. index:: xml; suckiness of + +Using an XML engine to parse templates introduces a whole new world of human +error in editing templates -- and incurs an unacceptable level of overhead in +template processing. + +Assume designer competence +-------------------------- + +The template system shouldn't be designed so that templates necessarily are +displayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of +a limitation and wouldn't allow the syntax to be as nice as it is. Django +expects template authors are comfortable editing HTML directly. + +Treat whitespace obviously +-------------------------- + +The template system shouldn't do magic things with whitespace. If a template +includes whitespace, the system should treat the whitespace as it treats text +-- just display it. Any whitespace that's not in a template tag should be +displayed. + +Don't invent a programming language +----------------------------------- + +The goal is not to invent a programming language. The goal is to offer just +enough programming-esque functionality, such as branching and looping, that is +essential for making presentation-related decisions. The :ref:`Django Template +Language (DTL) ` aims to avoid advanced logic. + +The Django template system recognizes that templates are most often written by +*designers*, not *programmers*, and therefore should not assume Python +knowledge. + +Safety and security +------------------- + +The template system, out of the box, should forbid the inclusion of malicious +code -- such as commands that delete database records. + +This is another reason the template system doesn't allow arbitrary Python code. + +Extensibility +------------- + +The template system should recognize that advanced template authors may want +to extend its technology. + +This is the philosophy behind custom template tags and filters. + +Views +===== + +Simplicity +---------- + +Writing a view should be as simple as writing a Python function. Developers +shouldn't have to instantiate a class when a function will do. + +Use request objects +------------------- + +Views should have access to a request object -- an object that stores metadata +about the current request. The object should be passed directly to a view +function, rather than the view function having to access the request data from +a global variable. This makes it light, clean and easy to test views by passing +in "fake" request objects. + +Loose coupling +-------------- + +A view shouldn't care about which template system the developer uses -- or even +whether a template system is used at all. + +Differentiate between GET and POST +---------------------------------- + +GET and POST are distinct; developers should explicitly use one or the other. +The framework should make it easy to distinguish between GET and POST data. + +.. _cache-design-philosophy: + +Cache Framework +=============== + +The core goals of Django's :doc:`cache framework ` are: + +Less code +--------- + +A cache should be as fast as possible. Hence, all framework code surrounding +the cache backend should be kept to the absolute minimum, especially for +``get()`` operations. + +Consistency +----------- + +The cache API should provide a consistent interface across the different +cache backends. + +Extensibility +------------- + +The cache API should be extensible at the application level based on the +developer's needs (for example, see :ref:`cache_key_transformation`). diff --git a/testbed/django__django/docs/misc/distributions.txt b/testbed/django__django/docs/misc/distributions.txt new file mode 100644 index 0000000000000000000000000000000000000000..f3aec15da8f10d3212ac98ec2a04f6e9276b1724 --- /dev/null +++ b/testbed/django__django/docs/misc/distributions.txt @@ -0,0 +1,33 @@ +=================================== +Third-party distributions of Django +=================================== + +Many third-party distributors are now providing versions of Django integrated +with their package-management systems. These can make installation and upgrading +much easier for users of Django since the integration includes the ability to +automatically install dependencies (like database adapters) that Django +requires. + +Typically, these packages are based on the latest stable release of Django, so +if you want to use the development version of Django you'll need to follow the +instructions for :ref:`installing the development version +` from our Git repository. + +If you're using Linux or a Unix installation, such as OpenSolaris, +check with your distributor to see if they already package Django. If +you're using a Linux distro and don't know how to find out if a package +is available, then now is a good time to learn. The Django Wiki contains +a list of `Third Party Distributions`_ to help you out. + +.. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions + + +For distributors +================ + +If you'd like to package Django for distribution, we'd be happy to help out! +Please join the |django-developers| mailing list and introduce yourself. + +We also encourage all distributors to subscribe to the |django-announce| mailing +list, which is a (very) low-traffic list for announcing new releases of Django +and important bugfixes. diff --git a/testbed/django__django/docs/misc/index.txt b/testbed/django__django/docs/misc/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..6232a26e3765a251b37890d50b55b17d3b629af6 --- /dev/null +++ b/testbed/django__django/docs/misc/index.txt @@ -0,0 +1,13 @@ +================================= +Meta-documentation and miscellany +================================= + +Documentation that we can't find a more organized place for. Like that drawer in +your kitchen with the scissors, batteries, duct tape, and other junk. + +.. toctree:: + :maxdepth: 2 + + api-stability + design-philosophies + distributions diff --git a/testbed/django__django/docs/ref/class-based-views/base.txt b/testbed/django__django/docs/ref/class-based-views/base.txt new file mode 100644 index 0000000000000000000000000000000000000000..b1260093c133442595aaa4d8ae34838a45192016 --- /dev/null +++ b/testbed/django__django/docs/ref/class-based-views/base.txt @@ -0,0 +1,295 @@ +========== +Base views +========== + +The following three classes provide much of the functionality needed to create +Django views. You may think of them as *parent* views, which can be used by +themselves or inherited from. They may not provide all the capabilities +required for projects, in which case there are Mixins and Generic class-based +views. + +Many of Django's built-in class-based views inherit from other class-based +views or various mixins. Because this inheritance chain is very important, the +ancestor classes are documented under the section title of **Ancestors (MRO)**. +MRO is an acronym for Method Resolution Order. + +``View`` +======== + +.. class:: django.views.generic.base.View + + The base view class. 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** + + #. :meth:`setup()` + #. :meth:`dispatch()` + #. :meth:`http_method_not_allowed()` + #. :meth:`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** + + .. attribute:: 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 + :meth:`setup` method assigns the :class:`~django.http.HttpRequest` to + the view's ``request`` attribute, and any positional and/or keyword + arguments :ref:`captured from the URL pattern + ` to the ``args`` and ``kwargs`` + attributes, respectively. Then :meth:`dispatch` is called. + + If a ``View`` subclass defines asynchronous (``async def``) method + handlers, ``as_view()`` will mark the returned callable as a coroutine + function. An ``ImproperlyConfigured`` exception will be raised if both + asynchronous (``async def``) and synchronous (``def``) handlers are + defined on a single view-class. + + .. method:: setup(request, *args, **kwargs) + + Performs key view initialization prior to :meth:`dispatch`. + + If overriding this method, you must call ``super()``. + + .. method:: 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 + :ref:`supporting-other-http-methods` for an example. + + .. method:: 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. + + .. method:: 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. + + If the other HTTP methods handlers on the class are asynchronous + (``async def``) then the response will be wrapped in a coroutine + function for use with ``await``. + +``TemplateView`` +================ + +.. 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: + + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.base.ContextMixin` + * :class:`django.views.generic.base.View` + + **Method Flowchart** + + #. :meth:`~django.views.generic.base.View.setup()` + #. :meth:`~django.views.generic.base.View.dispatch()` + #. :meth:`~django.views.generic.base.View.http_method_not_allowed()` + #. :meth:`~django.views.generic.base.ContextMixin.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 :class:`~django.views.generic.base.ContextMixin`) with + the keyword arguments captured from the URL pattern that served the view. + * You can also add context using the + :attr:`~django.views.generic.base.ContextMixin.extra_context` keyword + argument for :meth:`~django.views.generic.base.View.as_view`. + +``RedirectView`` +================ + +.. 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: + + * :class:`django.views.generic.base.View` + + **Method Flowchart** + + #. :meth:`~django.views.generic.base.View.setup()` + #. :meth:`~django.views.generic.base.View.dispatch()` + #. :meth:`~django.views.generic.base.View.http_method_not_allowed()` + #. :meth:`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//", + ArticleCounterRedirectView.as_view(), + name="article-counter", + ), + path("details//", ArticleDetailView.as_view(), name="article-detail"), + path( + "go-to-django/", + RedirectView.as_view(url="https://www.djangoproject.com/"), + name="go-to-django", + ), + ] + + **Attributes** + + .. attribute:: url + + The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone) + HTTP error. + + .. attribute:: 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. + + .. attribute:: 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``. + + .. attribute:: 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** + + .. method:: get_redirect_url(*args, **kwargs) + + Constructs the target URL for redirection. + + The ``args`` and ``kwargs`` arguments are positional and/or keyword + arguments :ref:`captured from the URL pattern + `, respectively. + + The default implementation uses :attr:`url` as a starting + string and performs expansion of ``%`` named parameters in that string + using the named groups captured in the URL. + + If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the + :attr:`pattern_name` using what was captured in the URL (both named and + unnamed groups are used). + + If requested by :attr:`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. diff --git a/testbed/django__django/docs/ref/class-based-views/generic-editing.txt b/testbed/django__django/docs/ref/class-based-views/generic-editing.txt new file mode 100644 index 0000000000000000000000000000000000000000..9bd543bdfc535b713848db4622827ceb4ff8d9e9 --- /dev/null +++ b/testbed/django__django/docs/ref/class-based-views/generic-editing.txt @@ -0,0 +1,342 @@ +===================== +Generic editing views +===================== + +The following views are described on this page and provide a foundation for +editing content: + +* :class:`django.views.generic.edit.FormView` +* :class:`django.views.generic.edit.CreateView` +* :class:`django.views.generic.edit.UpdateView` +* :class:`django.views.generic.edit.DeleteView` + +.. seealso:: + + The :doc:`messages framework ` contains + :class:`~django.contrib.messages.views.SuccessMessageMixin`, which + facilitates presenting messages about successful form submissions. + +.. note:: + + Some of the examples on this page assume that an ``Author`` model has been + defined as follows in ``myapp/models.py``:: + + from django.db import models + from django.urls import reverse + + + class Author(models.Model): + name = models.CharField(max_length=200) + + def get_absolute_url(self): + return reverse("author-detail", kwargs={"pk": self.pk}) + +``FormView`` +============ + +.. class:: django.views.generic.edit.FormView + + A view that displays a form. On error, redisplays the form with validation + errors; on success, redirects to a new URL. + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseFormView` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.edit.ProcessFormView` + * :class:`django.views.generic.base.View` + + **Example myapp/forms.py**:: + + from django import forms + + + class ContactForm(forms.Form): + name = forms.CharField() + message = forms.CharField(widget=forms.Textarea) + + def send_email(self): + # send email using the self.cleaned_data dictionary + pass + + **Example myapp/views.py**:: + + from myapp.forms import ContactForm + from django.views.generic.edit import FormView + + + class ContactFormView(FormView): + template_name = "contact.html" + form_class = ContactForm + success_url = "/thanks/" + + def form_valid(self, form): + # This method is called when valid form data has been POSTed. + # It should return an HttpResponse. + form.send_email() + return super().form_valid(form) + + **Example myapp/contact.html**: + + .. code-block:: html+django + + {% csrf_token %} + {{ form.as_p }} + + + +.. class:: django.views.generic.edit.BaseFormView + + A base view for displaying a form. It is not intended to be used directly, + but rather as a parent class of the + :class:`django.views.generic.edit.FormView` or other views displaying a + form. + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.edit.ProcessFormView` + +``CreateView`` +============== + +.. class:: django.views.generic.edit.CreateView + + A view that displays a form for creating an object, redisplaying the form + with validation errors (if there are any) and saving the object. + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseCreateView` + * :class:`django.views.generic.edit.ModelFormMixin` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.edit.ProcessFormView` + * :class:`django.views.generic.base.View` + + **Attributes** + + .. attribute:: template_name_suffix + + The ``CreateView`` page displayed to a ``GET`` request uses a + ``template_name_suffix`` of ``'_form'``. For + example, changing this attribute to ``'_create_form'`` for a view + creating objects for the example ``Author`` model would cause the + default ``template_name`` to be ``'myapp/author_create_form.html'``. + + .. attribute:: object + + When using ``CreateView`` you have access to ``self.object``, which is + the object being created. If the object hasn't been created yet, the + value will be ``None``. + + **Example myapp/views.py**:: + + from django.views.generic.edit import CreateView + from myapp.models import Author + + + class AuthorCreateView(CreateView): + model = Author + fields = ["name"] + + **Example myapp/author_form.html**: + + .. code-block:: html+django + +
    {% csrf_token %} + {{ form.as_p }} + +
    + +.. class:: django.views.generic.edit.BaseCreateView + + A base view for creating a new object instance. It is not intended to be + used directly, but rather as a parent class of the + :class:`django.views.generic.edit.CreateView`. + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.edit.ModelFormMixin` + * :class:`django.views.generic.edit.ProcessFormView` + + **Methods** + + .. method:: get(request, *args, **kwargs) + + Sets the current object instance (``self.object``) to ``None``. + + .. method:: post(request, *args, **kwargs) + + Sets the current object instance (``self.object``) to ``None``. + +``UpdateView`` +============== + +.. class:: django.views.generic.edit.UpdateView + + A view that displays a form for editing an existing object, redisplaying + the form with validation errors (if there are any) and saving changes to + the object. This uses a form automatically generated from the object's + model class (unless a form class is manually specified). + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseUpdateView` + * :class:`django.views.generic.edit.ModelFormMixin` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.edit.ProcessFormView` + * :class:`django.views.generic.base.View` + + **Attributes** + + .. attribute:: template_name_suffix + + The ``UpdateView`` page displayed to a ``GET`` request uses a + ``template_name_suffix`` of ``'_form'``. For + example, changing this attribute to ``'_update_form'`` for a view + updating objects for the example ``Author`` model would cause the + default ``template_name`` to be ``'myapp/author_update_form.html'``. + + .. attribute:: object + + When using ``UpdateView`` you have access to ``self.object``, which is + the object being updated. + + **Example myapp/views.py**:: + + from django.views.generic.edit import UpdateView + from myapp.models import Author + + + class AuthorUpdateView(UpdateView): + model = Author + fields = ["name"] + template_name_suffix = "_update_form" + + **Example myapp/author_update_form.html**: + + .. code-block:: html+django + +
    {% csrf_token %} + {{ form.as_p }} + +
    + +.. class:: django.views.generic.edit.BaseUpdateView + + A base view for updating an existing object instance. It is not intended to + be used directly, but rather as a parent class of the + :class:`django.views.generic.edit.UpdateView`. + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.edit.ModelFormMixin` + * :class:`django.views.generic.edit.ProcessFormView` + + **Methods** + + .. method:: get(request, *args, **kwargs) + + Sets the current object instance (``self.object``). + + .. method:: post(request, *args, **kwargs) + + Sets the current object instance (``self.object``). + +``DeleteView`` +============== + +.. class:: django.views.generic.edit.DeleteView + + A view that displays a confirmation page and deletes an existing object. + The given object will only be deleted if the request method is ``POST``. If + this view is fetched via ``GET``, it will display a confirmation page that + should contain a form that POSTs to the same URL. + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseDeleteView` + * :class:`django.views.generic.edit.DeletionMixin` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.base.ContextMixin` + * :class:`django.views.generic.detail.BaseDetailView` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.base.View` + + **Attributes** + + .. attribute:: form_class + + Inherited from :class:`~django.views.generic.edit.BaseDeleteView`. The + form class that will be used to confirm the request. By default + :class:`django.forms.Form`, resulting in an empty form that is always + valid. + + By providing your own ``Form`` subclass, you can add additional + requirements, such as a confirmation checkbox, for example. + + .. attribute:: template_name_suffix + + The ``DeleteView`` page displayed to a ``GET`` request uses a + ``template_name_suffix`` of ``'_confirm_delete'``. For + example, changing this attribute to ``'_check_delete'`` for a view + deleting objects for the example ``Author`` model would cause the + default ``template_name`` to be ``'myapp/author_check_delete.html'``. + + **Example myapp/views.py**:: + + from django.urls import reverse_lazy + from django.views.generic.edit import DeleteView + from myapp.models import Author + + + class AuthorDeleteView(DeleteView): + model = Author + success_url = reverse_lazy("author-list") + + **Example myapp/author_confirm_delete.html**: + + .. code-block:: html+django + +
    {% csrf_token %} +

    Are you sure you want to delete "{{ object }}"?

    + {{ form }} + +
    + +.. class:: django.views.generic.edit.BaseDeleteView + + A base view for deleting an object instance. It is not intended to be used + directly, but rather as a parent class of the + :class:`django.views.generic.edit.DeleteView`. + + **Ancestors (MRO)** + + This view inherits methods and attributes from the following views: + + * :class:`django.views.generic.edit.DeletionMixin` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.detail.BaseDetailView` diff --git a/testbed/django__django/docs/ref/class-based-views/mixins-date-based.txt b/testbed/django__django/docs/ref/class-based-views/mixins-date-based.txt new file mode 100644 index 0000000000000000000000000000000000000000..6a441140ce0e20dff187a3c605aa0f0eb6cea10d --- /dev/null +++ b/testbed/django__django/docs/ref/class-based-views/mixins-date-based.txt @@ -0,0 +1,337 @@ +================= +Date-based mixins +================= + +.. currentmodule:: django.views.generic.dates + +.. note:: + + All the date formatting attributes in these mixins use + :func:`~time.strftime` format characters. Do not try to use the format + characters from the :ttag:`now` template tag as they are not compatible. + +``YearMixin`` +============= + +.. class:: YearMixin + + A mixin that can be used to retrieve and provide parsing information for a + year component of a date. + + **Methods and Attributes** + + .. attribute:: year_format + + The :func:`~time.strftime` format to use when parsing the year. + By default, this is ``'%Y'``. + + .. attribute:: year + + **Optional** The value for the year, as a string. By default, set to + ``None``, which means the year will be determined using other means. + + .. method:: get_year_format() + + Returns the :func:`~time.strftime` format to use when parsing the + year. Returns :attr:`~YearMixin.year_format` by default. + + .. method:: get_year() + + Returns the year for which this view will display data, as a string. + Tries the following sources, in order: + + * The value of the :attr:`YearMixin.year` attribute. + * The value of the ``year`` argument captured in the URL pattern. + * The value of the ``year`` ``GET`` query argument. + + Raises a 404 if no valid year specification can be found. + + .. method:: get_next_year(date) + + Returns a date object containing the first day of the year after the + date provided. This function can also return ``None`` or raise an + :class:`~django.http.Http404` exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + + .. method:: get_previous_year(date) + + Returns a date object containing the first day of the year before the + date provided. This function can also return ``None`` or raise an + :class:`~django.http.Http404` exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + +``MonthMixin`` +============== + +.. class:: MonthMixin + + A mixin that can be used to retrieve and provide parsing information for a + month component of a date. + + **Methods and Attributes** + + .. attribute:: month_format + + The :func:`~time.strftime` format to use when parsing the month. By + default, this is ``'%b'``. + + .. attribute:: 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. + + .. method:: get_month_format() + + Returns the :func:`~time.strftime` format to use when parsing the + month. Returns :attr:`~MonthMixin.month_format` by default. + + .. method:: 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 :attr:`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. + + .. method:: 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 + :class:`~django.http.Http404` exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + + .. method:: 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 + :class:`~django.http.Http404` exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + +``DayMixin`` +============ + +.. class:: DayMixin + + A mixin that can be used to retrieve and provide parsing information for a + day component of a date. + + **Methods and Attributes** + + .. attribute:: day_format + + The :func:`~time.strftime` format to use when parsing the day. By + default, this is ``'%d'``. + + .. attribute:: 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. + + .. method:: get_day_format() + + Returns the :func:`~time.strftime` format to use when parsing the day. + Returns :attr:`~DayMixin.day_format` by default. + + .. method:: 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 :attr:`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. + + .. method:: 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 + :class:`~django.http.Http404` exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + + .. method:: get_previous_day(date) + + Returns a date object containing the previous valid day. This function + can also return ``None`` or raise an :class:`~django.http.Http404` + exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + +``WeekMixin`` +============= + +.. class:: WeekMixin + + A mixin that can be used to retrieve and provide parsing information for a + week component of a date. + + **Methods and Attributes** + + .. attribute:: week_format + + The :func:`~time.strftime` format to use when parsing the week. By + default, this is ``'%U'``, which means the week starts on Sunday. Set + it to ``'%W'`` or ``'%V'`` (ISO 8601 week) if your week starts on + Monday. + + .. attribute:: week + + **Optional** The value for the week, as a string. By default, set to + ``None``, which means the week will be determined using other means. + + .. method:: get_week_format() + + Returns the :func:`~time.strftime` format to use when parsing the + week. Returns :attr:`~WeekMixin.week_format` by default. + + .. method:: get_week() + + Returns the week for which this view will display data, as a string. + Tries the following sources, in order: + + * The value of the :attr:`WeekMixin.week` attribute. + * The value of the ``week`` argument captured in the URL pattern + * The value of the ``week`` ``GET`` query argument. + + Raises a 404 if no valid week specification can be found. + + .. method:: get_next_week(date) + + Returns a date object containing the first day of the week after the + date provided. This function can also return ``None`` or raise an + :class:`~django.http.Http404` exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + + .. method:: get_prev_week(date) + + Returns a date object containing the first day of the week before the + date provided. This function can also return ``None`` or raise an + :class:`~django.http.Http404` exception, depending on the values of + :attr:`~BaseDateListView.allow_empty` and + :attr:`~DateMixin.allow_future`. + +``DateMixin`` +============= + +.. class:: DateMixin + + A mixin class providing common behavior for all date-based views. + + **Methods and Attributes** + + .. attribute:: 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 :doc:`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. + + .. 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``. + + .. method:: get_date_field() + + Returns the name of the field that contains the date data that this + view will operate on. Returns :attr:`~DateMixin.date_field` by default. + + .. method:: 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 + :attr:`~DateMixin.allow_future` by default. + +``BaseDateListView`` +==================== + +.. class:: BaseDateListView + + A base class that provides common behavior for all date-based views. There + won't normally be a reason to instantiate + :class:`~django.views.generic.dates.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** + + * :class:`~django.views.generic.dates.DateMixin` + * :class:`~django.views.generic.list.MultipleObjectMixin` + + **Methods and Attributes** + + .. attribute:: 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 + :attr:`django.views.generic.list.MultipleObjectMixin.allow_empty`, + except for the default value, which is ``False``. + + .. attribute:: date_list_period + + **Optional** A string defining the aggregation period for + ``date_list``. It must be one of ``'year'`` (default), ``'month'``, or + ``'day'``. + + .. method:: 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 + :class:`~django.views.generic.list.MultipleObjectMixin`. + + .. method:: 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``. + + .. method:: get_date_list_period() + + Returns the aggregation period for ``date_list``. Returns + :attr:`~BaseDateListView.date_list_period` by default. + + .. method:: 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 + :meth:`~BaseDateListView.get_date_list_period` is used. ``date_type`` + and ``ordering`` are passed to + :meth:`QuerySet.dates()`. diff --git a/testbed/django__django/docs/ref/class-based-views/mixins-single-object.txt b/testbed/django__django/docs/ref/class-based-views/mixins-single-object.txt new file mode 100644 index 0000000000000000000000000000000000000000..1378e10823df03fb9bbe0271820cca30a874ccc3 --- /dev/null +++ b/testbed/django__django/docs/ref/class-based-views/mixins-single-object.txt @@ -0,0 +1,172 @@ +==================== +Single object mixins +==================== + +``SingleObjectMixin`` +===================== + +.. class:: django.views.generic.detail.SingleObjectMixin + + Provides a mechanism for looking up an object associated with the + current HTTP request. + + **Methods and Attributes** + + .. attribute:: model + + The model that this view will display data for. Specifying ``model + = Foo`` is effectively the same as specifying ``queryset = + Foo.objects.all()``, where ``objects`` stands for ``Foo``’s + :ref:`default manager `. + + .. attribute:: queryset + + A ``QuerySet`` that represents the objects. If provided, the value of + ``queryset`` supersedes the value provided for :attr:`model`. + + .. warning:: + + ``queryset`` is a class attribute with a *mutable* value so care + must be taken when using it directly. Before using it, either call + its :meth:`~django.db.models.query.QuerySet.all` method or + retrieve it with :meth:`get_queryset` which takes care of the + cloning behind the scenes. + + .. attribute:: slug_field + + The name of the field on the model that contains the slug. By default, + ``slug_field`` is ``'slug'``. + + .. attribute:: slug_url_kwarg + + The name of the URLConf keyword argument that contains the slug. By + default, ``slug_url_kwarg`` is ``'slug'``. + + .. attribute:: pk_url_kwarg + + The name of the URLConf keyword argument that contains the primary key. + By default, ``pk_url_kwarg`` is ``'pk'``. + + .. attribute:: context_object_name + + Designates the name of the variable to use in the context. + + .. attribute:: query_pk_and_slug + + If ``True``, causes :meth:`get_object()` to perform its lookup using + both the primary key and the slug. Defaults to ``False``. + + This attribute can help mitigate `insecure direct object reference`_ + attacks. When applications allow access to individual objects by a + sequential primary key, an attacker could brute-force guess all URLs; + thereby obtaining a list of all objects in the application. If users + with access to individual objects should be prevented from obtaining + this list, setting ``query_pk_and_slug`` to ``True`` will help prevent + the guessing of URLs as each URL will require two correct, + non-sequential arguments. Using a unique slug may serve the same + purpose, but this scheme allows you to have non-unique slugs. + + .. _insecure direct object reference: https://wiki.owasp.org/index.php/Top_10_2013-A4-Insecure_Direct_Object_References + + .. method:: get_object(queryset=None) + + Returns the single object that this view will display. If ``queryset`` + is provided, that queryset will be used as the source of objects; + otherwise, :meth:`get_queryset` will be used. ``get_object()`` looks + for a :attr:`pk_url_kwarg` argument in the arguments to the view; if + this argument is found, this method performs a primary-key based lookup + using that value. If this argument is not found, it looks for a + :attr:`slug_url_kwarg` argument, and performs a slug lookup using the + :attr:`slug_field`. + + When :attr:`query_pk_and_slug` is ``True``, ``get_object()`` will + perform its lookup using both the primary key and the slug. + + .. method:: get_queryset() + + Returns the queryset that will be used to retrieve the object that + this view will display. By default, :meth:`get_queryset` returns the + value of the :attr:`queryset` attribute if it is set, otherwise + it constructs a :class:`~django.db.models.query.QuerySet` by calling + the ``all()`` method on the :attr:`model` attribute's default manager. + + .. method:: get_context_object_name(obj) + + Return the context variable name that will be used to contain the + data that this view is manipulating. If :attr:`context_object_name` is + not set, the context name will be constructed from the ``model_name`` + of the model that the queryset is composed from. For example, the model + ``Article`` would have context object named ``'article'``. + + .. method:: get_context_data(**kwargs) + + Returns context data for displaying the object. + + The base implementation of this method requires that the ``self.object`` + attribute be set by the view (even if ``None``). Be sure to do this if + you are using this mixin without one of the built-in views that does so. + + It returns a dictionary with these contents: + + * ``object``: The object that this view is displaying + (``self.object``). + * ``context_object_name``: ``self.object`` will also be stored under + the name returned by :meth:`get_context_object_name`, which defaults + to the lowercased version of the model name. + + .. admonition:: Context variables override values from template context processors + + Any variables from :meth:`get_context_data` take precedence over + context variables from :ref:`context processors + `. For example, if your view + sets the :attr:`model` attribute to + :class:`~django.contrib.auth.models.User`, the default context + object name of ``user`` would override the ``user`` variable from + the :func:`django.contrib.auth.context_processors.auth` context + processor. Use :meth:`get_context_object_name` to avoid a clash. + + .. method:: get_slug_field() + + Returns the name of a slug field to be used to look up by slug. By + default this returns the value of :attr:`slug_field`. + + +``SingleObjectTemplateResponseMixin`` +===================================== + +.. class:: django.views.generic.detail.SingleObjectTemplateResponseMixin + + A mixin class that performs template-based response rendering for views + that operate upon a single object instance. Requires that the view it is + mixed with provides ``self.object``, the object instance that the view is + operating on. ``self.object`` will usually be, but is not required to be, + an instance of a Django model. It may be ``None`` if the view is in the + process of constructing a new instance. + + **Extends** + + * :class:`~django.views.generic.base.TemplateResponseMixin` + + **Methods and Attributes** + + .. attribute:: template_name_field + + The field on the current object instance that can be used to determine + the name of a candidate template. If either ``template_name_field`` + itself or the value of the ``template_name_field`` on the current + object instance is ``None``, the object will not be used for a + candidate template name. + + .. attribute:: template_name_suffix + + The suffix to append to the auto-generated candidate template name. + Default suffix is ``_detail``. + + .. method:: get_template_names() + + Returns a list of candidate template names. Returns the following list: + + * the value of ``template_name`` on the view (if provided) + * the contents of the ``template_name_field`` field on the + object instance that the view is operating upon (if available) + * ``/.html``