prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
login"]) class PermissionManager(models.Manager): use_in_migrations = True def get_by_natural_key(self, codename, app_label, model): return self.get( codename=codename, content_type=ContentType.objects.db_manager(self.db).get_by_natural_key( app_label, model ...
nd add an object. - The "change" permission limits a user's ability to view the change list, view the "change" form and change an object. - The "delete" permission limits the ability to delete an object. - The "view" permi
system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows: - The "add" permission limits the user's ability to view the "add" form a
{ "filepath": "django/contrib/auth/models.py", "language": "python", "file_size": 21479, "cut_index": 1331, "middle_length": 229 }
t login_not_required, login_required from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm, ) from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.exception...
_cache from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters from django.views.generic.base import TemplateView from django.views.generic.edit import FormView UserModel = get_user_model()
.utils.decorators import method_decorator from django.utils.http import url_has_allowed_host_and_scheme, urlsafe_base64_decode from django.utils.translation import gettext_lazy as _ from django.views.decorators.cache import never
{ "filepath": "django/contrib/auth/views.py", "language": "python", "file_size": 13870, "cut_index": 921, "middle_length": 229 }
connections from django.utils.functional import cached_property from django.utils.text import capfirst class NotRunningInTTYException(Exception): pass PASSWORD_FIELD = "password" class Command(BaseCommand): help = "Used to create a superuser." requires_migrations_checks = True stealth_options = ("...
er.", ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help=( "Tells Django to NOT prompt the user for input of any kind.
eld( self.UserModel.USERNAME_FIELD ) def add_arguments(self, parser): parser.add_argument( "--%s" % self.UserModel.USERNAME_FIELD, help="Specifies the login for the superus
{ "filepath": "django/contrib/auth/management/commands/createsuperuser.py", "language": "python", "file_size": 13740, "cut_index": 921, "middle_length": 229 }
o.contrib.auth import validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0007_alter_validators_add_error_messages"), ] operations = [ migrations.AlterField( model_name="user", name="username", ...
ters, digits and @/./+/-/_ " "only." ), max_length=150, unique=True, validators=[validators.UnicodeUsernameValidator()], verbose_name="username",
or fewer. Let
{ "filepath": "django/contrib/auth/migrations/0008_alter_user_username_max_length.py", "language": "python", "file_size": 814, "cut_index": 522, "middle_length": 14 }
import default_storage from django.utils.deprecation import MiddlewareMixin class MessageMiddleware(MiddlewareMixin): """ Middleware that handles temporary messages. """ def process_request(self, request): request._messages = default_storage(request) def process_response(self, request, r...
not contain # messages storage, so make no assumption that it will be there. if hasattr(request, "_messages"): unstored_messages = request._messages.update(response) if unstored_messages and settings.DEBUG:
her middleware layer may return a request which does
{ "filepath": "django/contrib/messages/middleware.py", "language": "python", "file_size": 986, "cut_index": 582, "middle_length": 52 }
ImproperlyConfigured from django.core.handlers.asgi import ASGIRequest from django.shortcuts import resolve_url from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject def get_user(request): if not hasattr(request, "_cached_user"): request._cached_user = a...
ango authentication middleware requires session " "middleware to be installed. Edit your MIDDLEWARE setting to " "insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'dj
return request._acached_user class AuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): if not hasattr(request, "session"): raise ImproperlyConfigured( "The Dj
{ "filepath": "django/contrib/auth/middleware.py", "language": "python", "file_size": 11826, "cut_index": 921, "middle_length": 229 }
style from django.db import DEFAULT_DB_ALIAS, migrations, router, transaction def _get_all_permissions(opts): """ Return (codename, name) for all permissions in the given opts. """ return [*_get_builtin_permissions(opts), *opts.permissions] def _get_builtin_permissions(opts): """ Return (cod...
sity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs, ): if not app_config.models_module: return try: Permission = apps.get_model("auth", "Permission") except LookupError: return
end( ( get_permission_codename(action, opts), "Can %s %s" % (action, opts.verbose_name_raw), ) ) return perms def create_permissions( app_config, verbo
{ "filepath": "django/contrib/auth/management/__init__.py", "language": "python", "file_size": 9225, "cut_index": 921, "middle_length": 229 }
template import Library from django.utils.html import format_html, format_html_join from django.utils.translation import gettext register = Library() @register.simple_tag def render_password_as_hash(value): if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX): return format_html("<p><strong>{}</str...
gettext("Invalid password format or unknown hashing algorithm."), ) items = [(gettext(key), val) for key, val in hashed_summary.items()] return format_html( "<p>{}</p>", format_html_join(" ", "<strong>{}</strong>: <bdi>{}<
"<p><strong>{}</strong></p>",
{ "filepath": "django/contrib/auth/templatetags/auth.py", "language": "python", "file_size": 936, "cut_index": 606, "middle_length": 52 }
nt_time_compare, salted_hmac from django.utils.http import base36_to_int, int_to_base36 class PasswordResetTokenGenerator: """ Strategy object used to generate and check tokens for the password reset mechanism. """ key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" algorithm ...
ttings.SECRET_KEY_FALLBACKS return self._secret_fallbacks def _set_fallbacks(self, fallbacks): self._secret_fallbacks = fallbacks secret_fallbacks = property(_get_fallbacks, _set_fallbacks) def make_token(self, user):
ettings.SECRET_KEY def _set_secret(self, secret): self._secret = secret secret = property(_get_secret, _set_secret) def _get_fallbacks(self): if self._secret_fallbacks is None: return se
{ "filepath": "django/contrib/auth/tokens.py", "language": "python", "file_size": 4328, "cut_index": 614, "middle_length": 229 }
django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0003_alter_user_email_max_length"), ] # No database changes; modifies validators and error_messages (#13147). operations = [ migrations.AlterField( model_name="user", ...
()], help_text=( "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ " "only." ), unique=True, verbose_name="username", ),
validators=[validators.UnicodeUsernameValidator
{ "filepath": "django/contrib/auth/migrations/0004_alter_user_username_opts.py", "language": "python", "file_size": 880, "cut_index": 559, "middle_length": 52 }
seStorage from django.contrib.messages.storage.cookie import CookieStorage from django.contrib.messages.storage.session import SessionStorage class FallbackStorage(BaseStorage): """ Try to store all messages in the first backend. Store any unstored messages in each subsequent backend. """ storage...
l_messages = [] for storage in self.storages: messages, all_retrieved = storage._get() # If the backend hasn't been used, no more retrieval is necessary. if messages is None: break if
gs) for storage_class in self.storage_classes ] self._used_storages = set() def _get(self, *args, **kwargs): """ Get a single list of messages from all storage backends. """ al
{ "filepath": "django/contrib/messages/storage/fallback.py", "language": "python", "file_size": 2093, "cut_index": 563, "middle_length": 229 }
ngo.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.finders import get_finders from django.core.checks import Error E005 = Error( f"The STORAGES setting must define a '{STATICFILES_STORAGE_ALIAS}' storage.", id="staticfiles.E005", ) def check_finders(app_configs, **kwargs): ...
end(finder_errors) return errors def check_storages(app_configs, **kwargs): """Ensure staticfiles is defined in STORAGES setting.""" errors = [] if STATICFILES_STORAGE_ALIAS not in settings.STORAGES: errors.append(E005) return
pass else: errors.ext
{ "filepath": "django/contrib/staticfiles/checks.py", "language": "python", "file_size": 836, "cut_index": 520, "middle_length": 52 }
nc_to_async from django.conf import settings from django.contrib.staticfiles import utils from django.contrib.staticfiles.views import serve from django.core.handlers.asgi import ASGIHandler from django.core.handlers.exception import response_for_exception from django.core.handlers.wsgi import WSGIHandler, get_path_in...
t_base_url(self): utils.check_settings() return settings.STATIC_URL def _should_handle(self, path): """ Check if the path should be handled. Ignore the path if: * the host is provided as part of the base_url
(e.g. in a # request_finished signal) handles_files = True def load_middleware(self): # Middleware are already loaded for self.application; no need to reload # them for self. pass def ge
{ "filepath": "django/contrib/staticfiles/handlers.py", "language": "python", "file_size": 4043, "cut_index": 614, "middle_length": 229 }
ettings from django.core.exceptions import ImproperlyConfigured def matches_patterns(path, patterns): """ Return True or False depending on whether the ``path`` should be ignored (if it matches any pattern in ``ignore_patterns``). """ return any(fnmatch.fnmatchcase(path, pattern) for pattern in pa...
ntinue if location: fn = os.path.join(location, fn) # Match the full file path. if matches_patterns(fn, ignore_patterns): continue yield fn for dir in directories: if matches_p
if ignore_patterns is None: ignore_patterns = [] directories, files = storage.listdir(location) for fn in files: # Match only the basename. if matches_patterns(fn, ignore_patterns): co
{ "filepath": "django/contrib/staticfiles/utils.py", "language": "python", "file_size": 2279, "cut_index": 563, "middle_length": 229 }
cached_property class Command(BaseCommand): """ Copies or symlinks static files from different locations to the settings.STATIC_ROOT. """ help = "Collect static files in a single location." requires_system_checks = [Tags.staticfiles] def __init__(self, *args, **kwargs): super()....
edError: return False return True def add_arguments(self, parser): parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="
= [] self.deleted_files = [] self.storage = staticfiles_storage self.style = no_style() @cached_property def local(self): try: self.storage.path("") except NotImplement
{ "filepath": "django/contrib/staticfiles/management/commands/collectstatic.py", "language": "python", "file_size": 16248, "cut_index": 921, "middle_length": 229 }
conf import settings from django.contrib.staticfiles.handlers import StaticFilesHandler from django.core.management.commands.runserver import Command as RunserverCommand class Command(RunserverCommand): help = ( "Starts a lightweight web server for development and also serves static files." ) def...
help="Allows serving static files even if DEBUG is False.", ) def get_handler(self, *args, **options): """ Return the static files serving handler wrapping the default handler, if static files should be served
r", help="Tells Django to NOT automatically serve static files at STATIC_URL.", ) parser.add_argument( "--insecure", action="store_true", dest="insecure_serving",
{ "filepath": "django/contrib/staticfiles/management/commands/runserver.py", "language": "python", "file_size": 1373, "cut_index": 524, "middle_length": 229 }
rom django.conf import settings from django.core.checks import Error from django.core.exceptions import ValidationError def check_site_id(app_configs, **kwargs): # Inner import avoids AppRegistryNotReady from django.contrib.sites.models import Site if hasattr(settings, "SITE_ID"): try: ...
d != settings.SITE_ID: expected_type = type(site_id).__name__ return [ Error( f"The SITE_ID setting must be of type {expected_type}.", id="sites.E101",
idate: {exc}.", id="sites.E101" ), ] else: # to_python() might coerce a SITE_ID of the wrong type to the valid # type, e.g. "1" to 1 for AutoField. if site_i
{ "filepath": "django/contrib/sites/checks.py", "language": "python", "file_size": 1049, "cut_index": 513, "middle_length": 229 }
ite object. """ from django.apps import apps as global_apps from django.conf import settings from django.core.management.color import no_style from django.db import DEFAULT_DB_ALIAS, connections, router def create_default_site( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, ap...
the test suite after flush/syncdb), it isn't guaranteed that # the next id will be 1, so we coerce it. See #15573 and #16353. This # can also crop up outside of tests - see #15346. if verbosity >= 2: print("Creating exam
urn if not Site.objects.using(using).exists(): # The default settings set SITE_ID = 1, and some tests in Django's test # suite rely on this value. However, if database sequences are reused # (e.g. in
{ "filepath": "django/contrib/sites/management.py", "language": "python", "file_size": 1646, "cut_index": 537, "middle_length": 229 }
import models from django.db.models.signals import pre_delete, pre_save from django.http.request import split_domain_port from django.utils.translation import gettext_lazy as _ SITE_CACHE = {} def _simple_domain_name_validator(value): """ Validate that the given value contains no whitespaces to prevent comm...
SITE_CACHE[site_id] = site return SITE_CACHE[site_id] def _get_site_by_request(self, request): host = request.get_host() try: # First attempt to look up the site by host with or without port.
."), code="invalid", ) class SiteManager(models.Manager): use_in_migrations = True def _get_site_by_id(self, site_id): if site_id not in SITE_CACHE: site = self.get(pk=site_id)
{ "filepath": "django/contrib/sites/models.py", "language": "python", "file_size": 3695, "cut_index": 614, "middle_length": 229 }
jango.utils.connection import BaseConnectionHandler, ConnectionProxy from django.utils.module_loading import import_string from . import checks, signals # NOQA from .base import ( DEFAULT_TASK_BACKEND_ALIAS, DEFAULT_TASK_QUEUE_NAME, Task, TaskContext, TaskResult, TaskResultStatus, task, ) ...
params = self.settings[alias] backend = params["BACKEND"] try: backend_cls = import_string(backend) except ImportError as e: raise InvalidTaskBackend(f"Could not find backend '{backend}': {e}") from e
, "TaskContext", "TaskResult", "TaskResultStatus", ] class TaskBackendHandler(BaseConnectionHandler): settings_name = "TASKS" exception_class = InvalidTaskBackend def create_connection(self, alias):
{ "filepath": "django/tasks/__init__.py", "language": "python", "file_size": 1178, "cut_index": 518, "middle_length": 229 }
sgiref.sync import async_to_sync, sync_to_async from django.db.models.enums import TextChoices from django.utils.json import normalize_json from django.utils.module_loading import import_string from django.utils.translation import pgettext_lazy from .exceptions import TaskResultMismatch DEFAULT_TASK_BACKEND_ALIAS = ...
EADY", pgettext_lazy("Task", "Ready")) # The Task is currently running. RUNNING = ("RUNNING", pgettext_lazy("Task", "Running")) # The Task raised an exception during execution, or was unable to start. FAILED = ("FAILED", pgettext_lazy("Task
_at", "started_at", "last_attempted_at", "status", "enqueued_at", "worker_ids", } class TaskResultStatus(TextChoices): # The Task has just been enqueued, or is ready to be executed again. READY = ("R
{ "filepath": "django/tasks/base.py", "language": "python", "file_size": 8547, "cut_index": 716, "middle_length": 229 }
contrib.messages.storage.base import BaseStorage from django.contrib.messages.storage.cookie import MessageDecoder, MessageEncoder from django.core.exceptions import ImproperlyConfigured class SessionStorage(BaseStorage): """ Store messages in the session (that is, django.contrib.sessions). """ sessi...
kwargs) def _get(self, *args, **kwargs): """ Retrieve a list of messages from the request's session. This storage always stores everything it is given, so return True for the all_retrieved flag. """ retu
emporary message storage requires session " "middleware to be installed, and come before the message " "middleware in the MIDDLEWARE list." ) super().__init__(request, *args, **
{ "filepath": "django/contrib/messages/storage/session.py", "language": "python", "file_size": 1764, "cut_index": 537, "middle_length": 229 }
tic files. The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``. """ def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = settings.STATIC_ROOT if base_url is None: base_url = settings...
"You're using the staticfiles app " "without having set the STATIC_ROOT " "setting to a filesystem path." ) return super().path(name) class HashedFilesMixin: default_template = """url("%
so we restore the empty value. if not location: self.base_location = None self.location = None def path(self, name): if not self.location: raise ImproperlyConfigured(
{ "filepath": "django/contrib/staticfiles/storage.py", "language": "python", "file_size": 23320, "cut_index": 1331, "middle_length": 229 }
ntrib.staticfiles import finders from django.core.management.base import LabelCommand class Command(LabelCommand): help = "Finds the absolute paths for the given static file(s)." label = "staticfile" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( ...
n %s" % "\n ".join([str(loc) for loc in finders.searched_locations]) ) else: searched_locations = "" if result: if not isinstance(result, (list, tuple)): result = [result
options): verbosity = options["verbosity"] result = finders.find(path, find_all=options["all"]) if verbosity >= 2: searched_locations = ( "\nLooking in the following locations:\
{ "filepath": "django/contrib/staticfiles/management/commands/findstatic.py", "language": "python", "file_size": 1643, "cut_index": 537, "middle_length": 229 }
y, ngettext, ngettext_lazy, npgettext_lazy, pgettext, round_away_from_one, ) register = template.Library() @register.filter(is_safe=True) def ordinal(value): """ Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any non-negative integer....
pgettext("ordinal 11, 12, 13", "{}th").format(value) else: templates = ( # Translators: Ordinal format when value ends with 0, e.g. 80th. pgettext("ordinal 0", "{}th"), # Translators: Ordinal format when val
nal format when value is 1 (1st). value = pgettext("ordinal is 1", "{}st").format(value) elif value % 100 in (11, 12, 13): # Translators: Ordinal format for 11 (11th), 12 (12th), and 13 (13th). value =
{ "filepath": "django/contrib/humanize/templatetags/humanize.py", "language": "python", "file_size": 13010, "cut_index": 921, "middle_length": 229 }
ty from django.utils.module_loading import import_string # To keep track on which directories the finder has searched the static files. searched_locations = [] class BaseFinder: """ A base file finder to be used for custom staticfiles finder classes. """ def check(self, **kwargs): raise NotI...
provide a list() method" ) class FileSystemFinder(BaseFinder): """ A static files finder that uses the ``STATICFILES_DIRS`` setting to locate files. """ def __init__(self, app_names=None, *args, **kwargs): # List of
Given an optional list of paths to ignore, return a two item iterable consisting of the relative path and storage instance. """ raise NotImplementedError( "subclasses of BaseFinder must
{ "filepath": "django/contrib/staticfiles/finders.py", "language": "python", "file_size": 10668, "cut_index": 921, "middle_length": 229 }
ettings from django.core import checks from django.core.exceptions import FieldDoesNotExist from django.db import models class CurrentSiteManager(models.Manager): "Use this to limit objects to those associated with the current site." use_in_migrations = True def __init__(self, field_name=None): ...
checks.Error( "CurrentSiteManager could not find a field named '%s'." % field_name, obj=self, id="sites.E001", ) ] if not field.many_to_ma
n errors def _check_field_name(self): field_name = self._get_field_name() try: field = self.model._meta.get_field(field_name) except FieldDoesNotExist: return [
{ "filepath": "django/contrib/sites/managers.py", "language": "python", "file_size": 1994, "cut_index": 537, "middle_length": 229 }
ignals from django.db.utils import ( DEFAULT_DB_ALIAS, DJANGO_VERSION_PICKLE_KEY, ConnectionHandler, ConnectionRouter, DatabaseError, DataError, Error, IntegrityError, InterfaceError, InternalError, NotSupportedError, OperationalError, ProgrammingError, ) from django....
ectionHandler() router = ConnectionRouter() # For backwards compatibility. Prefer connections['default'] instead. connection = ConnectionProxy(connections, DEFAULT_DB_ALIAS) # Register an event to reset saved queries when a Django request is started. d
or", "InternalError", "ProgrammingError", "DataError", "NotSupportedError", "Error", "InterfaceError", "OperationalError", "DEFAULT_DB_ALIAS", "DJANGO_VERSION_PICKLE_KEY", ] connections = Conn
{ "filepath": "django/db/__init__.py", "language": "python", "file_size": 1533, "cut_index": 537, "middle_length": 229 }
Error: import psycopg2 as Database except ImportError: raise ImproperlyConfigured("Error loading psycopg2 or psycopg module") @lru_cache def psycopg_version(): version = Database.__version__.split(" ", 1)[0] return get_version_tuple(version) if psycopg_version() < (2, 9, 9): raise Improperly...
pq import Format from .psycopg_any import get_adapters_template, register_tzloader TIMESTAMPTZ_OID = adapters.types["timestamptz"].oid else: import psycopg2.extensions import psycopg2.extras psycopg2.extensions.register_adapter(Safe
sycopg version 3.1.12 or newer is required; you have {Database.__version__}" ) from .psycopg_any import IsolationLevel, is_psycopg3 # NOQA isort:skip if is_psycopg3: from psycopg import adapters, sql from psycopg.
{ "filepath": "django/db/backends/postgresql/base.py", "language": "python", "file_size": 23830, "cut_index": 1331, "middle_length": 229 }
oroutinefunction 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 iscor...
") 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
response["X-Frame-Options"] = "DENY" return response else: def _view_wrapper(*args, **kwargs): response = view_func(*args, **kwargs) if response.get("X-Frame-Options
{ "filepath": "django/views/decorators/clickjacking.py", "language": "python", "file_size": 2549, "cut_index": 563, "middle_length": 229 }
se from django.utils.decorators import classonlymethod from django.utils.functional import classproperty from django.utils.log import log_response logger = logging.getLogger("django.request") class ContextMixin: """ A default context mixin that passes the keyword arguments received by get_context_data() ...
ames = [ "get", "post", "put", "patch", "delete", "head", "options", "trace", ] def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpf
kwargs.update(self.extra_context) return kwargs class View: """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """ http_method_n
{ "filepath": "django/views/generic/base.py", "language": "python", "file_size": 9546, "cut_index": 921, "middle_length": 229 }
ContextMixin, TemplateResponseMixin, View class SingleObjectMixin(ContextMixin): """ Provide the ability to retrieve a single object for further manipulation. """ model = None queryset = None slug_field = "slug" context_object_name = None slug_url_kwarg = "slug" pk_url_kwarg = "p...
: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filt
rgument in the URLconf. Subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None
{ "filepath": "django/views/generic/detail.py", "language": "python", "file_size": 7040, "cut_index": 716, "middle_length": 229 }
nslation 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 ...
elf.queryset if isinstance(queryset, QuerySet): queryset = queryset.all() elif self.model is not None: queryset = self.model._default_manager.all() else: raise ImproperlyConfigured(
ew. 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 = s
{ "filepath": "django/views/generic/list.py", "language": "python", "file_size": 8009, "cut_index": 716, "middle_length": 229 }
from asgiref.local import Local from django.core.signals import setting_changed from django.dispatch import Signal, receiver from .base import TaskResultStatus logger = logging.getLogger("django.tasks") task_enqueued = Signal() task_finished = Signal() task_started = Signal() @receiver(setting_changed) def clea...
logger.debug( "Task id=%s path=%s enqueued backend=%s", task_result.id, task_result.task.module_path, task_result.backend, ) @receiver(task_started) def log_task_started(sender, task_result, **kwargs): logger.i
ds._settings = task_backends.settings = ( task_backends.configure_settings(None) ) task_backends._connections = Local() @receiver(task_enqueued) def log_task_enqueued(sender, task_result, **kwargs):
{ "filepath": "django/tasks/signals.py", "language": "python", "file_size": 1690, "cut_index": 537, "middle_length": 229 }
ort sync_to_async from django.conf import settings from django.tasks import DEFAULT_TASK_QUEUE_NAME from django.tasks.base import ( DEFAULT_TASK_PRIORITY, TASK_MAX_PRIORITY, TASK_MIN_PRIORITY, Task, ) from django.tasks.exceptions import InvalidTask from django.utils import timezone from django.utils.in...
pports_get_result = False # Does the backend support executing Tasks in a given # priority order? supports_priority = False def __init__(self, alias, params): self.alias = alias self.queues = set(params.get("QUEUES", [DEFA
# attribute? supports_defer = False # Does the backend support coroutines to be enqueued? supports_async_task = False # Does the backend support results being retrieved (from any # thread/process)? su
{ "filepath": "django/tasks/backends/base.py", "language": "python", "file_size": 3796, "cut_index": 614, "middle_length": 229 }
from django.tasks.base import TaskResult, TaskResultStatus from django.tasks.exceptions import TaskResultDoesNotExist from django.tasks.signals import task_enqueued from django.utils import timezone from django.utils.crypto import get_random_string from .base import BaseTaskBackend class DummyBackend(BaseTaskBacke...
sk, args, kwargs): self.validate_task(task) result = TaskResult( task=task, id=get_random_string(32), status=TaskResultStatus.READY, enqueued_at=None, started_at=None,
= [] def _store_result(self, result): object.__setattr__(result, "enqueued_at", timezone.now()) self.results.append(result) task_enqueued.send(type(self), task_result=result) def enqueue(self, ta
{ "filepath": "django/tasks/backends/dummy.py", "language": "python", "file_size": 1957, "cut_index": 537, "middle_length": 229 }
_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...
bject 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._wrap
ion because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name class ExceptionCycleWarning(UserWarning): pass class CallableSettingWrapper: """ O
{ "filepath": "django/views/debug.py", "language": "python", "file_size": 26618, "cut_index": 1331, "middle_length": 229 }
.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 dj...
RL while setting the chosen language in the language 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 PO
e 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 U
{ "filepath": "django/views/i18n.py", "language": "python", "file_size": 9031, "cut_index": 716, "middle_length": 229 }
oroutinefunction from django.middleware.cache import CacheMiddleware from django.utils.cache import add_never_cache_headers, patch_cache_control from django.utils.decorators import decorator_from_middleware_with_args def cache_page(timeout, *, cache=None, key_prefix=None): """ Decorator for views that tries ...
from the response's Vary header will be taken into account on caching -- just like the middleware does. """ return decorator_from_middleware_with_args(CacheMiddleware)( page_timeout=timeout, cache_alias=cache, key_prefix
key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the get_current_site().domain, for example, as that is unique across a Django project. Additionally, all headers
{ "filepath": "django/views/decorators/cache.py", "language": "python", "file_size": 2815, "cut_index": 563, "middle_length": 229 }
oroutinefunction from django.middleware.csrf import CsrfViewMiddleware, get_token from django.utils.decorators import decorator_from_middleware csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly ...
csrf_token.__name__ = "requires_csrf_token" requires_csrf_token.__doc__ = """ Use this decorator on views that need a correct csrf_token available to RequestContext, but without the CSRF protection that csrf_protect enforces. """ class _EnsureCsrfCookie(
iddleware): # Behave like CsrfViewMiddleware but don't reject requests or log warnings. def _reject(self, request, reason): return None requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken) requires_
{ "filepath": "django/views/decorators/csrf.py", "language": "python", "file_size": 2317, "cut_index": 563, "middle_length": 229 }
are.http import ConditionalGetMiddleware from django.utils import timezone from django.utils.cache import get_conditional_response from django.utils.decorators import decorator_from_middleware from django.utils.http import http_date, quote_etag from django.utils.log import log_response conditional_page = decorator_fro...
ecorator(func): if iscoroutinefunction(func): @wraps(func) async def inner(request, *args, **kwargs): if request.method not in request_method_list: response = HttpResponseNotAllowed(reque
ttp_methods(["GET", "POST"]) def my_view(request): # I can assume now that only GET or POST requests make it this far # ... Note that request methods should be in uppercase. """ def d
{ "filepath": "django/views/decorators/http.py", "language": "python", "file_size": 6517, "cut_index": 716, "middle_length": 229 }
rt 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 Crea...
", "DayArchiveView", "TodayArchiveView", "DateDetailView", "DetailView", "FormView", "CreateView", "UpdateView", "DeleteView", "ListView", "GenericViewError", ] class GenericViewError(Exception): """A problem i
eView", "MonthArchiveView", "WeekArchiveView
{ "filepath": "django/views/generic/__init__.py", "language": "python", "file_size": 886, "cut_index": 547, "middle_length": 52 }
bles. """ 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: ...
te, 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: re
"""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, da
{ "filepath": "django/views/generic/dates.py", "language": "python", "file_size": 26921, "cut_index": 1331, "middle_length": 229 }
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 ...
"""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 k
lf): """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):
{ "filepath": "django/views/generic/edit.py", "language": "python", "file_size": 9039, "cut_index": 716, "middle_length": 229 }
o.contrib.sites.models from django.contrib.sites.models import _simple_domain_name_validator from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="Site", fields=[ ( ...
bose_name="domain name", validators=[_simple_domain_name_validator], ), ), ("name", models.CharField(max_length=50, verbose_name="display name")), ], option
primary_key=True, ), ), ( "domain", models.CharField( max_length=100, ver
{ "filepath": "django/contrib/sites/migrations/0001_initial.py", "language": "python", "file_size": 1361, "cut_index": 524, "middle_length": 229 }
en 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 ca...
FERER from django.template.context_processors import csp c = { "title": _("Forbidden"), "main": _("CSRF verification failed. Request aborted."), "reason": reason, "no_referer": reason == REASON_NO_REFERER, "
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_RE
{ "filepath": "django/views/csrf.py", "language": "python", "file_size": 3495, "cut_index": 614, "middle_length": 229 }
OULD 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.uti...
s" / 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 pa
urn 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 / "template
{ "filepath": "django/views/static.py", "language": "python", "file_size": 4053, "cut_index": 614, "middle_length": 229 }
ls import wraps from inspect import iscoroutinefunction def _make_csp_decorator(config_attr_name, config_attr_value): """General CSP override decorator factory.""" if not isinstance(config_attr_value, dict): raise TypeError("CSP config should be a mapping.") def decorator(view_func): @wr...
attr_name, config_attr_value) return response if iscoroutinefunction(view_func): return _wrapped_async_view return _wrapped_sync_view return decorator def csp_override(config): """Override the Content-Sec
config_attr_value) return response @wraps(view_func) def _wrapped_sync_view(request, *args, **kwargs): response = view_func(request, *args, **kwargs) setattr(response, config_
{ "filepath": "django/views/decorators/csp.py", "language": "python", "file_size": 1273, "cut_index": 524, "middle_length": 229 }
Error, TaskResult, TaskResultStatus from django.tasks.signals import task_enqueued, task_finished, task_started from django.utils import timezone from django.utils.crypto import get_random_string from django.utils.json import normalize_json from .base import BaseTaskBackend logger = logging.getLogger(__name__) clas...
enqueued_at", timezone.now()) task_enqueued.send(type(self), task_result=task_result) task = task_result.task task_start_time = timezone.now() object.__setattr__(task_result, "status", TaskResultStatus.RUNNING) obje
rker_id = get_random_string(32) def _execute_task(self, task_result): """ Execute the Task for the given TaskResult, mutating it with the outcome. """ object.__setattr__(task_result, "
{ "filepath": "django/tasks/backends/immediate.py", "language": "python", "file_size": 3377, "cut_index": 614, "middle_length": 229 }
s): """ 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', 'p...
or( "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_vari
iable names, in which case consider all variables are sensitive: @sensitive_variables() def my_function() ... """ if len(variables) == 1 and callable(variables[0]): raise TypeErr
{ "filepath": "django/views/decorators/debug.py", "language": "python", "file_size": 5250, "cut_index": 716, "middle_length": 229 }
unctools import wraps from inspect 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 i...
uest, *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
er(request, *args, **kwargs): response = await func(request, *args, **kwargs) patch_vary_headers(response, headers) return response else: def _view_wrapper(req
{ "filepath": "django/views/decorators/vary.py", "language": "python", "file_size": 1195, "cut_index": 518, "middle_length": 229 }
ort import_string DEFAULT_DB_ALIAS = "default" DJANGO_VERSION_PICKLE_KEY = "_django_version" class Error(Exception): pass class InterfaceError(Error): pass class DatabaseError(Error): pass class DataError(DatabaseError): pass class OperationalError(DatabaseError): pass class IntegrityEr...
rapper. It must have a Database attribute defining PEP-249 exceptions. """ self.wrapper = wrapper def __del__(self): del self.wrapper def __enter__(self): pass def __exit__(self, exc_type, exc_value,
eErrorWrapper: """ Context manager and decorator that reraises backend-specific database exceptions using Django's common wrappers. """ def __init__(self, wrapper): """ wrapper is a database w
{ "filepath": "django/db/utils.py", "language": "python", "file_size": 9350, "cut_index": 921, "middle_length": 229 }
self.db = db WRAP_ERROR_ATTRS = frozenset(["fetchone", "fetchmany", "fetchall", "nextset"]) APPS_NOT_READY_WARNING_MSG = ( "Accessing the database during app initialization is discouraged. To fix this " "warning, avoid executing queries in AppConfig.ready() or when your app " "mo...
def __exit__(self, type, value, traceback): # Close instead of passing through to avoid backend-specific behavior # (#17671). Catch errors liberally because errors in cleanup code # aren't useful. try: self.close
_database_errors(cursor_attr) else: return cursor_attr def __iter__(self): with self.db.wrap_database_errors: yield from self.cursor def __enter__(self): return self
{ "filepath": "django/db/backends/utils.py", "language": "python", "file_size": 11137, "cut_index": 921, "middle_length": 229 }
import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = "mysql" @classmethod def settings_to_cmd_args_env(cls, settings_dict, parameters): args = [cls.executable_name] env = None database = settings_dict["OPTIONS"].get( "database", ...
NS"].get("port", settings_dict["PORT"]) server_ca = settings_dict["OPTIONS"].get("ssl", {}).get("ca") client_cert = settings_dict["OPTIONS"].get("ssl", {}).get("cert") client_key = settings_dict["OPTIONS"].get("ssl", {}).get("key")
.get( "password", settings_dict["OPTIONS"].get("passwd", settings_dict["PASSWORD"]), ) host = settings_dict["OPTIONS"].get("host", settings_dict["HOST"]) port = settings_dict["OPTIO
{ "filepath": "django/db/backends/mysql/client.py", "language": "python", "file_size": 2988, "cut_index": 563, "middle_length": 229 }
ion from .client import DatabaseClient class DatabaseCreation(BaseDatabaseCreation): def sql_table_creation_suffix(self): suffix = [] test_settings = self.connection.settings_dict["TEST"] if test_settings["CHARSET"]: suffix.append("CHARACTER SET %s" % test_settings["CHARSET"])...
database exists" (1007) cancel tests. self.log("Got an error creating the test database: %s" % e) sys.exit(2) else: raise def _clone_test_db(self, suffix, verbosity, keepdb=False): so
meters, keepdb=False): try: super()._execute_create_test_db(cursor, parameters, keepdb) except Exception as e: if len(e.args) < 1 or e.args[0] != 1007: # All errors except "
{ "filepath": "django/db/backends/mysql/creation.py", "language": "python", "file_size": 4052, "cut_index": 614, "middle_length": 229 }
FieldInfo = namedtuple( "FieldInfo", [ *BaseFieldInfo._fields, "extra", "is_unsigned", "has_json_constraint", "comment", "data_type", ], ) InfoLine = namedtuple( "InfoLine", "col_name data_type max_len num_prec num_scale extra column_default " "c...
ME: "DateTimeField", FIELD_TYPE.DOUBLE: "FloatField", FIELD_TYPE.FLOAT: "FloatField", FIELD_TYPE.INT24: "IntegerField", FIELD_TYPE.JSON: "JSONField", FIELD_TYPE.LONG: "IntegerField", FIELD_TYPE.LONGLONG: "Big
FIELD_TYPE.BLOB: "TextField", FIELD_TYPE.CHAR: "CharField", FIELD_TYPE.DECIMAL: "DecimalField", FIELD_TYPE.NEWDECIMAL: "DecimalField", FIELD_TYPE.DATE: "DateField", FIELD_TYPE.DATETI
{ "filepath": "django/db/backends/mysql/introspection.py", "language": "python", "file_size": 14976, "cut_index": 921, "middle_length": 229 }
%(column)s %(type)s NOT NULL" sql_alter_column_type = "MODIFY %(column)s %(type)s%(collation)s%(comment)s" sql_alter_column_no_default_null = "ALTER COLUMN %(column)s SET DEFAULT NULL" sql_delete_unique = "ALTER TABLE %(table)s DROP INDEX %(name)s" sql_create_column_inline_fk = ( ", ADD CONSTRA...
(columns)s)" ) sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY" sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" sql_alter_table_comment = "ALTER TABLE %(table)s COMMENT = %(comment)s" sql_alter_c
lete_index = "DROP INDEX %(name)s ON %(table)s" sql_rename_index = "ALTER TABLE %(table)s RENAME INDEX %(old_name)s TO %(new_name)s" sql_create_pk = ( "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%
{ "filepath": "django/db/backends/mysql/schema.py", "language": "python", "file_size": 9938, "cut_index": 921, "middle_length": 229 }
from re import search as re_search from uuid import uuid4 from django.db.backends.utils import ( split_tzname_delta, typecast_time, typecast_timestamp, ) from django.utils import timezone from django.utils.duration import duration_microseconds from django.utils.version import PY314 if PY314: from uui...
me_cast_date ) create_deterministic_function( "django_datetime_cast_time", 3, _sqlite_datetime_cast_time ) create_deterministic_function( "django_datetime_extract", 4, _sqlite_datetime_extract ) create_deterministic_
_function("django_date_extract", 2, _sqlite_datetime_extract) create_deterministic_function("django_date_trunc", 4, _sqlite_date_trunc) create_deterministic_function( "django_datetime_cast_date", 3, _sqlite_dateti
{ "filepath": "django/db/backends/sqlite3/_functions.py", "language": "python", "file_size": 15731, "cut_index": 921, "middle_length": 229 }
class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.conn...
_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % (self._get_database_display_str(v
eturn test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is
{ "filepath": "django/db/backends/sqlite3/creation.py", "language": "python", "file_size": 6823, "cut_index": 716, "middle_length": 229 }
include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it use...
"bigint unsigned": "PositiveBigIntegerField", "decimal": "DecimalField", "real": "FloatField", "text": "TextField", "char": "CharField", "varchar": "CharField", "blob": "BinaryField", "date": "
PositiveSmallIntegerField", "smallinteger": "SmallIntegerField", "int": "IntegerField", "integer": "IntegerField", "bigint": "BigIntegerField", "integer unsigned": "PositiveIntegerField",
{ "filepath": "django/db/backends/sqlite3/introspection.py", "language": "python", "file_size": 18046, "cut_index": 1331, "middle_length": 229 }
_unique = "DROP INDEX %(name)s" sql_alter_table_comment = None sql_alter_column_comment = None def __enter__(self): # Some SQLite schema alterations need foreign key constraints to be # disabled. Enforce it here for the duration of the schema edition. if not self.connection.disable_...
return super().__enter__() def __exit__(self, exc_type, exc_value, traceback): self.connection.check_constraints() super().__exit__(exc_type, exc_value, traceback) self.connection.enable_constraint_checking() def q
o disable them " "before entering a transaction.atomic() context because " "SQLite does not support disabling them in the middle of " "a multi-statement transaction." )
{ "filepath": "django/db/backends/sqlite3/schema.py", "language": "python", "file_size": 20358, "cut_index": 1331, "middle_length": 229 }
Forbidden, HttpResponseNotFound, HttpResponseServerError, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = "404.html" ERROR_403_TEMPLATE_NAME = "403.html" ERROR_400_TEMPLATE_NAME = "400.html" ERROR...
n, template_name=ERROR_404_TEMPLATE_NAME): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent
l> """ # These views can be called when CsrfViewMiddleware.process_view() not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. @requires_csrf_token def page_not_found(request, exceptio
{ "filepath": "django/views/defaults.py", "language": "python", "file_size": 4718, "cut_index": 614, "middle_length": 229 }
on(using=None): """ Get a database connection by name, or the default database connection if no name is provided. This is a private API. """ if using is None: using = DEFAULT_DB_ALIAS return connections[using] def get_autocommit(using=None): """Get the autocommit status of the conn...
savepoint(using=None): warnings.warn( "savepoint() is deprecated. Use savepoint_create() instead.", category=RemovedInDjango70Warning, skip_file_prefixes=django_file_prefixes(), ) return savepoint_create(using=using) d
g).set_autocommit(autocommit) def commit(using=None): """Commit a transaction.""" get_connection(using).commit() def rollback(using=None): """Roll back a transaction.""" get_connection(using).rollback() def
{ "filepath": "django/db/transaction.py", "language": "python", "file_size": 12872, "cut_index": 921, "middle_length": 229 }
y from django.utils.regex_helper import _lazy_re_compile try: import MySQLdb as Database except ImportError as err: raise ImproperlyConfigured( "Error loading MySQLdb module.\nDid you install mysqlclient?" ) from err from MySQLdb.constants import CLIENT, FIELD_TYPE from MySQLdb.converters import c...
ersion < (2, 2, 1): raise ImproperlyConfigured( "mysqlclient 2.2.1 or newer is required; you have %s." % Database.__version__ ) # MySQLdb returns TIME columns as timedelta -- they are more like timedelta in # terms of actual behavior as t
atabaseFeatures from .introspection import DatabaseIntrospection from .operations import DatabaseOperations from .schema import DatabaseSchemaEditor from .validation import DatabaseValidation version = Database.version_info if v
{ "filepath": "django/db/backends/mysql/base.py", "language": "python", "file_size": 16315, "cut_index": 921, "middle_length": 229 }
alue = () related_fields_match_type = True # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME. allow_sliced_subqueries_with_in = False has_select_for_update = True has_select_for_update_nowait = True has_select_for_update_skip_locked = True supports_forward_references = False ...
_compound = True supports_index_on_text_field = False supports_over_clause = True supports_frame_range_fixed_distance = True supports_update_conflicts = True supports_default_in_bit_aggregations = False can_rename_index = True d
tions = False can_clone_databases = True supports_aggregate_order_by_clause = True supports_comments = True supports_comments_inline = True supports_temporal_subtraction = True supports_slicing_ordering_in
{ "filepath": "django/db/backends/mysql/features.py", "language": "python", "file_size": 8405, "cut_index": 716, "middle_length": 229 }
rom django.utils.version import get_docs_version class DatabaseValidation(BaseDatabaseValidation): def check(self, **kwargs): issues = super().check(**kwargs) issues.extend(self._check_sql_mode(**kwargs)) return issues def _check_sql_mode(self, **kwargs): if not ( ...
"%s, such as data truncation upon insertion, by " "escalating warnings into errors. It is strongly " "recommended you activate it. See: " "https://docs.djangoproject.com/en/%s/ref/da
ase connection '%s'" % (self.connection.display_name, self.connection.alias), hint=( "%s's Strict Mode fixes many data integrity problems in "
{ "filepath": "django/db/backends/mysql/validation.py", "language": "python", "file_size": 3093, "cut_index": 614, "middle_length": 229 }
l import cached_property from django.utils.version import PY314 from .base import Database class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (3, 37) test_db_allows_multiple_connections = False supports_unspecified_pk = True supports_timezones = False supports_transactions =...
False can_defer_constraint_checks = True supports_over_clause = True supports_frame_range_fixed_distance = True supports_frame_exclusion = True supports_aggregate_filter_clause = True supports_aggregate_order_by_clause = Database.s
traction = True ignores_table_name_case = True supports_cast_with_precision = False time_cast_precision = 3 can_release_savepoints = True has_case_insensitive_like = True supports_parentheses_in_compound =
{ "filepath": "django/db/backends/sqlite3/features.py", "language": "python", "file_size": 7086, "cut_index": 716, "middle_length": 229 }
d functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import os import posixpath from django.conf import settings from django.contrib.staticfiles import finders from django.http import Http404 from django.views import static def serv...
""" if not settings.DEBUG and not insecure: raise Http404 normalized_path = posixpath.normpath(path).lstrip("/") absolute_path = finders.find(normalized_path) if not absolute_path: if path.endswith("/") or path == "":
se, put a URL pattern such as:: from django.contrib.staticfiles import views path('<path:path>', views.serve) in your URLconf. It uses the django.views.static.serve() view to serve the found files.
{ "filepath": "django/contrib/staticfiles/views.py", "language": "python", "file_size": 1262, "cut_index": 524, "middle_length": 229 }
Col from django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler from django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler from django.db.models.sql.compiler import SQLInsertCompiler from django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler __all__ =...
fficient query # plan than when using a subquery. where, having, qualify = self.query.where.split_having_qualify( must_group_by=self.query.group_by is not None ) if self.single_alias or having or qualify:
self): # Prefer the non-standard DELETE FROM syntax over the SQL generated by # the SQLDeleteCompiler's default implementation when multiple tables # are involved since MySQL/MariaDB will generate a more e
{ "filepath": "django/db/backends/mysql/compiler.py", "language": "python", "file_size": 3047, "cut_index": 614, "middle_length": 229 }
mport async_unsafe from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.regex_helper import _lazy_re_compile from ._functions import register as register_functions from .client import DatabaseClient from .creation import DatabaseCreation from .features import DatabaseFeatures fro...
umn(data): if data["max_length"] is None: return "varchar" return "varchar(%(max_length)s)" % data Database.register_converter("bool", b"1".__eq__) Database.register_converter("date", decoder(parse_date)) Database.register_converter("time
Python's sqlite3 interface to a regular string. """ return lambda s: conv_func(s.decode()) def adapt_date(val): return val.isoformat() def adapt_datetime(val): return val.isoformat(" ") def _get_varchar_col
{ "filepath": "django/db/backends/sqlite3/base.py", "language": "python", "file_size": 15095, "cut_index": 921, "middle_length": 229 }
1615), } cast_data_types = { "AutoField": "signed integer", "BigAutoField": "signed integer", "SmallAutoField": "signed integer", "CharField": "char(%(max_length)s)", "DecimalField": "decimal(%(max_digits)s, %(decimal_places)s)", "TextField": "char", "Inte...
XTRACT format cannot be passed in parameters. _extract_format_re = _lazy_re_compile(r"[A-Z_]+") def date_extract_sql(self, lookup_type, sql, params): # https://dev.mysql.com/doc/mysql/en/date-and-time-functions.html if lookup_type
eIntegerField": "unsigned integer", "PositiveSmallIntegerField": "unsigned integer", "DurationField": "signed integer", } cast_char_field_without_max_length = "char" explain_prefix = "EXPLAIN" # E
{ "filepath": "django/db/backends/mysql/operations.py", "language": "python", "file_size": 17469, "cut_index": 1331, "middle_length": 229 }
teger_field_ranges = { "SmallIntegerField": (-32768, 32767), "IntegerField": (-2147483648, 2147483647), "BigIntegerField": (-9223372036854775808, 9223372036854775807), "PositiveBigIntegerField": (0, 9223372036854775807), "PositiveSmallIntegerField": (0, 32767), "PositiveI...
type to use for the Cast() function, if different from # DatabaseWrapper.data_types. cast_data_types = {} # CharField data type if the max_length argument isn't provided. cast_char_field_without_max_length = None # Start and end point
} set_operators = { "union": "UNION", "intersection": "INTERSECT", "difference": "EXCEPT", } # Mapping of Field.get_internal_type() (typically the model field's class # name) to the data
{ "filepath": "django/db/backends/base/operations.py", "language": "python", "file_size": 33304, "cut_index": 1331, "middle_length": 229 }
connection, template="SHA2(%%(expressions)s, %s)" % self.function[3:], **extra_context, ) class OracleHashMixin: def as_oracle(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template=( ...
nction)s'), 'hex')", function=self.function.lower(), **extra_context, ) class Chr(Transform): function = "CHR" lookup_name = "chr" output_field = CharField() def as_mysql(self, compiler, connection, **extr
class PostgreSQLSHAMixin: def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template="ENCODE(DIGEST(%(expressions)s, '%(fu
{ "filepath": "django/db/models/functions/text.py", "language": "python", "file_size": 11538, "cut_index": 921, "middle_length": 229 }
ion import BaseDatabaseCreation from django.db.backends.postgresql.psycopg_any import errors from django.db.backends.utils import strip_quotes class DatabaseCreation(BaseDatabaseCreation): def _quote_name(self, name): return self.connection.ops.quote_name(name) def _get_database_create_suffix(self, e...
raise ImproperlyConfigured( "PostgreSQL does not support collation setting at database " "creation time." ) return self._get_database_create_suffix( encoding=test_settings["CHARSET
self._quote_name(template)) return suffix and "WITH" + suffix def sql_table_creation_suffix(self): test_settings = self.connection.settings_dict["TEST"] if test_settings.get("COLLATION") is not None:
{ "filepath": "django/db/backends/postgresql/creation.py", "language": "python", "file_size": 3886, "cut_index": 614, "middle_length": 229 }
ango.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (15,) allows_group_by_selected_pks = True can_return_columns_from_insert = True can_return_rows_from_bulk_insert = True can_return_rows_from_update = True has_real_datatype = T...
spaces = True supports_transactions = True can_introspect_materialized_views = True can_distinct_on_fields = True can_rollback_ddl = True schema_editor_uses_clientside_param_binding = True supports_combined_alters = True nulls_o
t_for_update_nowait = True has_select_for_update_of = True has_select_for_update_skip_locked = True has_select_for_no_key_update = True can_release_savepoints = True supports_comments = True supports_table
{ "filepath": "django/db/backends/postgresql/features.py", "language": "python", "file_size": 6960, "cut_index": 716, "middle_length": 229 }
.db.models.constants import OnConflict from django.db.models.functions import Cast from django.utils.regex_helper import _lazy_re_compile @lru_cache def get_json_dumps(encoder): if encoder is None: return json.dumps return partial(json.dumps, cls=encoder) class DatabaseOperations(BaseDatabaseOperati...
BOSE", "WAL", ] ) cast_data_types = { "AutoField": "integer", "BigAutoField": "bigint", "SmallAutoField": "smallint", } if is_psycopg3: from psycopg.types import numeric integerf
[ "ANALYZE", "BUFFERS", "COSTS", "GENERIC_PLAN", "MEMORY", "SETTINGS", "SERIALIZE", "SUMMARY", "TIMING", "VER
{ "filepath": "django/db/backends/postgresql/operations.py", "language": "python", "file_size": 15521, "cut_index": 921, "middle_length": 229 }
efault = ( "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL" "; SET CONSTRAINTS ALL IMMEDIATE" ) sql_alter_sequence_type = "ALTER SEQUENCE IF EXISTS %(sequence)s AS %(type)s" sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE" sql_create_index = (...
s" # Setting the constraint to IMMEDIATE to allow changing data in the same # transaction. sql_create_column_inline_fk = ( "CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(on_delete_db)s" "%(deferrable)s; SET CONSTR
%(name)s ON %(table)s%(using)s " "(%(columns)s)%(include)s%(extra)s%(condition)s" ) sql_delete_index = "DROP INDEX IF EXISTS %(name)s" sql_delete_index_concurrently = "DROP INDEX CONCURRENTLY IF EXISTS %(name)
{ "filepath": "django/db/backends/postgresql/schema.py", "language": "python", "file_size": 14772, "cut_index": 921, "middle_length": 229 }
# Cygwin requires some special voodoo to set the environment variables # properly so that Oracle will see them. if platform.system().upper().startswith("CYGWIN"): try: import ctypes except ImportError as e: raise ImproperlyConfigured( "Error loading ct...
ment. ("NLS_LANG", ".AL32UTF8"), # This prevents Unicode from getting mangled by getting encoded into # the potentially non-Unicode database character set. ("ORA_NCHAR_LITERAL_REPLACE", "TRUE"), ] ) # Some of these imp
name, value in environ: kernel32.SetEnvironmentVariableA(name, value) else: os.environ.update(environ) _setup_environment( [ # Oracle takes client-side character set encoding from the environ
{ "filepath": "django/db/backends/oracle/base.py", "language": "python", "file_size": 25945, "cut_index": 1331, "middle_length": 229 }
# Although GROUP BY select index is supported by Oracle 23c+, it requires # GROUP_BY_POSITION_ENABLED to be enabled to avoid backward compatibility # issues. Introspection of this settings is not straightforward. allows_group_by_select_index = False interprets_empty_strings_as_nulls = True has_se...
supports_transactions = True supports_timezones = False has_native_duration_field = True can_defer_constraint_checks = True supports_partially_nullable_unique_constraints = False supports_deferrable_unique_constraints = True trunca
eturn_columns_from_insert = True can_return_rows_from_update = True supports_subqueries_in_group_by = False ignores_unnecessary_order_by_in_subqueries = False supports_tuple_comparison_against_subquery = False
{ "filepath": "django/db/backends/oracle/features.py", "language": "python", "file_size": 10084, "cut_index": 921, "middle_length": 229 }
mment"] ) TableInfo = namedtuple("TableInfo", [*BaseTableInfo._fields, "comment"]) class DatabaseIntrospection(BaseDatabaseIntrospection): cache_bust_counter = 1 # Maps type objects to Django Field types. data_types_reverse = { oracledb.DB_TYPE_DATE: "DateField", oracledb.DB_TYPE_BINARY_D...
_TIMESTAMP: "DateTimeField", oracledb.DB_TYPE_VARCHAR: "CharField", } def get_field_type(self, data_type, description): if data_type == oracledb.NUMBER: precision, scale = description[4:6] if scale == 0:
"DurationField", oracledb.DB_TYPE_NCHAR: "CharField", oracledb.DB_TYPE_NCLOB: "TextField", oracledb.DB_TYPE_NVARCHAR: "CharField", oracledb.DB_TYPE_NUMBER: "DecimalField", oracledb.DB_TYPE
{ "filepath": "django/db/backends/oracle/introspection.py", "language": "python", "file_size": 15917, "cut_index": 921, "middle_length": 229 }
olumn)s %(type)s%(collation)s" sql_alter_column_null = "MODIFY %(column)s NULL" sql_alter_column_not_null = "MODIFY %(column)s NOT NULL" sql_alter_column_default = "MODIFY %(column)s DEFAULT %(default)s" sql_alter_column_no_default = "MODIFY %(column)s DEFAULT NULL" sql_alter_column_no_default_null ...
time, datetime.datetime)): return "'%s'" % value elif isinstance(value, datetime.timedelta): return "'%s'" % duration_iso_string(value) elif isinstance(value, str): return "'%s'" % value.replace("'", "''"
elete_table = "DROP TABLE %(table)s CASCADE CONSTRAINTS" sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" def quote_value(self, value): if isinstance(value, (datetime.date, datetime.
{ "filepath": "django/db/backends/oracle/schema.py", "language": "python", "file_size": 10849, "cut_index": 921, "middle_length": 229 }
import checks from django.db.backends.base.validation import BaseDatabaseValidation class DatabaseValidation(BaseDatabaseValidation): def check_field_type(self, field, field_type): """Oracle doesn't support a database index on some data types.""" errors = [] if field.db_index and field_typ...
t=( "An index won't be created. Silence this warning if " "you don't care about it." ), obj=field, id="fields.W162", ) )
% field_type, hin
{ "filepath": "django/db/backends/oracle/validation.py", "language": "python", "file_size": 860, "cut_index": 529, "middle_length": 52 }
fines the reference interface.""" def references_table(self, table): """ Return whether or not this instance references the specified table. """ return False def references_column(self, table, column): """ Return whether or not this instance references the speci...
e, old_column, new_column): """ Rename all references to the old_column to the new_column. """ pass def __repr__(self): return "<%s %r>" % (self.__class__.__name__, str(self)) def __str__(self): rai
return False def rename_table_references(self, old_table, new_table): """ Rename all references to the old_name to the new_table. """ pass def rename_column_references(self, tabl
{ "filepath": "django/db/backends/ddl_references.py", "language": "python", "file_size": 8619, "cut_index": 716, "middle_length": 229 }
import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = "psql" @classmethod def settings_to_cmd_args_env(cls, settings_dict, parameters): args = [cls.executable_name] options = settings_dict["OPTIONS"] host = settings_dict.get("HOST") port = ...
f not dbname and not service: # Connect to the default 'postgres' db. dbname = "postgres" if user: args += ["-U", user] if host: args += ["-h", host] if port: args += ["-p"
sfile") service = options.get("service") sslmode = options.get("sslmode") sslrootcert = options.get("sslrootcert") sslcert = options.get("sslcert") sslkey = options.get("sslkey") i
{ "filepath": "django/db/backends/postgresql/client.py", "language": "python", "file_size": 2044, "cut_index": 563, "middle_length": 229 }
this if the database ENGINE setting is empty (None or empty string). Each of these API functions, except connection.close(), raise ImproperlyConfigured. """ from django.core.exceptions import ImproperlyConfigured from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.base.client import ...
"Please supply the ENGINE value. Check " "settings documentation for more details." ) def ignore(*args, **kwargs): pass class DatabaseOperations(BaseDatabaseOperations): quote_name = complain class DatabaseClient(BaseDataba
erations import BaseDatabaseOperations from django.db.backends.dummy.features import DummyDatabaseFeatures def complain(*args, **kwargs): raise ImproperlyConfigured( "settings.DATABASES is improperly configured. "
{ "filepath": "django/db/backends/dummy/base.py", "language": "python", "file_size": 2217, "cut_index": 563, "middle_length": 229 }
ld? All core backends implement this correctly, but other # databases such as SQL Server do not. supports_nullable_unique_constraints = True # Does the backend allow inserting duplicate rows when a unique_together # constraint exists and some fields are nullable but not all of them? supports_partia...
can_return_rows_from_bulk_insert = False can_return_rows_from_update = False has_bulk_insert = True uses_savepoints = True can_release_savepoints = False # If True, don't use integer foreign keys referring to, e.g., positive # int
ique_constraints = False # Does the backend support initially deferrable unique constraints? supports_deferrable_unique_constraints = False can_use_chunked_reads = True can_return_columns_from_insert = False
{ "filepath": "django/db/backends/base/features.py", "language": "python", "file_size": 18285, "cut_index": 1331, "middle_length": 229 }
__" RAN_DB_VERSION_CHECK = set() logger = logging.getLogger("django.db.backends.base") class BaseDatabaseWrapper: """Represent a database connection.""" # Mapping of Field objects to their column types. data_types = {} # Mapping of Field objects to their SQL suffix such as AUTOINCREMENT. data_ty...
Validation queries_limit = 9000 def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS): # Connection related attributes. # The underlying database connection. self.connection = None # `settings_dict` should be a
chemaEditorClass = None # Classes instantiated in __init__(). client_class = None creation_class = None features_class = None introspection_class = None ops_class = None validation_class = BaseDatabase
{ "filepath": "django/db/backends/base/base.py", "language": "python", "file_size": 28546, "cut_index": 1331, "middle_length": 229 }
, Index FieldInfo = namedtuple("FieldInfo", [*BaseFieldInfo._fields, "is_autofield", "comment"]) TableInfo = namedtuple("TableInfo", [*BaseTableInfo._fields, "comment"]) class DatabaseIntrospection(BaseDatabaseIntrospection): # Maps type codes to Django Field types. data_types_reverse = { 16: "Boolea...
meField", 1186: "DurationField", 1266: "TimeField", 1700: "DecimalField", 2950: "UUIDField", 3802: "JSONField", } # A hook for subclasses. index_default_access_method = "btree" ignored_tables = []
"FloatField", 869: "GenericIPAddressField", 1042: "CharField", # blank-padded 1043: "CharField", 1082: "DateField", 1083: "TimeField", 1114: "DateTimeField", 1184: "DateTi
{ "filepath": "django/db/backends/postgresql/introspection.py", "language": "python", "file_size": 12717, "cut_index": 921, "middle_length": 229 }
.connection.alias] user = settings_dict.get("SAVED_USER") or settings_dict["USER"] password = settings_dict.get("SAVED_PASSWORD") or settings_dict["PASSWORD"] settings_dict = {**settings_dict, "USER": user, "PASSWORD": password} DatabaseWrapper = type(self.connection) return Data...
) except Exception as e: if "ORA-01543" not in str(e): # All errors except "tablespace already exists" cancel # tests self.log("Go
th self._maindb_connection.cursor() as cursor: if self._test_database_create(): try: self._execute_test_db_creation( cursor, parameters, verbosity, keepdb
{ "filepath": "django/db/backends/oracle/creation.py", "language": "python", "file_size": 21081, "cut_index": 1331, "middle_length": 229 }
): # Oracle uses NUMBER(5), NUMBER(11), and NUMBER(19) for integer fields. # SmallIntegerField uses NUMBER(11) instead of NUMBER(5), which is used by # SmallAutoField, to preserve backward compatibility. integer_field_ranges = { "SmallIntegerField": (-99999999999, 99999999999), "IntegerF...
999999999999), } set_operators = {**BaseDatabaseOperations.set_operators, "difference": "MINUS"} # TODO: colorize this SQL code with style.SQL_KEYWORD(), etc. _sequence_reset_sql = """ DECLARE table_value integer; seq_value integer
ntegerField": (0, 99999999999), "PositiveIntegerField": (0, 99999999999), "SmallAutoField": (-99999, 99999), "AutoField": (-99999999999, 99999999999), "BigAutoField": (-9999999999999999999, 9999999
{ "filepath": "django/db/backends/oracle/operations.py", "language": "python", "file_size": 29468, "cut_index": 1331, "middle_length": 229 }
sions import Col from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.functional import cached_property from .base import Database UNSUPPORTED_DATETIME_AGGREGATES = ( models.Sum, models.Avg, models.Variance, models.StdDev, ) DATE...
jsonfield_datatype_values = frozenset(["null", "false", "true"]) def check_expression_support(self, expression): if isinstance(expression, UNSUPPORTED_DATETIME_AGGREGATES): for expr in expression.get_source_expressions():
= { "DateField": "TEXT", "DateTimeField": "TEXT", } explain_prefix = "EXPLAIN QUERY PLAN" # List of datatypes to that cannot be extracted with JSON_EXTRACT() on # SQLite. Use JSON_TYPE() instead.
{ "filepath": "django/db/backends/sqlite3/operations.py", "language": "python", "file_size": 15892, "cut_index": 921, "middle_length": 229 }
late backend-specific methods for opening a client shell.""" # This should be a string representing the name of the executable # (e.g., "psql"). Subclasses must override this. executable_name = None def __init__(self, connection): # connection is an instance of BaseDatabaseWrapper. sel...
ust provide a " "settings_to_cmd_args_env() method or override a runshell()." ) def runshell(self, parameters): args, env = self.settings_to_cmd_args_env( self.connection.settings_dict, parameters )
ror( "subclasses of BaseDatabaseClient m
{ "filepath": "django/db/backends/base/client.py", "language": "python", "file_size": 989, "cut_index": 582, "middle_length": 52 }
"TableInfo", ["name", "type"]) # Structure returned by the DB-API cursor.description interface (PEP 249) FieldInfo = namedtuple( "FieldInfo", "name type_code display_size internal_size precision scale null_ok " "default collation", ) class BaseDatabaseIntrospection: """Encapsulate backend-specific in...
pe(self, data_type, description): """ Hook for a database backend to use the cursor description to match a Django field type to a database column. For Oracle, the column data_type on its own is insufficient to disti
ET NULL": DB_SET_NULL, # DB_RESTRICT - "RESTRICT" is not supported. } def __init__(self, connection): self.connection = connection def __del__(self): del self.connection def get_field_ty
{ "filepath": "django/db/backends/base/introspection.py", "language": "python", "file_size": 8317, "cut_index": 716, "middle_length": 229 }
Level, adapt, adapters, errors, pq, sql from psycopg.postgres import types from psycopg.types.json import Jsonb from psycopg.types.range import Range, RangeDumper from psycopg.types.string import TextLoader Inet = ipaddress.ip_address DateRange = DateTimeRange = DateTimeTZRange = NumericRange ...
oader(adapt.Loader): """ Load a PostgreSQL timestamptz using the a specific timezone. The timezone can be None too, in which case it will be chopped. """ timezone = None def __init__(self, oid, context):
.oid, pq.Format.TEXT, ) def mogrify(sql, params, connection): with connection.cursor() as cursor: return ClientCursor(cursor.connection).mogrify(sql, params) # Adapters. class BaseTzL
{ "filepath": "django/db/backends/postgresql/psycopg_any.py", "language": "python", "file_size": 4074, "cut_index": 614, "middle_length": 229 }
import shutil from django.db.backends.base.client import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = "sqlplus" wrapper_name = "rlwrap" @staticmethod def connect_string(settings_dict): from django.db.backends.oracle.utils import dsn return '%s/"%s"@...
: args = [cls.executable_name, "-L", cls.connect_string(settings_dict)] wrapper_path = shutil.which(cls.wrapper_name) if wrapper_path: args = [wrapper_path, *args] args.extend(parameters) return args, Non
t, parameters)
{ "filepath": "django/db/backends/oracle/client.py", "language": "python", "file_size": 784, "cut_index": 512, "middle_length": 14 }
t:skip SQLAggregateCompiler, SQLCompiler, SQLDeleteCompiler, SQLInsertCompiler as BaseSQLInsertCompiler, SQLUpdateCompiler, ) __all__ = [ "SQLAggregateCompiler", "SQLCompiler", "SQLDeleteCompiler", "SQLInsertCompiler", "SQLUpdateCompiler", ] class InsertUnnest(list): """ ...
the query. if ( # The optimization is not worth doing if there is a single # row as it will result in the same number of placeholders. len(value_rows) <= 1 # Lack of fields denote the usage of the DE
", ".join(self) class SQLInsertCompiler(BaseSQLInsertCompiler): def assemble_as_sql(self, fields, value_rows): # Specialize bulk-insertion of literal values through UNNEST to # reduce the time spent planning
{ "filepath": "django/db/backends/postgresql/compiler.py", "language": "python", "file_size": 2478, "cut_index": 563, "middle_length": 229 }
atabase class BoundVar: """ A late-binding cursor variable that can be passed to Cursor.execute as a parameter, in order to receive the id of the row created by an insert statement. """ types = { "AutoField": int, "BigAutoField": int, "SmallAutoField": int, "In...
def __init__(self, field): internal_type = getattr(field, "target_field", field).get_internal_type() self.db_type = self.types.get(internal_type, str) self.bound_param = None def bind_parameter(self, cursor): self
eld": int, "BooleanField": int, "FloatField": Database.DB_TYPE_BINARY_DOUBLE, "DateTimeField": Database.DB_TYPE_TIMESTAMP, "DateField": datetime.date, "DecimalField": decimal.Decimal, }
{ "filepath": "django/db/backends/oracle/utils.py", "language": "python", "file_size": 2752, "cut_index": 563, "middle_length": 229 }
port DecimalField, DurationField, Func class IntervalToSeconds(Func): function = "" template = """ EXTRACT(day from %(expressions)s) * 86400 + EXTRACT(hour from %(expressions)s) * 3600 + EXTRACT(minute from %(expressions)s) * 60 + EXTRACT(second from %(expressions)s) """ def __init__(...
on = "NUMTODSINTERVAL" template = "%(function)s(%(expressions)s, 'SECOND')" def __init__(self, expression, *, output_field=None, **extra): super().__init__( expression, output_field=output_field or DurationField(), **extra
c): functi
{ "filepath": "django/db/backends/oracle/functions.py", "language": "python", "file_size": 812, "cut_index": 536, "middle_length": 14 }
ss BaseDatabaseValidation: """Encapsulate backend-specific validation.""" def __init__(self, connection): self.connection = connection def __del__(self): del self.connection def check(self, **kwargs): return [] def check_field(self, field, **kwargs): errors = [] ...
for feature in field.model._meta.required_db_features ) if db_supports_all_required_features: field_type = field.db_type(self.connection) # Ignore non-concrete fields. if fie
getattr(field, "remote_field", None) ): # Ignore fields with unsupported features. db_supports_all_required_features = all( getattr(self.connection.features, feature, False)
{ "filepath": "django/db/backends/base/validation.py", "language": "python", "file_size": 1119, "cut_index": 515, "middle_length": 229 }
m django.db.models.functions.mixins import ( FixDurationInputMixin, NumericOutputFieldMixin, ) __all__ = [ "Aggregate", "AnyValue", "Avg", "BitAnd", "BitOr", "BitXor", "Count", "Max", "Min", "StdDev", "StringAgg", "Sum", "Variance", ] class AggregateFilter(...
xt) except FullResultSet: return "", () @property def condition(self): return self.source_expressions[0] def __str__(self): return self.arg_joiner.join(str(arg) for arg in self.source_expressions) class A
_clause: raise NotSupportedError( "Aggregate filter clauses are not supported on this database backend." ) try: return super().as_sql(compiler, connection, **extra_conte
{ "filepath": "django/db/models/aggregates.py", "language": "python", "file_size": 15427, "cut_index": 921, "middle_length": 229 }