prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
eString, mark_safe from django.utils.text import capfirst from django.utils.translation import gettext as _ from .base import InclusionAdminNode register = Library() @register.simple_tag def paginator_number(cl, i): """ Generate an individual page index link in a paginated list. """ if i == cl.pagin...
te the series of links to the pages in a paginated list. """ pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page page_range = ( cl.paginator.get_elided_page_range(cl.page_num) if pagination_required else []
', i, ) else: return format_html( '<a role="button" href="{}">{}</a> ', cl.get_query_string({PAGE_VAR: i}), i, ) def pagination(cl): """ Genera
{ "filepath": "django/contrib/admin/templatetags/admin_list.py", "language": "python", "file_size": 19476, "cut_index": 1331, "middle_length": 229 }
, ) from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist from django.db import connections, models, router, transaction from django.utils.encoding import force_str # LayerMapping exceptions. class LayerMapError(Exception): pass class InvalidString(LayerMapError): pass class InvalidDeci...
ype("Point25D").num: OGRGeomType("MultiPoint25D"), OGRGeomType("LineString25D").num: OGRGeomType("MultiLineString25D"), OGRGeomType("Polygon25D").num: OGRGeomType("MultiPolygon25D"), } # Acceptable Django field types and correspondi
ango Models." # Acceptable 'base' types for a multi-geometry type. MULTI_TYPES = { 1: OGRGeomType("MultiPoint"), 2: OGRGeomType("MultiLineString"), 3: OGRGeomType("MultiPolygon"), OGRGeomT
{ "filepath": "django/contrib/gis/utils/layermapping.py", "language": "python", "file_size": 29093, "cut_index": 1331, "middle_length": 229 }
DataSource from django.contrib.gis.gdal.field import ( OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString, OFTTime, ) def mapping(data_source, geom_name="geom", layer_key=0, multi_geom=False): """ Given a DataSource, generate a dictionary that may be used for in...
a_source, str): # Instantiating the DataSource from the string. data_source = DataSource(data_source) elif isinstance(data_source, DataSource): pass else: raise TypeError( "Data source parameter must be a
aSource to use; defaults to 0 (the first layer). May be an integer index or a string identifier for the layer. `multi_geom` => Boolean (default: False) - specify as multigeometry. """ if isinstance(dat
{ "filepath": "django/contrib/gis/utils/ogrinspect.py", "language": "python", "file_size": 9157, "cut_index": 716, "middle_length": 229 }
pps from django.conf import settings from django.contrib.redirects.models import Redirect from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponseGone, HttpResponsePermanentRedirect from django.utils.deprecation import Middl...
iddleware when " "django.contrib.sites is not installed." ) super().__init__(get_response) def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if r
rect_class = HttpResponsePermanentRedirect def __init__(self, get_response): if not apps.is_installed("django.contrib.sites"): raise ImproperlyConfigured( "You cannot use RedirectFallbackM
{ "filepath": "django/contrib/redirects/middleware.py", "language": "python", "file_size": 1921, "cut_index": 537, "middle_length": 229 }
gration(migrations.Migration): dependencies = [ ("sites", "0001_initial"), ] operations = [ migrations.CreateModel( name="Redirect", fields=[ ( "id", models.AutoField( verbose_name="ID", ...
), ( "old_path", models.CharField( help_text=( "This should be an absolute path, excluding the domain " "name. Ex
"site", models.ForeignKey( to="sites.Site", on_delete=models.CASCADE, verbose_name="site", ),
{ "filepath": "django/contrib/redirects/migrations/0001_initial.py", "language": "python", "file_size": 2101, "cut_index": 563, "middle_length": 229 }
contrib.admindocs import views from django.urls import path, re_path urlpatterns = [ path( "", views.BaseAdminDocsView.as_view(template_name="admin_doc/index.html"), name="django-admindocs-docroot", ), path( "bookmarklets/", views.BookmarkletsView.as_view(), ...
"views/<view>/", views.ViewDetailView.as_view(), name="django-admindocs-views-detail", ), path( "models/", views.ModelIndexView.as_view(), name="django-admindocs-models-index", ), re_path(
views.TemplateFilterIndexView.as_view(), name="django-admindocs-filters", ), path( "views/", views.ViewIndexView.as_view(), name="django-admindocs-views-index", ), path(
{ "filepath": "django/contrib/admindocs/urls.py", "language": "python", "file_size": 1309, "cut_index": 524, "middle_length": 229 }
ls import reverse from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe try: import docutils.core import docutils.nodes import docutils.parsers.rst.roles import docutils.writers except ImportError: docutils_is_available = False else: docutils_is_av...
eturn (title, body, metadata). """ if not docstring: return "", "", {} docstring = cleandoc(docstring) parts = re.split(r"\n{2,}", docstring) title = parts[0] if len(parts) == 1: body = "" metadata = {} e
ame = view_func.__module__ view_name = getattr(view_func, "__qualname__", view_func.__class__.__name__) return mod_name + "." + view_name def parse_docstring(docstring): """ Parse out the parts of a docstring. R
{ "filepath": "django/contrib/admindocs/utils.py", "language": "python", "file_size": 8400, "cut_index": 716, "middle_length": 229 }
import GEOSBase from django.contrib.gis.geos.libgeos import CONTEXT_PTR, error_h, lgeos, notice_h class GEOSContextHandle(GEOSBase): """Represent a GEOS context handle.""" ptr_type = CONTEXT_PTR destructor = lgeos.GEOS_finish_r def __init__(self): self.ptr = lgeos.GEOS_init_r() lgeo...
variants when available. """ def __init__(self, func_name): # GEOS thread-safe function signatures end with '_r' and take an # additional context handle parameter. self.cfunc = getattr(lgeos, func_name + "_r") # C
rence to GEOSContextHandle for this thread. class GEOSContext(threading.local): handle = None thread_context = GEOSContext() class GEOSFunc: """ Serve as a wrapper for GEOS C Functions. Use thread-safe function
{ "filepath": "django/contrib/gis/geos/prototypes/threadsafe.py", "language": "python", "file_size": 2311, "cut_index": 563, "middle_length": 229 }
nctions for the topological operations on geometries. """ from ctypes import c_double, c_int from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory from django.contrib.gis.geos.prototypes.errcheck import ( check_geom, check_minus_one, check_string, ) from django.contrib.gis.geos.prototypes....
nt, c_int, c_int, c_double] ) geos_centroid = Topology("GEOSGetCentroid") geos_convexhull = Topology("GEOSConvexHull") geos_difference = Topology("GEOSDifference", argtypes=[GEOM_PTR, GEOM_PTR]) geos_envelope = Topology("GEOSEnvelope") geos_intersection =
# Topology Routines geos_boundary = Topology("GEOSBoundary") geos_buffer = Topology("GEOSBuffer", argtypes=[GEOM_PTR, c_double, c_int]) geos_bufferwithstyle = Topology( "GEOSBufferWithStyle", argtypes=[GEOM_PTR, c_double, c_i
{ "filepath": "django/contrib/gis/geos/prototypes/topology.py", "language": "python", "file_size": 2327, "cut_index": 563, "middle_length": 229 }
es.shortcuts import get_current_site from django.core.paginator import EmptyPage, PageNotAnInteger from django.http import Http404 from django.template.response import TemplateResponse from django.urls import reverse from django.utils import timezone from django.utils.http import http_date @dataclass class SitemapInd...
ither a date or a datetime. """ if not isinstance(new_lastmod, datetime.datetime): new_lastmod = datetime.datetime.combine(new_lastmod, datetime.time.min) if timezone.is_naive(new_lastmod): new_lastmod = timezone.make_aware(
response.headers["X-Robots-Tag"] = "noindex, noodp, noarchive" return response return inner def _get_latest_lastmod(current_lastmod, new_lastmod): """ Returns the latest `lastmod` where `lastmod` can be e
{ "filepath": "django/contrib/sitemaps/views.py", "language": "python", "file_size": 4648, "cut_index": 614, "middle_length": 229 }
fields import GenericForeignKey from django.contrib.contenttypes.forms import ( BaseGenericInlineFormSet, generic_inlineformset_factory, ) from django.core import checks from django.core.exceptions import FieldDoesNotExist from django.forms import ALL_FIELDS from django.forms.models import modelform_defines_fie...
nKey. gfks = [ f for f in obj.model._meta.private_fields if isinstance(f, GenericForeignKey) ] if not gfks: return [ checks.Error( "'%s' has no Gen
re required. return [] def _check_relation(self, obj, parent_model): # There's no FK, but we do need to confirm that the ct_field and # ct_fk_field are valid, and that they are part of a GenericForeig
{ "filepath": "django/contrib/contenttypes/admin.py", "language": "python", "file_size": 5858, "cut_index": 716, "middle_length": 229 }
some utility functions for inspecting the layout of a GDAL data source -- the functionality is analogous to the output produced by the `ogrinfo` utility. """ from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal.geometries import GEO_CLASSES def ogrinfo(data_source, num_features=10): """ ...
) for i, layer in enumerate(data_source): print("data source : %s" % data_source.name) print("==== layer %s" % i) print(" shape type: %s" % GEO_CLASSES[layer.geom_type.num].__name__) print(" # features: %s" % len
e, str): data_source = DataSource(data_source) elif isinstance(data_source, DataSource): pass else: raise Exception( "Data source parameter must be a string or a DataSource object."
{ "filepath": "django/contrib/gis/utils/ogrinfo.py", "language": "python", "file_size": 1956, "cut_index": 537, "middle_length": 229 }
m django.contrib.sites.models import Site from django.db import models from django.utils.translation import gettext_lazy as _ class Redirect(models.Model): site = models.ForeignKey(Site, models.CASCADE, verbose_name=_("site")) old_path = models.CharField( _("redirect from"), max_length=200, ...
https://”." ), ) class Meta: verbose_name = _("redirect") verbose_name_plural = _("redirects") db_table = "django_redirect" unique_together = [["site", "old_path"]] ordering = ["old_path"] def _
odels.CharField( _("redirect to"), max_length=200, blank=True, help_text=_( "This can be either an absolute path (as above) or a full URL " "starting with a scheme such as “
{ "filepath": "django/contrib/redirects/models.py", "language": "python", "file_size": 1083, "cut_index": 515, "middle_length": 229 }
m django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.inspect import ( func_accepts_kwargs, func_accepts_var_args, get_func_full_args, method_has_no_args, ) from django.utils.translation import gettext as _ from django.views.generic impor...
le: # Display an error message for people without docutils self.template_name = "admin_doc/missing_docutils.html" return self.render_to_response(admin.site.each_context(request)) return super().dispatch(request,
class BaseAdminDocsView(TemplateView): """ Base view for admindocs views. """ @method_decorator(staff_member_required) def dispatch(self, request, *args, **kwargs): if not utils.docutils_is_availab
{ "filepath": "django/contrib/admindocs/views.py", "language": "python", "file_size": 19572, "cut_index": 1331, "middle_length": 229 }
is module is for the miscellaneous GEOS routines, particularly the ones that return the area, distance, and length. """ from ctypes import POINTER, c_double, c_int from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string from...
, distance, and length prototypes. geos_area = DblFromGeom("GEOSArea", argtypes=[GEOM_PTR, POINTER(c_double)]) geos_distance = DblFromGeom( "GEOSDistance", argtypes=[GEOM_PTR, GEOM_PTR, POINTER(c_double)] ) geos_length = DblFromGeom("GEOSLength", argty
ument is a Geometry, return type is double that is passed in by reference as the last argument. """ restype = c_int # Status code returned errcheck = staticmethod(check_dbl) # ### ctypes prototypes ### # Area
{ "filepath": "django/contrib/gis/geos/prototypes/misc.py", "language": "python", "file_size": 1167, "cut_index": 518, "middle_length": 229 }
AppConfig from django.contrib.contenttypes.checks import ( check_generic_foreign_keys, check_model_name_lengths, ) from django.core import checks from django.db.models.signals import post_migrate, pre_migrate from django.utils.translation import gettext_lazy as _ from .management import create_contenttypes, i...
igrate.connect(inject_rename_contenttypes_operations, sender=self) post_migrate.connect(create_contenttypes) checks.register(check_generic_foreign_keys, checks.Tags.models) checks.register(check_model_name_lengths, checks.Tags.model
"Content Types") def ready(self): pre_m
{ "filepath": "django/contrib/contenttypes/apps.py", "language": "python", "file_size": 846, "cut_index": 535, "middle_length": 52 }
ls import chain from django.apps import apps from django.core.checks import Error def check_generic_foreign_keys(app_configs, **kwargs): from .fields import GenericForeignKeyDescriptor if app_configs is None: models = apps.get_models() else: models = chain.from_iterable( app_...
models = apps.get_models() else: models = chain.from_iterable( app_config.get_models() for app_config in app_configs ) errors = [] for model in models: if len(model._meta.model_name) > 100:
tance(obj, GenericForeignKeyDescriptor) ) for descriptor in descriptors: errors.extend(descriptor.field.check()) return errors def check_model_name_lengths(app_configs, **kwargs): if app_configs is None:
{ "filepath": "django/contrib/contenttypes/checks.py", "language": "python", "file_size": 1304, "cut_index": 524, "middle_length": 229 }
rms import ModelForm, modelformset_factory from django.forms.models import BaseModelFormSet class BaseGenericInlineFormSet(BaseModelFormSet): """ A formset for generic inline objects to a parent. """ def __init__( self, data=None, files=None, instance=None, sav...
instance is None or not self.instance._is_pk_set(): qs = self.model._default_manager.none() else: if queryset is None: queryset = self.model._default_manager qs = queryset.filter(
.app_label + "-" + opts.model_name + "-" + self.ct_field.name + "-" + self.ct_fk_field.name ) self.save_as_new = save_as_new if self.
{ "filepath": "django/contrib/contenttypes/forms.py", "language": "python", "file_size": 3950, "cut_index": 614, "middle_length": 229 }
db.models import Prefetch from django.db.models.query import ModelIterable, RawQuerySet class GenericPrefetch(Prefetch): def __init__(self, lookup, querysets, to_attr=None): for queryset in querysets: if queryset is not None and ( isinstance(queryset, RawQuerySet) ...
e__(self): obj_dict = self.__dict__.copy() obj_dict["querysets"] = [] for queryset in self.querysets: if queryset is not None: queryset = queryset._chain() # Prevent the QuerySet from bein
raise ValueError( "Prefetch querysets cannot use raw(), values(), and values_list()." ) self.querysets = querysets super().__init__(lookup, to_attr=to_attr) def __getstat
{ "filepath": "django/contrib/contenttypes/prefetch.py", "language": "python", "file_size": 1358, "cut_index": 524, "middle_length": 229 }
ntegrityError, migrations, router, transaction class RenameContentType(migrations.RunPython): def __init__(self, app_label, old_model, new_model): self.app_label = app_label self.old_model = old_model self.new_model = new_model super().__init__(self.rename_forward, self.rename_back...
except ContentType.DoesNotExist: pass else: content_type.model = new_model try: with transaction.atomic(using=db): content_type.save(using=db, update_fields={"model"})
if not router.allow_migrate_model(db, ContentType): return try: content_type = ContentType.objects.db_manager(db).get_by_natural_key( self.app_label, old_model )
{ "filepath": "django/contrib/contenttypes/management/__init__.py", "language": "python", "file_size": 5012, "cut_index": 614, "middle_length": 229 }
o.contrib.contenttypes.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="ContentType", fields=[ ( "id", models.AutoField(...
max_length=100, verbose_name="python model class name" ), ), ], options={ "ordering": ("name",), "db_table": "django_content_type",
), ("name", models.CharField(max_length=100)), ("app_label", models.CharField(max_length=100)), ( "model", models.CharField(
{ "filepath": "django/contrib/contenttypes/migrations/0001_initial.py", "language": "python", "file_size": 1434, "cut_index": 524, "middle_length": 229 }
conf import settings from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin from .utils import get_view_name class XViewMiddleware(MiddlewareMixin): """ Add an X-View header to internal HEAD requests. """ def ...
rlyConfigured( "The XView middleware requires authentication middleware to " "be installed. Edit your MIDDLEWARE setting to insert " "'django.contrib.auth.middleware.AuthenticationMiddleware'." )
return a response with an x-view header indicating the view function. This is used to lookup the view function for an arbitrary page. """ if not hasattr(request, "user"): raise Imprope
{ "filepath": "django/contrib/admindocs/middleware.py", "language": "python", "file_size": 1329, "cut_index": 524, "middle_length": 229 }
class Sitemap: # This limit is defined by Google. See the index documentation at # https://www.sitemaps.org/protocol.html#index. limit = 50000 # If protocol is None, the URLs in the sitemap will use the protocol # with which the sitemap was requested. protocol = None # Enables generating...
if callable(attr): if self.i18n: # Split the (item, lang_code) tuples again for the location, # priority, lastmod and changefreq method calls. item, lang_code = item return att
n alternate/hreflang link with value 'x-default'. x_default = False def _get(self, name, item, default=None): try: attr = getattr(self, name) except AttributeError: return default
{ "filepath": "django/contrib/sitemaps/__init__.py", "language": "python", "file_size": 6951, "cut_index": 716, "middle_length": 229 }
e from django.db import DEFAULT_DB_ALIAS, connections def add_srs_entry( srs, auth_name="EPSG", auth_srid=None, ref_sys_name=None, database=None ): """ Take a GDAL SpatialReference system and add its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-lev...
s keyword may be customized with the value of the `auth_srid` field. Defaults to the SRID determined by GDAL. ref_sys_name: For SpatiaLite users only, sets the value of the `ref_sys_name` field. Defaults to the name determined by
.utils import add_srs_entry >>> add_srs_entry(3857) Keyword Arguments: auth_name: This keyword may be customized with the value of the `auth_name` field. Defaults to 'EPSG'. auth_srid: Thi
{ "filepath": "django/contrib/gis/utils/srs.py", "language": "python", "file_size": 2961, "cut_index": 563, "middle_length": 229 }
ntrib.sites.shortcuts import get_current_site from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.http import Http404, HttpResponseRedirect from django.utils.translation import gettext as _ def shortcut(request, content_type_id, object_id): """ Redirect to an object's page based...
ontent_type.get_object_for_this_type(pk=object_id) except (ObjectDoesNotExist, ValueError, ValidationError): raise Http404( _("Content type %(ct_id)s object %(obj_id)s doesn’t exist") % {"ct_id": content_type_id, "obj_id
_type_id) if not content_type.model_class(): raise Http404( _("Content type %(ct_id)s object has no associated model") % {"ct_id": content_type_id} ) obj = c
{ "filepath": "django/contrib/contenttypes/views.py", "language": "python", "file_size": 3583, "cut_index": 614, "middle_length": 229 }
jango.db import migrations, models def add_legacy_name(apps, schema_editor): alias = schema_editor.connection.alias ContentType = apps.get_model("contenttypes", "ContentType") for ct in ContentType.objects.using(alias): try: ct.name = apps.get_model(ct.app_label, ct.model)._meta.object...
}, ), migrations.AlterField( model_name="contenttype", name="name", field=models.CharField(max_length=100, null=True), ), migrations.RunPython( migrations.RunPython.noop,
operations = [ migrations.AlterModelOptions( name="contenttype", options={ "verbose_name": "content type", "verbose_name_plural": "content types",
{ "filepath": "django/contrib/contenttypes/migrations/0002_remove_content_type_name.py", "language": "python", "file_size": 1199, "cut_index": 518, "middle_length": 229 }
django.utils.http import http_date from django.utils.timezone import get_default_timezone, is_naive, make_aware from django.utils.translation import get_language def add_domain(domain, url, secure=False): protocol = "https" if secure else "http" if url.startswith("//"): # Support network-path referenc...
f __call__(self, request, *args, **kwargs): try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404("Feed object does not exist.") feedgen = self.get_feed(obj, request)
ol, domain, url)) return url class FeedDoesNotExist(ObjectDoesNotExist): pass class Feed: feed_type = feedgenerator.DefaultFeed title_template = None description_template = None language = None de
{ "filepath": "django/contrib/syndication/views.py", "language": "python", "file_size": 9371, "cut_index": 921, "middle_length": 229 }
ype from django.core.management import BaseCommand from django.db import DEFAULT_DB_ALIAS, connections, router from django.db.models.deletion import Collector class Command(BaseCommand): help = "Deletes stale content types in the database." def add_arguments(self, parser): parser.add_argument( ...
) parser.add_argument( "--include-stale-apps", action="store_true", default=False, help=( "Deletes stale content types including ones from previously " "installe
) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help='Nominates the database to use. Defaults to the "default" database.',
{ "filepath": "django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py", "language": "python", "file_size": 4494, "cut_index": 614, "middle_length": 229 }
ontrib.admin import helpers from django.contrib.admin.decorators import action from django.contrib.admin.utils import model_ngettext from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.utils.translation import gettext as _ from django.utils.translation i...
a "permission denied" message. Next, it deletes all selected objects and redirects back to the change list. """ opts = modeladmin.model._meta app_label = opts.app_label # Populate deletable_objects, a data structure of all relate
Default action which deletes the selected objects. This action first displays a confirmation page which shows all the deletable objects, or, if the user has no permission one of the related childs (foreignkeys),
{ "filepath": "django/contrib/admin/actions.py", "language": "python", "file_size": 3272, "cut_index": 614, "middle_length": 229 }
ngo.apps import AppConfig from django.contrib.admin.checks import check_admin_app, check_dependencies from django.core import checks from django.utils.translation import gettext_lazy as _ class SimpleAdminConfig(AppConfig): """Simple AppConfig which does not do automatic discovery.""" default_auto_field = "d...
checks.register(check_admin_app, checks.Tags.admin) class AdminConfig(SimpleAdminConfig): """The default AppConfig for admin which does autodiscovery.""" default = True def ready(self): super().ready() self.module.aut
ks.register(check_dependencies, checks.Tags.admin)
{ "filepath": "django/contrib/admin/apps.py", "language": "python", "file_size": 840, "cut_index": 520, "middle_length": 52 }
rmissions=None, description=None, description_plural=None, location=ActionLocation.CHANGE_LIST, ): """ Conveniently add attributes to an action function:: @admin.action( permissions=['publish'], description='Mark selected stories as published', ) def ...
ished' """ def decorator(func): if permissions is not None: func.allowed_permissions = permissions if description is not None: func.short_description = description if description_plural is not None:
ly:: def make_published(self, request, queryset): queryset.update(status='p') make_published.allowed_permissions = ['publish'] make_published.short_description = 'Mark selected stories as publ
{ "filepath": "django/contrib/admin/decorators.py", "language": "python", "file_size": 3930, "cut_index": 614, "middle_length": 229 }
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ class AdminAuthenticationForm(AuthenticationForm): """ A custom authentication form used in the admin app. """ error_m...
alidationError( self.error_messages["invalid_login"], code="invalid_login", params={"username": self.username_field.verbose_name}, ) class AdminPasswordChangeForm(PasswordChangeForm): requir
at both fields may be case-sensitive." ), } required_css_class = "required" def confirm_login_allowed(self, user): super().confirm_login_allowed(user) if not user.is_staff: raise V
{ "filepath": "django/contrib/admin/forms.py", "language": "python", "file_size": 1023, "cut_index": 512, "middle_length": 229 }
oReverseMatch, reverse from django.utils import timezone from django.utils.text import get_text_list from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ ADDITION = 1 CHANGE = 2 DELETION = 3 ACTION_FLAG_CHOICES = [ (ADDITION, _("Addition")), (CHANGE, _("Change"))...
content_type_id=ContentType.objects.get_for_model( obj, for_concrete_model=False ).id, object_id=obj.pk, object_repr=str(obj)[:200], action_flag=action_flag,
*, single_object=False ): if isinstance(change_message, list): change_message = json.dumps(change_message) log_entry_list = [ self.model( user_id=user_id,
{ "filepath": "django/contrib/admin/models.py", "language": "python", "file_size": 6867, "cut_index": 716, "middle_length": 229 }
rse_lazy from django.utils.decorators import method_decorator from django.utils.functional import LazyObject from django.utils.module_loading import import_string from django.utils.text import capfirst from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy from django.views....
g the register() method, and the get_urls() method can then be used to access Django view functions that present a full admin interface for the collection of registered models. """ # Text to put at the end of each page's <title>. site_
alog all_sites = WeakSet() class AdminSite: """ An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite usin
{ "filepath": "django/contrib/admin/sites.py", "language": "python", "file_size": 23478, "cut_index": 1331, "middle_length": 229 }
om django.utils.text import capfirst from django.utils.translation import ngettext from django.utils.translation import override as translation_override QUOTE_MAP = {i: "_%02X" % i for i in b'":/_#?;@&=+$,"[]<>%\n\\'} UNQUOTE_MAP = {v: chr(k) for k, v in QUOTE_MAP.items()} UNQUOTE_RE = _lazy_re_compile("_(?:%s)" % "|"...
ame in lookup_fields: if field_name == "pk": field_name = opts.pk.name try: field = opts.get_field(field_name) except FieldDoesNotExist: # Ignore query lookups. continue else:
ookup_path): """ Return True if the given lookup path spawns duplicates. """ lookup_fields = lookup_path.split(LOOKUP_SEP) # Go through the fields (following all relations) and look for an m2m. for field_n
{ "filepath": "django/contrib/admin/utils.py", "language": "python", "file_size": 22600, "cut_index": 1331, "middle_length": 229 }
e.exceptions import FieldDoesNotExist, PermissionDenied from django.http import Http404, JsonResponse from django.views.generic.list import BaseListView class AutocompleteJsonView(BaseListView): """Handle AutocompleteWidget's AJAX requests for data.""" paginate_by = 20 admin_site = None def get(self...
st) if not self.has_perm(request): raise PermissionDenied self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse( { "results": [
: "foo"}], pagination: {more: true} } """ ( self.term, self.model_admin, self.source_field, to_field_name, ) = self.process_request(reque
{ "filepath": "django/contrib/admin/views/autocomplete.py", "language": "python", "file_size": 4385, "cut_index": 614, "middle_length": 229 }
import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("contenttypes", "__first__"), ] operations = [ migrations.CreateModel( name="LogEntry", ...
se_name="action time"), ), ( "object_id", models.TextField(null=True, verbose_name="object id", blank=True), ), ( "object_repr",
auto_created=True, primary_key=True, ), ), ( "action_time", models.DateTimeField(auto_now=True, verbo
{ "filepath": "django/contrib/admin/migrations/0001_initial.py", "language": "python", "file_size": 2507, "cut_index": 563, "middle_length": 229 }
in.options import EMPTY_VALUE_STRING from django.contrib.admin.utils import display_for_value from django.template.defaultfilters import _walk_items, stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from django.utils.translation import ngettext register = temp...
ted_objects|truncated_unordered_list:100 }} """ has_unlimited_items = max_items is None if not has_unlimited_items: max_items = int(max_items) if max_items <= 0: return mark_safe("") if autoescape: esca
pe=True) def truncated_unordered_list(value, max_items, autoescape=True): """ Render an unordered list, showing at most ``max_items`` items and a "...and N more objects." item at the end. Usage:: {{ dele
{ "filepath": "django/contrib/admin/templatetags/admin_filters.py", "language": "python", "file_size": 2422, "cut_index": 563, "middle_length": 229 }
jango.contrib.admin.decorators import action, display, register from django.contrib.admin.filters import ( AllValuesFieldListFilter, BooleanFieldListFilter, ChoicesFieldListFilter, DateFieldListFilter, EmptyFieldListFilter, FieldListFilter, ListFilter, RelatedFieldListFilter, Related...
", "HORIZONTAL", "VERTICAL", "StackedInline", "TabularInline", "AdminSite", "site", "ListFilter", "SimpleListFilter", "FieldListFilter", "BooleanFieldListFilter", "RelatedFieldListFilter", "ChoicesFieldListFi
TabularInline, ) from django.contrib.admin.sites import AdminSite, site from django.utils.module_loading import autodiscover_modules __all__ = [ "action", "ActionLocation", "display", "register", "ModelAdmin
{ "filepath": "django/contrib/admin/__init__.py", "language": "python", "file_size": 1245, "cut_index": 518, "middle_length": 229 }
s def check_dependencies(**kwargs): """ Check that the admin's dependencies are correctly installed. """ from django.contrib.admin.sites import all_sites if not apps.is_installed("django.contrib.admin"): return [] errors = [] app_dependencies = ( ("django.contrib.contentty...
de, ) ) for engine in engines.all(): if isinstance(engine, DjangoTemplates): django_templates_instance = engine.engine break else: django_templates_instance = None if not djang
errors.append( checks.Error( "'%s' must be in INSTALLED_APPS in order to use the admin " "application." % app_name, id="admin.E%d" % error_co
{ "filepath": "django/contrib/admin/checks.py", "language": "python", "file_size": 52481, "cut_index": 2151, "middle_length": 229 }
class ActionForm(forms.Form): action = forms.ChoiceField(label=_("Action:")) select_across = forms.BooleanField( label="", required=False, initial=0, widget=forms.HiddenInput({"class": "select-across"}), ) class AdminForm: def __init__( self, form, ...
adonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __repr__(self): return ( f"<{self.__class__.__qualname__}: " f"form={self.form.__class__.__qualname__} "
s = [ {"field": form[field_name], "dependencies": [form[f] for f in dependencies]} for field_name, dependencies in prepopulated_fields.items() ] self.model_admin = model_admin if re
{ "filepath": "django/contrib/admin/helpers.py", "language": "python", "file_size": 18435, "cut_index": 1331, "middle_length": 229 }
s( MIDDLEWARE={"append": "django.middleware.csp.ContentSecurityPolicyMiddleware"} ) @override_settings( SECURE_CSP={ "default-src": [CSP.NONE], "connect-src": [CSP.SELF], "img-src": [CSP.SELF], "script-src": [CSP.SELF], "style-src": [CSP.SELF], }, ) class AdminSeleniu...
super().tearDown() def wait_until(self, callback, timeout=10): """ Block the execution of the tests until the specified callback returns a value that is not falsy. This method can be called, for example, after click
ngo.contrib.sessions", "django.contrib.sites", ] def tearDown(self): # Ensure that no CSP violations were logged in the browser. self.assertEqual(self.get_browser_logs(source="security"), [])
{ "filepath": "django/contrib/admin/tests.py", "language": "python", "file_size": 9400, "cut_index": 921, "middle_length": 229 }
.models import F, Field, ManyToOneRel, OrderBy from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import Combinable from django.urls import reverse from django.utils.http import urlencode from django.utils.timezone import make_aware from django.utils.translation import gettext # Change...
is a variable: self.fields = { SEARCH_VAR: forms.CharField(required=False, strip=False), } class ChangeList: search_form_class = ChangeListSearchForm def __init__( self, request, model,
AR, SOURCE_MODEL_VAR, TO_FIELD_VAR, ) class ChangeListSearchForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Populate "fields" dynamically because SEARCH_VAR
{ "filepath": "django/contrib/admin/views/main.py", "language": "python", "file_size": 22542, "cut_index": 1331, "middle_length": 229 }
istFilter: title = None # Human-readable title to appear in the right sidebar. template = "admin/filter.html" def __init__(self, request, params, model, model_admin): self.request = request # This dictionary will eventually contain the request's query string # parameters actually u...
asses of ListFilter must provide a has_output() method" ) def choices(self, changelist): """ Return choices ready to be output in the template. `changelist` is the ChangeList to be displayed. """ raise
% self.__class__.__name__ ) def has_output(self): """ Return True if some choices would be output for this filter. """ raise NotImplementedError( "subcl
{ "filepath": "django/contrib/admin/filters.py", "language": "python", "file_size": 27668, "cut_index": 1331, "middle_length": 229 }
arnings.warn( "Unpacking an action tuple is deprecated. Use Action attributes instead.", RemovedInDjango70Warning, skip_file_prefixes=django_file_prefixes(), ) return iter(self._as_tuple()) # RemovedInDjango70Warning. def __getitem__(self, index): war...
import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def get_ul_class(radio_style): return "radiolist" i
ango_file_prefixes(), ) return self._as_tuple()[index] HORIZONTAL, VERTICAL = 1, 2 def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot
{ "filepath": "django/contrib/admin/options.py", "language": "python", "file_size": 113731, "cut_index": 3790, "middle_length": 229 }
from asgiref.sync import async_to_sync, sync_to_async from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import PermissionDenied from django.shortcuts import resolve_url def user_passes_test( test_func, login_url=None, redirect_field_name=REDIRECT_FI...
l or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlsplit(resolved_login_url)[:2] current_scheme, curren
ser object and returns True if the user passes. """ def decorator(view_func): def _redirect_to_login(request): path = request.build_absolute_uri() resolved_login_url = resolve_url(login_ur
{ "filepath": "django/contrib/auth/decorators.py", "language": "python", "file_size": 4779, "cut_index": 614, "middle_length": 229 }
ger(models.Manager): use_in_migrations = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Cache shared by all the get_for_* methods to speed up # ContentType retrieval. self._cache = {} def get_by_natural_key(self, app_label, model): try...
s.app_label, opts.model_name) return self._cache[self.db][key] def get_for_model(self, model, for_concrete_model=True): """ Return the ContentType object for a given model, creating the ContentType if necessary. Lookups
return ct def _get_opts(self, model, for_concrete_model): if for_concrete_model: model = model._meta.concrete_model return model._meta def _get_from_cache(self, opts): key = (opt
{ "filepath": "django/contrib/contenttypes/models.py", "language": "python", "file_size": 6874, "cut_index": 716, "middle_length": 229 }
i18n catalog has been loaded in the page """ use_fieldset = True class Media: js = [ "admin/js/core.js", "admin/js/SelectBox.js", "admin/js/SelectFilter2.js", ] def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.v...
.verbose_name context["widget"]["attrs"]["data-is-stacked"] = int(self.is_stacked) return context class DateTimeWidgetContextMixin: def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs)
ame, value, attrs) context["widget"]["attrs"]["class"] = "selectfilter" if self.is_stacked: context["widget"]["attrs"]["class"] += "stacked" context["widget"]["attrs"]["data-field-name"] = self
{ "filepath": "django/contrib/admin/widgets.py", "language": "python", "file_size": 20576, "cut_index": 1331, "middle_length": 229 }
it, urlunsplit from django import template from django.contrib.admin.utils import quote from django.urls import Resolver404, get_script_prefix, resolve from django.utils.http import urlencode register = template.Library() @register.filter def admin_urlname(value, arg): return "admin:%s_%s_%s" % (value.app_label...
rl[3])) merged_qs = {} if preserved_qsl: merged_qs.update(preserved_qsl) if opts and preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters)) match_url = "/%s" % unquote(url).partition(get_script_pref
o_field=None): opts = context.get("opts") preserved_filters = context.get("preserved_filters") preserved_qsl = context.get("preserved_qsl") parsed_url = list(urlsplit(url)) parsed_qs = dict(parse_qsl(parsed_u
{ "filepath": "django/contrib/admin/templatetags/admin_urls.py", "language": "python", "file_size": 2038, "cut_index": 563, "middle_length": 229 }
brary() class AdminLogNode(template.Node): def __init__(self, limit, varname, user): self.limit = limit self.varname = varname self.user = user def __repr__(self): return "<GetAdminLog Node>" def render(self, context): entries = context["log_entries"] if s...
{% get_admin_log [limit] as [varname] for_user [user_id_or_varname] %} Examples:: {% get_admin_log 10 as admin_log for_user 23 %} {% get_admin_log 10 as admin_log for_user user %} {% get_admin_log 10 as admin_log %}
d) context[self.varname] = entries[: int(self.limit)] return "" @register.tag def get_admin_log(parser, token): """ Populate a template variable with the admin log for the given criteria. Usage::
{ "filepath": "django/contrib/admin/templatetags/log.py", "language": "python", "file_size": 2030, "cut_index": 563, "middle_length": 229 }
t connections from django.db.backends.postgresql.psycopg_any import RANGE_TYPES from django.db.backends.signals import connection_created from django.db.migrations.writer import MigrationWriter from django.db.models import CharField, OrderBy, TextField from django.db.models.functions import Collate from django.db.model...
s of PostgresConfig.ready() when django.contrib.postgres is "uninstalled" by override_settings(). """ if ( not enter and setting == "INSTALLED_APPS" and "django.contrib.postgres" not in set(value) ): connecti
rictWordSimilar, TrigramWordSimilar, Unaccent, ) from .serializers import RangeSerializer from .signals import register_type_handlers def uninstall_if_needed(setting, value, enter, **kwargs): """ Undo the effect
{ "filepath": "django/contrib/postgres/apps.py", "language": "python", "file_size": 4062, "cut_index": 614, "middle_length": 229 }
ort Transform from django.db.models.lookups import PostgresOperatorLookup from django.db.models.sql.query import Query from .search import SearchVector, SearchVectorExact, SearchVectorField class DataContains(PostgresOperatorLookup): lookup_name = "contains" postgres_operator = "@>" class ContainedBy(Postg...
okup): lookup_name = "has_key" postgres_operator = "?" prepare_rhs = False class HasKeys(PostgresOperatorLookup): lookup_name = "has_keys" postgres_operator = "?&" def get_prep_lookup(self): return [str(item) for item in
_prep_lookup(self): from .expressions import ArraySubquery if isinstance(self.rhs, Query): self.rhs = ArraySubquery(self.rhs) return super().get_prep_lookup() class HasKey(PostgresOperatorLo
{ "filepath": "django/contrib/postgres/lookups.py", "language": "python", "file_size": 1991, "cut_index": 537, "middle_length": 229 }
reversible = True category = OperationCategory.ADDITION def __init__(self, name, hints=None): self.name = name self.hints = hints or {} def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): if sc...
oids. get_hstore_oids.cache_clear() get_citext_oids.cache_clear() # Registering new type handlers cannot be done before the extension is # installed, otherwise a subsequent data migration would use the same # connec
.extension_exists(schema_editor, self.name): schema_editor.execute( "CREATE EXTENSION IF NOT EXISTS %s" % schema_editor.quote_name(self.name) ) # Clear cached, stale
{ "filepath": "django/contrib/postgres/operations.py", "language": "python", "file_size": 12668, "cut_index": 921, "middle_length": 229 }
from django.db.backends.base.base import NO_DB_ALIAS from django.db.backends.postgresql.psycopg_any import is_psycopg3 def get_type_oids(connection_alias, type_name): with connections[connection_alias].cursor() as cursor: cursor.execute( "SELECT oid, typarray FROM pg_type WHERE typname = %s",...
ion_alias): """Return citext and citext array OIDs.""" return get_type_oids(connection_alias, "citext") if is_psycopg3: from psycopg.types import TypeInfo, hstore def register_type_handlers(connection, **kwargs): if connection.ve
uple(array_oids) @functools.lru_cache def get_hstore_oids(connection_alias): """Return hstore and hstore array OIDs.""" return get_type_oids(connection_alias, "hstore") @functools.lru_cache def get_citext_oids(connect
{ "filepath": "django/contrib/postgres/signals.py", "language": "python", "file_size": 2880, "cut_index": 563, "middle_length": 229 }
from django.core.validators import ( MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, ) from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy class ArrayMaxLengthValida...
should contain no fewer than " "%(limit_value)d.", "List contains %(show_value)d items, it should contain no fewer than " "%(limit_value)d.", "show_value", ) @deconstructible class KeysValidator: """A validator de
ue)d items, it should contain no more than " "%(limit_value)d.", "show_value", ) class ArrayMinLengthValidator(MinLengthValidator): message = ngettext_lazy( "List contains %(show_value)d item, it
{ "filepath": "django/contrib/postgres/validators.py", "language": "python", "file_size": 2801, "cut_index": 563, "middle_length": 229 }
import forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ __all__ = ["HStoreField"] class HStoreField(forms.CharField): """ A field for HStore data which accepts dictionary JSON input. """ widget = forms.Textarea default_error_messages...
value = json.loads(value) except json.JSONDecodeError: raise ValidationError( self.error_messages["invalid_json"], code="invalid_json", ) if not isinst
alue, dict): return json.dumps(value, ensure_ascii=False) return value def to_python(self, value): if not value: return {} if not isinstance(value, dict): try:
{ "filepath": "django/contrib/postgres/forms/hstore.py", "language": "python", "file_size": 1787, "cut_index": 537, "middle_length": 229 }
e from django.db.models.fields.mixins import CheckFieldDefaultMixin from django.db.models.lookups import Exact, In from django.utils.translation import gettext_lazy as _ from .utils import AttributeSetter __all__ = ["ArrayField"] class ArrayField(CheckPostgresInstalledMixin, CheckFieldDefaultMixin, Field): empt...
self.size = size if self.size: self.default_validators = [ *self.default_validators, ArrayMaxLengthValidator(self.size), ] # For performance, only add a from_db_value() method
he same length."), } _default_hint = ("list", "[]") def __init__(self, base_field, size=None, **kwargs): self.base_field = base_field self.db_collation = getattr(self.base_field, "db_collation", None)
{ "filepath": "django/contrib/postgres/fields/array.py", "language": "python", "file_size": 13205, "cut_index": 921, "middle_length": 229 }
Create a list of prepopulated_fields that should render JavaScript for the prepopulated fields for both the admin form and inlines. """ prepopulated_fields = [] if "adminform" in context: prepopulated_fields.extend(context["adminform"].prepopulated_fields) if "inline_admin_formsets" in cont...
d": "#%s" % field["field"].auto_id, "name": field["field"].name, "dependency_ids": [ "#%s" % dependency.auto_id for dependency in field["dependencies"] ], "dependency_list"
prepopulated_fields.extend(inline_admin_form.prepopulated_fields) prepopulated_fields_json = [] for field in prepopulated_fields: prepopulated_fields_json.append( { "i
{ "filepath": "django/contrib/admin/templatetags/admin_modify.py", "language": "python", "file_size": 5343, "cut_index": 716, "middle_length": 229 }
PostgresOperatorLookup from django.db.models.sql import Query from .fields import RangeOperators from .utils import CheckPostgresInstalledMixin __all__ = ["ExclusionConstraint"] class ExclusionConstraintExpression(IndexExpression): template = "%(expressions)s WITH %(operator)s" class ExclusionConstraint(Chec...
message=None, ): if index_type and index_type.lower() not in {"gist", "hash", "spgist"}: raise ValueError( "Exclusion constraints only support GiST, Hash, or SP-GiST indexes." ) if not expressions
def __init__( self, *, name, expressions, index_type=None, condition=None, deferrable=None, include=None, violation_error_code=None, violation_error_
{ "filepath": "django/contrib/postgres/constraints.py", "language": "python", "file_size": 10255, "cut_index": 921, "middle_length": 229 }
", "GinIndex", "GistIndex", "HashIndex", "SpGistIndex", ] class PostgresIndex(CheckPostgresInstalledMixin, Index): @cached_property def max_name_length(self): # Allow an index name longer than 30 characters when the suffix is # longer than the usual 3 character limit. The 30 ch...
, **kwargs ) with_params = self.get_with_params() if with_params: statement.parts["extra"] = " WITH (%s)%s" % ( ", ".join(with_params), statement.parts["extra"], ) retu
def create_sql(self, model, schema_editor, using="", **kwargs): self.check_supported(schema_editor) statement = super().create_sql( model, schema_editor, using=" USING %s" % (using or self.suffix)
{ "filepath": "django/contrib/postgres/indexes.py", "language": "python", "file_size": 8301, "cut_index": 716, "middle_length": 229 }
utils import CheckPostgresInstalledMixin if is_psycopg3: from psycopg.adapt import Dumper class UTF8Dumper(Dumper): def dump(self, obj): return bytes(obj, "utf-8") def quote_lexeme(value): return UTF8Dumper(str).quote(psql_escape(value)).decode() else: from psycopg2.exten...
return None return multiple_spaces_re.sub(" ", val) def psql_escape(query): """Replace chars not fit for use in search queries with a single space.""" query = spec_chars_re.sub(" ", query) return normalize_spaces(query) class SearchVe
azy_re_compile(r"['\0\[\]()|&:*!@<>\\]") multiple_spaces_re = _lazy_re_compile(r"\s{2,}") def normalize_spaces(val): """Convert multiple spaces to single and strip from both sides.""" if not (val := val.strip()):
{ "filepath": "django/contrib/postgres/search.py", "language": "python", "file_size": 16079, "cut_index": 921, "middle_length": 229 }
ator, ArrayMinLengthValidator, ) from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ class SimpleArrayField(forms.CharField): default_error_messages = { "item_invalid": _("Item %(nth)s in the array did not validate:"), } def __init__( ...
ngth self.validators.append(ArrayMaxLengthValidator(int(max_length))) def clean(self, value): value = super().clean(value) return [self.base_field.clean(val) for val in value] def prepare_value(self, value): if
rgs) if min_length is not None: self.min_length = min_length self.validators.append(ArrayMinLengthValidator(int(min_length))) if max_length is not None: self.max_length = max_le
{ "filepath": "django/contrib/postgres/forms/array.py", "language": "python", "file_size": 8422, "cut_index": 716, "middle_length": 229 }
_any import ( DateRange, DateTimeTZRange, NumericRange, ) from django.forms.widgets import HiddenInput, MultiWidget from django.utils.translation import gettext_lazy as _ __all__ = [ "BaseRangeField", "IntegerRangeField", "DecimalRangeField", "DateTimeRangeField", "DateRangeField", ...
input type="hidden"> inputs.""" def __init__(self, attrs=None): super().__init__(HiddenInput, attrs) class BaseRangeField(forms.MultiValueField): default_error_messages = { "invalid": _("Enter two valid values."), "bound_
__(widgets, attrs) def decompress(self, value): if value: return (value.lower, value.upper) return (None, None) class HiddenRangeWidget(RangeWidget): """A widget that splits input into two <
{ "filepath": "django/contrib/postgres/forms/ranges.py", "language": "python", "file_size": 3652, "cut_index": 614, "middle_length": 229 }
ptions import TemplateSyntaxError from django.template.library import InclusionNode, parse_bits from django.utils.inspect import getfullargspec class InclusionAdminNode(InclusionNode): """ Template tag that allows its template to be overridden per model, per app, or globally. """ def __init__(sel...
teSyntaxError( f"{name!r} sets takes_context=True so {function_name!r} " "must have a first argument of 'context'" ) bits = token.split_contents() args, kwargs = parse_bits(
ec( func ) if takes_context: if params and params[0] == "context": del params[0] else: function_name = func.__name__ raise Templa
{ "filepath": "django/contrib/admin/templatetags/base.py", "language": "python", "file_size": 1886, "cut_index": 537, "middle_length": 229 }
t checks from django.core.exceptions import ValidationError from django.utils.functional import SimpleLazyObject from django.utils.text import format_lazy def prefix_validation_error(error, prefix, code, params): """ Prefix a validation error message while maintaining the existing validation data structur...
# to an empty string if they are missing it. message=format_lazy( "{} {}", SimpleLazyObject(lambda: prefix % params), SimpleLazyObject(lambda: error.message % error_params), ),
uire # their associated parameters to be expressed correctly which # is not something `format_lazy` does. For example, proxied # ngettext calls require a count parameter and are converted
{ "filepath": "django/contrib/postgres/utils.py", "language": "python", "file_size": 2021, "cut_index": 563, "middle_length": 229 }
m django.utils.safestring import SafeData, mark_safe class MessageEncoder(json.JSONEncoder): """ Compactly serialize instances of the ``Message`` class as JSON. """ message_key = "__json_message" def default(self, obj): if isinstance(obj, Message): # Using 0/1 here instead of...
es serialized ``Message`` instances. """ def process_messages(self, obj): if isinstance(obj, list) and obj: if obj[0] == MessageEncoder.message_key: if obj[1]: obj[3] = mark_safe(obj[3])
if obj.extra_tags is not None: message.append(obj.extra_tags) return message return super().default(obj) class MessageDecoder(json.JSONDecoder): """ Decode JSON that includ
{ "filepath": "django/contrib/messages/storage/cookie.py", "language": "python", "file_size": 8678, "cut_index": 716, "middle_length": 229 }
gregate from django.db.models import BitAnd as _BitAnd from django.db.models import BitOr as _BitOr from django.db.models import BitXor as _BitXor from django.db.models import BooleanField, JSONField from django.db.models import StringAgg as _StringAgg from django.db.models import Value from django.utils.deprecation im...
self): return ArrayField(self.source_expressions[0].output_field) class BitAnd(_BitAnd): def __init__(self, expression, **extra): warnings.warn( "The PostgreSQL-specific BitAnd function is deprecated. Use " "dj
lAnd", "BoolOr", "JSONBAgg", "StringAgg", # RemovedInDjango70Warning. ] class ArrayAgg(Aggregate): function = "ARRAY_AGG" allow_distinct = True allow_order_by = True @property def output_field(
{ "filepath": "django/contrib/postgres/aggregates/general.py", "language": "python", "file_size": 3187, "cut_index": 614, "middle_length": 229 }
ule allows importing AbstractBaseSession even when django.contrib.sessions is not in INSTALLED_APPS. """ from django.db import models from django.utils.translation import gettext_lazy as _ class BaseSessionManager(models.Manager): def encode(self, session_dict): """ Return the given session dicti...
no data. return s class AbstractBaseSession(models.Model): session_key = models.CharField(_("session key"), max_length=40, primary_key=True) session_data = models.TextField(_("session data")) expire_date = models.DateTimeField(_("exp
(self, session_key, session_dict, expire_date): s = self.model(session_key, self.encode(session_dict), expire_date) if session_dict: s.save() else: s.delete() # Clear sessions with
{ "filepath": "django/contrib/sessions/base_session.py", "language": "python", "file_size": 1491, "cut_index": 524, "middle_length": 229 }
jango.contrib.sessions.base_session import AbstractBaseSession, BaseSessionManager class SessionManager(BaseSessionManager): use_in_migrations = True class Session(AbstractBaseSession): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitra...
nerable to session-ID theft via the "Referer" header. For complete documentation on using Sessions in your code, consult the sessions documentation that is shipped with Django (also available on the Django web site). """ objects = Ses
The Django sessions framework is entirely cookie-based. It does not fall back to putting session IDs in URLs. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vul
{ "filepath": "django/contrib/sessions/models.py", "language": "python", "file_size": 1250, "cut_index": 518, "middle_length": 229 }
nBase, UpdateError from django.core.cache import caches KEY_PREFIX = "django.contrib.sessions.cache" class SessionStore(SessionBase): """ A cache-based session store. """ cache_key_prefix = KEY_PREFIX def __init__(self, session_key=None): self._cache = caches[settings.SESSION_CACHE_ALIA...
emcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. session_data = None if session_data is not None: return session_data self._session_key = None r
return self.cache_key_prefix + await self._aget_or_create_session_key() def load(self): try: session_data = self._cache.get(self.cache_key) except Exception: # Some backends (e.g. m
{ "filepath": "django/contrib/sessions/backends/cache.py", "language": "python", "file_size": 4674, "cut_index": 614, "middle_length": 229 }
django.db import DatabaseError, IntegrityError, router, transaction from django.utils import timezone from django.utils.functional import cached_property class SessionStore(SessionBase): """ Implement database session store. """ def __init__(self, session_key=None): super().__init__(session_k...
lf.model.objects.get( session_key=self.session_key, expire_date__gt=timezone.now() ) except (self.model.DoesNotExist, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger =
from django.contrib.sessions.models import Session return Session @cached_property def model(self): return self.get_model_class() def _get_session_from_db(self): try: return se
{ "filepath": "django/contrib/sessions/backends/db.py", "language": "python", "file_size": 6907, "cut_index": 716, "middle_length": 229 }
SessionStore(SessionBase): def load(self): """ Load the data from the key itself instead of fetching from some external data store. Opposite of _get_session_key(), raise BadSignature if signature fails. """ try: return signing.loads( self.s...
self.create() return {} async def aload(self): return self.load() def create(self): """ To create a new key, set the modified flag so that the cookie is set on the client for the current request
salt="django.contrib.sessions.backends.signed_cookies", ) except Exception: # BadSignature, ValueError, or unpickling exceptions. If any of # these happen, reset the session.
{ "filepath": "django/contrib/sessions/backends/signed_cookies.py", "language": "python", "file_size": 3218, "cut_index": 614, "middle_length": 229 }
ngo.views.decorators.debug import sensitive_variables from .signals import user_logged_in, user_logged_out, user_login_failed SESSION_KEY = "_auth_user_id" BACKEND_SESSION_KEY = "_auth_user_backend" HASH_SESSION_KEY = "_auth_user_hash" REDIRECT_FIELD_NAME = "next" def load_backend(path): return import_string(pa...
ing?" ) return backends def get_backends(): return _get_backends(return_tuples=False) def _get_compatible_backends(request, **credentials): for backend, backend_path in _get_backends(return_tuples=True): backend_signature =
((backend, backend_path) if return_tuples else backend) if not backends: raise ImproperlyConfigured( "No authentication backends have been defined. Does " "AUTHENTICATION_BACKENDS contain anyth
{ "filepath": "django/contrib/auth/__init__.py", "language": "python", "file_size": 14635, "cut_index": 921, "middle_length": 229 }
ray import ArrayField from django.contrib.postgres.utils import CheckPostgresInstalledMixin from django.core import exceptions from django.db.models import Field, TextField, Transform from django.db.models.fields.mixins import CheckFieldDefaultMixin from django.utils.translation import gettext_lazy as _ __all__ = ["HS...
name): transform = super().get_transform(name) if transform: return transform return KeyTransformFactory(name) def validate(self, value, model_instance): super().validate(value, model_instance) for k
t_error_messages = { "not_a_string": _("The value of “%(key)s” is not a string or null."), } _default_hint = ("dict", "{}") def db_type(self, connection): return "hstore" def get_transform(self,
{ "filepath": "django/contrib/postgres/fields/hstore.py", "language": "python", "file_size": 3387, "cut_index": 614, "middle_length": 229 }
jango.core.exceptions import PermissionDenied from django.db import router, transaction from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import path, reverse from django.utils.decorators import method_decorator from django.utils.html import esc...
, db_field, request=None, **kwargs): if db_field.name == "permissions": qs = kwargs.get("queryset", db_field.remote_field.model.objects) # Avoid a major performance hit resolving permission names which # triggers
import sensitive_post_parameters @admin.register(Group) class GroupAdmin(admin.ModelAdmin): search_fields = ("name",) ordering = ("name",) filter_horizontal = ("permissions",) def formfield_for_manytomany(self
{ "filepath": "django/contrib/auth/admin.py", "language": "python", "file_size": 10163, "cut_index": 921, "middle_length": 229 }
apps import AppConfig from django.core import checks from django.db.models.query_utils import DeferredAttribute from django.db.models.signals import post_migrate from django.utils.translation import gettext_lazy as _ from . import get_user_model from .checks import check_middleware, check_models_permissions, check_use...
tch_uid="django.contrib.auth.management.rename_permissions", ) post_migrate.connect( create_permissions, dispatch_uid="django.contrib.auth.management.create_permissions", ) last_login_field = getattr(
.models.AutoField" name = "django.contrib.auth" verbose_name = _("Authentication and Authorization") def ready(self): post_migrate.connect( rename_permissions_after_model_rename, dispa
{ "filepath": "django/contrib/auth/apps.py", "language": "python", "file_size": 1492, "cut_index": 524, "middle_length": 229 }
ist, return -1. """ cls = import_string(class_path) for index, path in enumerate(candidate_paths): try: candidate_cls = import_string(path) if issubclass(candidate_cls, cls): return index except (ImportError, TypeError): continue return...
against a set of app configs that don't # include the specified user model. In this case we simply don't # perform the checks defined below. return [] errors = [] # Check that REQUIRED_FIELDS is a list if
ER_MODEL.split(".") for app_config in app_configs: if app_config.label == app_label: cls = app_config.get_model(model_name) break else: # Checks might be run
{ "filepath": "django/contrib/auth/checks.py", "language": "python", "file_size": 9780, "cut_index": 921, "middle_length": 229 }
ort Aggregate, FloatField, IntegerField __all__ = [ "CovarPop", "Corr", "RegrAvgX", "RegrAvgY", "RegrCount", "RegrIntercept", "RegrR2", "RegrSlope", "RegrSXX", "RegrSXY", "RegrSYY", "StatAggregate", ] class StatAggregate(Aggregate): output_field = FloatField() ...
t=None): self.function = "COVAR_SAMP" if sample else "COVAR_POP" super().__init__(y, x, filter=filter, default=default) class RegrAvgX(StatAggregate): function = "REGR_AVGX" class RegrAvgY(StatAggregate): function = "REGR_AVGY"
y, x, output_field=output_field, filter=filter, default=default ) class Corr(StatAggregate): function = "CORR" class CovarPop(StatAggregate): def __init__(self, y, x, sample=False, filter=None, defaul
{ "filepath": "django/contrib/postgres/aggregates/statistics.py", "language": "python", "file_size": 1511, "cut_index": 537, "middle_length": 229 }
itive file systems. VALID_KEY_CHARS = string.ascii_lowercase + string.digits class CreateError(Exception): """ Used internally as a consistent exception type to catch from save (see the docstring for SessionBase.save() for details). """ pass class UpdateError(Exception): """ Occurs if D...
ring(settings.SESSION_SERIALIZER) def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value se
OOKIE_VALUE = "worked" __not_given = object() def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False self.serializer = import_st
{ "filepath": "django/contrib/sessions/backends/base.py", "language": "python", "file_size": 17040, "cut_index": 921, "middle_length": 229 }
onBase, UpdateError, ) from django.contrib.sessions.exceptions import InvalidSessionKey from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation class SessionStore(SessionBase): """ Implement a file based session store. """ def __init__(self, session_key=None): self.st...
torage path is valid. if not os.path.isdir(storage_path): raise ImproperlyConfigured( "The session storage path %r doesn't exist. Please set your" " SESSION_FILE_PATH setting to an existin
y: return cls._storage_path except AttributeError: storage_path = ( getattr(settings, "SESSION_FILE_PATH", None) or tempfile.gettempdir() ) # Make sure the s
{ "filepath": "django/contrib/sessions/backends/file.py", "language": "python", "file_size": 8188, "cut_index": 716, "middle_length": 229 }
django.contrib.sessions.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="Session", fields=[ ( "session_key", models.Cha...
ate", db_index=True), ), ], options={ "abstract": False, "db_table": "django_session", "verbose_name": "session", "verbose_name_plural": "sessions",
), ), ("session_data", models.TextField(verbose_name="session data")), ( "expire_date", models.DateTimeField(verbose_name="expire d
{ "filepath": "django/contrib/sessions/migrations/0001_initial.py", "language": "python", "file_size": 1148, "cut_index": 518, "middle_length": 229 }
def authenticate(self, request, **kwargs): return None async def aauthenticate(self, request, **kwargs): return await sync_to_async(self.authenticate)(request, **kwargs) def get_user(self, user_id): return None async def aget_user(self, user_id): return await sync_to_a...
async(self.get_group_permissions)(user_obj, obj) def get_all_permissions(self, user_obj, obj=None): return { *self.get_user_permissions(user_obj, obj=obj), *self.get_group_permissions(user_obj, obj=obj), }
sync_to_async(self.get_user_permissions)(user_obj, obj) def get_group_permissions(self, user_obj, obj=None): return set() async def aget_group_permissions(self, user_obj, obj=None): return await sync_to_
{ "filepath": "django/contrib/auth/backends.py", "language": "python", "file_size": 12899, "cut_index": 921, "middle_length": 229 }
kupDict proxy the permissions system into objects that # the template system can understand. class PermLookupDict: def __init__(self, user, app_label): self.user, self.app_label = user, app_label def __repr__(self): return str(self.user.get_all_permissions()) def __getitem__(self, perm_n...
user): self.user = user def __repr__(self): return f"{self.__class__.__qualname__}({self.user!r})" def __getitem__(self, app_label): return PermLookupDict(self.user, app_label) def __iter__(self): # I am large
# define __iter__. See #18979 for details. raise TypeError("PermLookupDict is not iterable.") def __bool__(self): return self.user.has_module_perms(self.app_label) class PermWrapper: def __init__(self,
{ "filepath": "django/contrib/auth/context_processors.py", "language": "python", "file_size": 1911, "cut_index": 537, "middle_length": 229 }
sessions.backends.base import UpdateError from django.contrib.sessions.exceptions import SessionInterrupted from django.utils.cache import patch_vary_headers from django.utils.deprecation import MiddlewareMixin from django.utils.http import http_date class SessionMiddleware(MiddlewareMixin): def __init__(self, ge...
modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.acc
st): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was
{ "filepath": "django/contrib/sessions/middleware.py", "language": "python", "file_size": 3755, "cut_index": 614, "middle_length": 229 }
o.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import caches KEY_PREFIX = "django.contrib.sessions.cached_db" logger = logging.getLogger("django.contrib.sessions") class SessionStore(DBStore): """ Implement cached, database backed sessions. """ cache_key_prefix...
data = self._cache.get(self.cache_key) except Exception: # Some backends (e.g. memcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. data = None if da
: return self.cache_key_prefix + self._get_or_create_session_key() async def acache_key(self): return self.cache_key_prefix + await self._aget_or_create_session_key() def load(self): try:
{ "filepath": "django/contrib/sessions/backends/cached_db.py", "language": "python", "file_size": 4148, "cut_index": 614, "middle_length": 229 }
PS. """ import unicodedata from django.conf import settings from django.contrib.auth import password_validation from django.contrib.auth.hashers import ( acheck_password, check_password, is_password_usable, make_password, ) from django.db import models from django.utils.crypto import salted_hmac from ...
email = email_name + "@" + domain_part.lower() return email def get_by_natural_key(self, username): return self.get(**{self.model.USERNAME_FIELD: username}) async def aget_by_natural_key(self, username): return await self.
by lowercasing the domain part of it. """ email = email or "" try: email_name, domain_part = email.strip().rsplit("@", 1) except ValueError: pass else:
{ "filepath": "django/contrib/auth/base_user.py", "language": "python", "file_size": 4893, "cut_index": 614, "middle_length": 229 }
db.models import CharField, EmailField, TextField __all__ = ["CICharField", "CIEmailField", "CITextField"] class CICharField(CharField): system_check_removed_details = { "msg": ( "django.contrib.postgres.fields.CICharField is removed except for support " "in historical migrations....
), "hint": ( 'Use EmailField(db_collation="…") with a case-insensitive ' "non-deterministic collation instead." ), "id": "fields.E906", } class CITextField(TextField): system_check_removed_detail
} class CIEmailField(EmailField): system_check_removed_details = { "msg": ( "django.contrib.postgres.fields.CIEmailField is removed except for support " "in historical migrations."
{ "filepath": "django/contrib/postgres/fields/citext.py", "language": "python", "file_size": 1363, "cut_index": 524, "middle_length": 229 }
om .utils import AttributeSetter __all__ = [ "RangeField", "IntegerRangeField", "BigIntegerRangeField", "DecimalRangeField", "DateTimeRangeField", "DateRangeField", "RangeBoundary", "RangeOperators", ] class RangeBoundary(models.Expression): """A class that represents range bounda...
_EQUAL = "<>" CONTAINS = "@>" CONTAINED_BY = "<@" OVERLAPS = "&&" FULLY_LT = "<<" FULLY_GT = ">>" NOT_LT = "&>" NOT_GT = "&<" ADJACENT_TO = "-|-" class RangeField(CheckPostgresInstalledMixin, models.Field): empty_strin
f as_sql(self, compiler, connection): return "'%s%s'" % (self.lower, self.upper), [] class RangeOperators: # https://www.postgresql.org/docs/current/functions-range.html#RANGE-OPERATORS-TABLE EQUAL = "=" NOT
{ "filepath": "django/contrib/postgres/fields/ranges.py", "language": "python", "file_size": 11682, "cut_index": 921, "middle_length": 229 }
(encoded): """ Return True if this password wasn't generated by User.set_unusable_password(), i.e. make_password(None). """ return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX) def verify_password(password, encoded, preferred="default"): """ Return two booleans. The f...
True if fake_runtime: # Run the default password hasher once to reduce the timing difference # between an existing user with an unusable password and a nonexistent # user or missing hasher (similar to #20760). make_pas
d_usable(encoded) preferred = get_hasher(preferred) try: hasher = identify_hasher(encoded) except ValueError: # encoded is gibberish or uses a hasher that's no longer installed. fake_runtime =
{ "filepath": "django/contrib/auth/hashers.py", "language": "python", "file_size": 23765, "cut_index": 1331, "middle_length": 229 }
DIRECT_FIELD_NAME from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.shortcuts import resolve_url class AccessMixin: """ Abstract CBV mixin that gives access mixins the same customizable functionality. """ ...
ng the login_url attribute. Define " f"{self.__class__.__name__}.login_url, settings.LOGIN_URL, or override " f"{self.__class__.__name__}.get_login_url()." ) return str(login_url) def get_permission_
thod to override the login_url attribute. """ login_url = self.login_url or settings.LOGIN_URL if not login_url: raise ImproperlyConfigured( f"{self.__class__.__name__} is missi
{ "filepath": "django/contrib/auth/mixins.py", "language": "python", "file_size": 4660, "cut_index": 614, "middle_length": 229 }
tring from django.utils.translation import gettext as _ from django.utils.translation import ngettext @functools.cache def get_default_password_validators(): return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) def get_password_validators(validator_config): validators = [] for validator in ...
tors def validate_password(password, user=None, password_validators=None): """ Validate that the password meets all validator requirements. If the password is valid, return ``None``. If the password is invalid, raise ValidationError with
s. Check your " "AUTH_PASSWORD_VALIDATORS setting." ) raise ImproperlyConfigured(msg % validator["NAME"]) validators.append(klass(**validator.get("OPTIONS", {}))) return valida
{ "filepath": "django/contrib/auth/password_validation.py", "language": "python", "file_size": 9635, "cut_index": 921, "middle_length": 229 }
views used below are normally mapped in the AdminSite instance. # This URLs file is used to provide a reliable view deployment for test # purposes. It is also provided as a convenience to those who want to deploy # these URLs elsewhere. from django.contrib.auth import views from django.urls import path urlpatterns = ...
view(), name="password_reset"), path( "password_reset/done/", views.PasswordResetDoneView.as_view(), name="password_reset_done", ), path( "reset/<uidb64>/<token>/", views.PasswordResetConfirmView.as_view(
_view(), name="password_change" ), path( "password_change/done/", views.PasswordChangeDoneView.as_view(), name="password_change_done", ), path("password_reset/", views.PasswordResetView.as_
{ "filepath": "django/contrib/auth/urls.py", "language": "python", "file_size": 1185, "cut_index": 518, "middle_length": 229 }
m django.contrib import auth UserModel = auth.get_user_model() def _get_user(username): """ Return the UserModel instance for `username`. If no matching user exists, or if the user is inactive, return None. """ try: user = UserModel._default_manager.get_by_natural_key(username) excep...
user exists but password is not correct, and return True otherwise. """ # db connection state is managed similarly to the wsgi handler # as mod_wsgi may call these functions outside of a request/response cycle db.reset_queries() tr
thenticate against Django's auth database. mod_wsgi docs specify None, True, False as return value depending on whether the user exists and authenticates. Return None if the user does not exist, return False if the
{ "filepath": "django/contrib/auth/handlers/modwsgi.py", "language": "python", "file_size": 1634, "cut_index": 537, "middle_length": 229 }
_user_model from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections UserModel = get_user_model() class Command(BaseCommand): help ...
=( "Username to change password for; by default, it's the current " "username." ), ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(
etpass(prompt=prompt) if not p: raise CommandError("aborted") return p def add_arguments(self, parser): parser.add_argument( "username", nargs="?", help
{ "filepath": "django/contrib/auth/management/commands/changepassword.py", "language": "python", "file_size": 2686, "cut_index": 563, "middle_length": 229 }
ncies = [ ("contenttypes", "__first__"), ] operations = [ migrations.CreateModel( name="Permission", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=Fa...
verbose_name="content type", ), ), ("codename", models.CharField(max_length=100, verbose_name="codename")), ], options={ "ordering": [
bose_name="name")), ( "content_type", models.ForeignKey( to="contenttypes.ContentType", on_delete=models.CASCADE,
{ "filepath": "django/contrib/auth/migrations/0001_initial.py", "language": "python", "file_size": 7281, "cut_index": 716, "middle_length": 229 }
django.contrib.auth import validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0006_require_contenttypes_0002"), ] operations = [ migrations.AlterField( model_name="user", name="username", ...
digits and @/./+/-/_ " "only." ), max_length=30, unique=True, validators=[validators.UnicodeUsernameValidator()], verbose_name="username", ),
wer. Letters,
{ "filepath": "django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py", "language": "python", "file_size": 802, "cut_index": 517, "middle_length": 14 }
t color_style from django.db import IntegrityError, migrations, transaction from django.db.models import Q WARNING = """ A problem arose migrating proxy model permissions for {old} to {new}. Permission(s) for {new} already existed. Codenames Q: {query} Ensure to audit ALL permissions for {old} an...
els(): opts = Model._meta if not opts.proxy: continue proxy_default_permissions_codenames = [ "%s_%s" % (action, opts.model_name) for action in opts.default_permissions ] permissions_query = Q
del. """ style = color_style() Permission = apps.get_model("auth", "Permission") ContentType = apps.get_model("contenttypes", "ContentType") alias = schema_editor.connection.alias for Model in apps.get_mod
{ "filepath": "django/contrib/auth/migrations/0011_update_proxy_permissions.py", "language": "python", "file_size": 2860, "cut_index": 563, "middle_length": 229 }
age __all__ = ( "add_message", "get_messages", "get_level", "set_level", "debug", "info", "success", "warning", "error", "MessageFailure", ) class MessageFailure(Exception): pass def add_message(request, level, message, extra_tags="", fail_silently=False): """ At...
( "You cannot add messages without installing " "django.contrib.messages.middleware.MessageMiddleware" ) else: return messages.add(level, message, extra_tags) def get_messages(request): """
raise TypeError( "add_message() argument must be an HttpRequest object, not " "'%s'." % request.__class__.__name__ ) if not fail_silently: raise MessageFailure
{ "filepath": "django/contrib/messages/api.py", "language": "python", "file_size": 3250, "cut_index": 614, "middle_length": 229 }
age: """ Represent an actual message that can be stored in any of the supported storage classes (typically session- or cookie-based) and rendered in a view or template. """ def __init__(self, level, message, extra_tags=None): self.level = int(level) self.message = message ...
e): return NotImplemented return self.level == other.level and self.message == other.message def __str__(self): return str(self.message) def __repr__(self): extra_tags = f", extra_tags={self.extra_tags!r}" if s
lazy translations. """ self.message = str(self.message) self.extra_tags = str(self.extra_tags) if self.extra_tags is not None else None def __eq__(self, other): if not isinstance(other, Messag
{ "filepath": "django/contrib/messages/storage/base.py", "language": "python", "file_size": 6082, "cut_index": 716, "middle_length": 229 }
ger("django.contrib.auth") def _unicode_ci_compare(s1, s2): """ Perform case-insensitive comparison of two identifiers, using the recommended algorithm from Unicode Technical Report 36, section 2.11.2(B)(2). """ return ( unicodedata.normalize("NFKC", s1).casefold() == unicodeda...
e_password else _("Set password") ) return context def id_for_label(self, id_): return None class ReadOnlyPasswordHashField(forms.Field): widget = ReadOnlyPasswordHashWidget def __init__(self, *args, **kwargs):
ue, attrs): context = super().get_context(name, value, attrs) usable_password = value and not value.startswith(UNUSABLE_PASSWORD_PREFIX) context["button_label"] = ( _("Reset password") if usabl
{ "filepath": "django/contrib/auth/forms.py", "language": "python", "file_size": 20800, "cut_index": 1331, "middle_length": 229 }