hash
stringlengths
64
64
content
stringlengths
0
1.51M
d9e4ec5b459141b5d5d4678e3cb5fbe91305bfa190a881ae66cd741854fb578f
import json from django.conf import settings from django.contrib.admin.utils import quote from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import NoReverseMatch, 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")), (DELETION, _("Deletion")), ) class LogEntryManager(models.Manager): use_in_migrations = True def log_action( self, user_id, content_type_id, object_id, object_repr, action_flag, change_message="", ): if isinstance(change_message, list): change_message = json.dumps(change_message) return self.model.objects.create( user_id=user_id, content_type_id=content_type_id, object_id=str(object_id), object_repr=object_repr[:200], action_flag=action_flag, change_message=change_message, ) class LogEntry(models.Model): action_time = models.DateTimeField( _("action time"), default=timezone.now, editable=False, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, models.CASCADE, verbose_name=_("user"), ) content_type = models.ForeignKey( ContentType, models.SET_NULL, verbose_name=_("content type"), blank=True, null=True, ) object_id = models.TextField(_("object id"), blank=True, null=True) # Translators: 'repr' means representation # (https://docs.python.org/library/functions.html#repr) object_repr = models.CharField(_("object repr"), max_length=200) action_flag = models.PositiveSmallIntegerField( _("action flag"), choices=ACTION_FLAG_CHOICES ) # change_message is either a string or a JSON structure change_message = models.TextField(_("change message"), blank=True) objects = LogEntryManager() class Meta: verbose_name = _("log entry") verbose_name_plural = _("log entries") db_table = "django_admin_log" ordering = ["-action_time"] def __repr__(self): return str(self.action_time) def __str__(self): if self.is_addition(): return gettext("Added “%(object)s”.") % {"object": self.object_repr} elif self.is_change(): return gettext("Changed “%(object)s” — %(changes)s") % { "object": self.object_repr, "changes": self.get_change_message(), } elif self.is_deletion(): return gettext("Deleted “%(object)s.”") % {"object": self.object_repr} return gettext("LogEntry Object") def is_addition(self): return self.action_flag == ADDITION def is_change(self): return self.action_flag == CHANGE def is_deletion(self): return self.action_flag == DELETION def get_change_message(self): """ If self.change_message is a JSON structure, interpret it as a change string, properly translated. """ if self.change_message and self.change_message[0] == "[": try: change_message = json.loads(self.change_message) except json.JSONDecodeError: return self.change_message messages = [] for sub_message in change_message: if "added" in sub_message: if sub_message["added"]: sub_message["added"]["name"] = gettext( sub_message["added"]["name"] ) messages.append( gettext("Added {name} “{object}”.").format( **sub_message["added"] ) ) else: messages.append(gettext("Added.")) elif "changed" in sub_message: sub_message["changed"]["fields"] = get_text_list( [ gettext(field_name) for field_name in sub_message["changed"]["fields"] ], gettext("and"), ) if "name" in sub_message["changed"]: sub_message["changed"]["name"] = gettext( sub_message["changed"]["name"] ) messages.append( gettext("Changed {fields} for {name} “{object}”.").format( **sub_message["changed"] ) ) else: messages.append( gettext("Changed {fields}.").format( **sub_message["changed"] ) ) elif "deleted" in sub_message: sub_message["deleted"]["name"] = gettext( sub_message["deleted"]["name"] ) messages.append( gettext("Deleted {name} “{object}”.").format( **sub_message["deleted"] ) ) change_message = " ".join(msg[0].upper() + msg[1:] for msg in messages) return change_message or gettext("No fields changed.") else: return self.change_message def get_edited_object(self): """Return the edited object represented by this log entry.""" return self.content_type.get_object_for_this_type(pk=self.object_id) def get_admin_url(self): """ Return the admin URL to edit the object represented by this log entry. """ if self.content_type and self.object_id: url_name = "admin:%s_%s_change" % ( self.content_type.app_label, self.content_type.model, ) try: return reverse(url_name, args=(quote(self.object_id),)) except NoReverseMatch: pass return None
d033a6a8ae24c74fa572df162c758229543e98b0cf1c38efb7276a8e4a2bdf4d
import copy import json import re from functools import partial, update_wrapper from urllib.parse import quote as urlquote from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import helpers, widgets from django.contrib.admin.checks import ( BaseModelAdminChecks, InlineModelAdminChecks, ModelAdminChecks, ) from django.contrib.admin.decorators import display from django.contrib.admin.exceptions import DisallowedModelAdminToField from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.utils import ( NestedObjects, construct_change_message, flatten_fieldsets, get_deleted_objects, lookup_spawns_duplicates, model_format_dict, model_ngettext, quote, unquote, ) from django.contrib.admin.widgets import AutocompleteSelect, AutocompleteSelectMultiple from django.contrib.auth import get_permission_codename from django.core.exceptions import ( FieldDoesNotExist, FieldError, PermissionDenied, ValidationError, ) from django.core.paginator import Paginator from django.db import models, router, transaction from django.db.models.constants import LOOKUP_SEP from django.forms.formsets import DELETION_FIELD_NAME, all_valid from django.forms.models import ( BaseInlineFormSet, inlineformset_factory, modelform_defines_fields, modelform_factory, modelformset_factory, ) from django.forms.widgets import CheckboxSelectMultiple, SelectMultiple from django.http import HttpResponseRedirect from django.http.response import HttpResponseBase from django.template.response import SimpleTemplateResponse, TemplateResponse from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.html import format_html from django.utils.http import urlencode from django.utils.safestring import mark_safe from django.utils.text import ( capfirst, format_lazy, get_text_list, smart_split, unescape_string_literal, ) from django.utils.translation import gettext as _ from django.utils.translation import ngettext from django.views.decorators.csrf import csrf_protect from django.views.generic import RedirectView IS_POPUP_VAR = "_popup" TO_FIELD_VAR = "_to_field" HORIZONTAL, VERTICAL = 1, 2 def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot 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" if radio_style == VERTICAL else "radiolist inline" class IncorrectLookupParameters(Exception): pass # Defaults for formfield_overrides. ModelAdmin subclasses can change this # by adding to ModelAdmin.formfield_overrides. FORMFIELD_FOR_DBFIELD_DEFAULTS = { models.DateTimeField: { "form_class": forms.SplitDateTimeField, "widget": widgets.AdminSplitDateTime, }, models.DateField: {"widget": widgets.AdminDateWidget}, models.TimeField: {"widget": widgets.AdminTimeWidget}, models.TextField: {"widget": widgets.AdminTextareaWidget}, models.URLField: {"widget": widgets.AdminURLFieldWidget}, models.IntegerField: {"widget": widgets.AdminIntegerFieldWidget}, models.BigIntegerField: {"widget": widgets.AdminBigIntegerFieldWidget}, models.CharField: {"widget": widgets.AdminTextInputWidget}, models.ImageField: {"widget": widgets.AdminFileWidget}, models.FileField: {"widget": widgets.AdminFileWidget}, models.EmailField: {"widget": widgets.AdminEmailInputWidget}, models.UUIDField: {"widget": widgets.AdminUUIDInputWidget}, } csrf_protect_m = method_decorator(csrf_protect) class BaseModelAdmin(metaclass=forms.MediaDefiningClass): """Functionality common to both ModelAdmin and InlineAdmin.""" autocomplete_fields = () raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} prepopulated_fields = {} formfield_overrides = {} readonly_fields = () ordering = None sortable_by = None view_on_site = True show_full_result_count = True checks_class = BaseModelAdminChecks def check(self, **kwargs): return self.checks_class().check(self, **kwargs) def __init__(self): # Merge FORMFIELD_FOR_DBFIELD_DEFAULTS with the formfield_overrides # rather than simply overwriting. overrides = copy.deepcopy(FORMFIELD_FOR_DBFIELD_DEFAULTS) for k, v in self.formfield_overrides.items(): overrides.setdefault(k, {}).update(v) self.formfield_overrides = overrides def formfield_for_dbfield(self, db_field, request, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. """ # If the field specifies choices, we don't need to look for special # admin widgets - we just need to use a select widget of some kind. if db_field.choices: return self.formfield_for_choice_field(db_field, request, **kwargs) # ForeignKey or ManyToManyFields if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # Combine the field kwargs with any options for formfield_overrides. # Make sure the passed in **kwargs override anything in # formfield_overrides because **kwargs is more specific, and should # always win. if db_field.__class__ in self.formfield_overrides: kwargs = {**self.formfield_overrides[db_field.__class__], **kwargs} # Get the correct formfield. if isinstance(db_field, models.ForeignKey): formfield = self.formfield_for_foreignkey(db_field, request, **kwargs) elif isinstance(db_field, models.ManyToManyField): formfield = self.formfield_for_manytomany(db_field, request, **kwargs) # For non-raw_id fields, wrap the widget with a wrapper that adds # extra HTML -- the "add other" interface -- to the end of the # rendered output. formfield can be None if it came from a # OneToOneField with parent_link=True or a M2M intermediary. if formfield and db_field.name not in self.raw_id_fields: related_modeladmin = self.admin_site._registry.get( db_field.remote_field.model ) wrapper_kwargs = {} if related_modeladmin: wrapper_kwargs.update( can_add_related=related_modeladmin.has_add_permission(request), can_change_related=related_modeladmin.has_change_permission( request ), can_delete_related=related_modeladmin.has_delete_permission( request ), can_view_related=related_modeladmin.has_view_permission( request ), ) formfield.widget = widgets.RelatedFieldWidgetWrapper( formfield.widget, db_field.remote_field, self.admin_site, **wrapper_kwargs, ) return formfield # If we've got overrides for the formfield defined, use 'em. **kwargs # passed to formfield_for_dbfield override the defaults. for klass in db_field.__class__.mro(): if klass in self.formfield_overrides: kwargs = {**copy.deepcopy(self.formfield_overrides[klass]), **kwargs} return db_field.formfield(**kwargs) # For any other type of field, just call its formfield() method. return db_field.formfield(**kwargs) def formfield_for_choice_field(self, db_field, request, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name in self.radio_fields: # Avoid stomping on custom widget/choices arguments. if "widget" not in kwargs: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) if "choices" not in kwargs: kwargs["choices"] = db_field.get_choices( include_blank=db_field.blank, blank_choice=[("", _("None"))] ) return db_field.formfield(**kwargs) def get_field_queryset(self, db, db_field, request): """ If the ModelAdmin specifies ordering, the queryset should respect that ordering. Otherwise don't specify the queryset, let the field decide (return None in that case). """ related_admin = self.admin_site._registry.get(db_field.remote_field.model) if related_admin is not None: ordering = related_admin.get_ordering(request) if ordering is not None and ordering != (): return db_field.remote_field.model._default_manager.using(db).order_by( *ordering ) return None def formfield_for_foreignkey(self, db_field, request, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get("using") if "widget" not in kwargs: if db_field.name in self.get_autocomplete_fields(request): kwargs["widget"] = AutocompleteSelect( db_field, self.admin_site, using=db ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ForeignKeyRawIdWidget( db_field.remote_field, self.admin_site, using=db ) elif db_field.name in self.radio_fields: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) kwargs["empty_label"] = _("None") if db_field.blank else None if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset return db_field.formfield(**kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get("using") if "widget" not in kwargs: autocomplete_fields = self.get_autocomplete_fields(request) if db_field.name in autocomplete_fields: kwargs["widget"] = AutocompleteSelectMultiple( db_field, self.admin_site, using=db, ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ManyToManyRawIdWidget( db_field.remote_field, self.admin_site, using=db, ) elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]: kwargs["widget"] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset form_field = db_field.formfield(**kwargs) if isinstance(form_field.widget, SelectMultiple) and not isinstance( form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple) ): msg = _( "Hold down “Control”, or “Command” on a Mac, to select more than one." ) help_text = form_field.help_text form_field.help_text = ( format_lazy("{} {}", help_text, msg) if help_text else msg ) return form_field def get_autocomplete_fields(self, request): """ Return a list of ForeignKey and/or ManyToMany fields which should use an autocomplete widget. """ return self.autocomplete_fields def get_view_on_site_url(self, obj=None): if obj is None or not self.view_on_site: return None if callable(self.view_on_site): return self.view_on_site(obj) elif hasattr(obj, "get_absolute_url"): # use the ContentType lookup if view_on_site is True return reverse( "admin:view_on_site", kwargs={ "content_type_id": get_content_type_for_model(obj).pk, "object_id": obj.pk, }, ) def get_empty_value_display(self): """ Return the empty_value_display set on ModelAdmin or AdminSite. """ try: return mark_safe(self.empty_value_display) except AttributeError: return mark_safe(self.admin_site.empty_value_display) def get_exclude(self, request, obj=None): """ Hook for specifying exclude. """ return self.exclude def get_fields(self, request, obj=None): """ Hook for specifying fields. """ if self.fields: return self.fields # _get_form_for_get_fields() is implemented in subclasses. form = self._get_form_for_get_fields(request, obj) return [*form.base_fields, *self.get_readonly_fields(request, obj)] def get_fieldsets(self, request, obj=None): """ Hook for specifying fieldsets. """ if self.fieldsets: return self.fieldsets return [(None, {"fields": self.get_fields(request, obj)})] def get_inlines(self, request, obj): """Hook for specifying custom inlines.""" return self.inlines def get_ordering(self, request): """ Hook for specifying field ordering. """ return self.ordering or () # otherwise we might try to *None, which is bad ;) def get_readonly_fields(self, request, obj=None): """ Hook for specifying custom readonly fields. """ return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): """ Hook for specifying custom prepopulated fields. """ return self.prepopulated_fields def get_queryset(self, request): """ Return a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() # TODO: this should be handled by some parameter to the ChangeList. ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs def get_sortable_by(self, request): """Hook for specifying which fields can be sorted in the changelist.""" return ( self.sortable_by if self.sortable_by is not None else self.get_list_display(request) ) def lookup_allowed(self, lookup, value): from django.contrib.admin.filters import SimpleListFilter model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for fk_lookup in model._meta.related_fkey_lookups: # As ``limit_choices_to`` can be a callable, invoke it here. if callable(fk_lookup): fk_lookup = fk_lookup() if (lookup, value) in widgets.url_params_from_lookup_dict( fk_lookup ).items(): return True relation_parts = [] prev_field = None for part in lookup.split(LOOKUP_SEP): try: field = model._meta.get_field(part) except FieldDoesNotExist: # Lookups on nonexistent fields are ok, since they're ignored # later. break # It is allowed to filter on values that would be found from local # model anyways. For example, if you filter on employee__department__id, # then the id value would be found already from employee__department_id. if not prev_field or ( prev_field.is_relation and field not in prev_field.path_infos[-1].target_fields ): relation_parts.append(part) if not getattr(field, "path_infos", None): # This is not a relational field, so further parts # must be transforms. break prev_field = field model = field.path_infos[-1].to_opts.model if len(relation_parts) <= 1: # Either a local field filter, or no fields at all. return True valid_lookups = {self.date_hierarchy} for filter_item in self.list_filter: if isinstance(filter_item, type) and issubclass( filter_item, SimpleListFilter ): valid_lookups.add(filter_item.parameter_name) elif isinstance(filter_item, (list, tuple)): valid_lookups.add(filter_item[0]) else: valid_lookups.add(filter_item) # Is it a valid relational lookup? return not { LOOKUP_SEP.join(relation_parts), LOOKUP_SEP.join(relation_parts + [part]), }.isdisjoint(valid_lookups) def to_field_allowed(self, request, to_field): """ Return True if the model associated with this admin should be allowed to be referenced by the specified field. """ opts = self.model._meta try: field = opts.get_field(to_field) except FieldDoesNotExist: return False # Always allow referencing the primary key since it's already possible # to get this information from the change view URL. if field.primary_key: return True # Allow reverse relationships to models defining m2m fields if they # target the specified field. for many_to_many in opts.many_to_many: if many_to_many.m2m_target_field_name() == to_field: return True # Make sure at least one of the models registered for this site # references this field through a FK or a M2M relationship. registered_models = set() for model, admin in self.admin_site._registry.items(): registered_models.add(model) for inline in admin.inlines: registered_models.add(inline.model) related_objects = ( f for f in opts.get_fields(include_hidden=True) if (f.auto_created and not f.concrete) ) for related_object in related_objects: related_model = related_object.related_model remote_field = related_object.field.remote_field if ( any(issubclass(model, related_model) for model in registered_models) and hasattr(remote_field, "get_related_field") and remote_field.get_related_field() == field ): return True return False def has_add_permission(self, request): """ Return True if the given request has permission to add an object. Can be overridden by the user in subclasses. """ opts = self.opts codename = get_permission_codename("add", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_change_permission(self, request, obj=None): """ Return True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to change the `obj` model instance. If `obj` is None, this should return True if the given request has permission to change *any* object of the given type. """ opts = self.opts codename = get_permission_codename("change", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): """ Return True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* object of the given type. """ opts = self.opts codename = get_permission_codename("delete", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_view_permission(self, request, obj=None): """ Return True if the given request has permission to view the given Django model instance. The default implementation doesn't examine the `obj` parameter. If overridden by the user in subclasses, it should return True if the given request has permission to view the `obj` model instance. If `obj` is None, it should return True if the request has permission to view any object of the given type. """ opts = self.opts codename_view = get_permission_codename("view", opts) codename_change = get_permission_codename("change", opts) return request.user.has_perm( "%s.%s" % (opts.app_label, codename_view) ) or request.user.has_perm("%s.%s" % (opts.app_label, codename_change)) def has_view_or_change_permission(self, request, obj=None): return self.has_view_permission(request, obj) or self.has_change_permission( request, obj ) def has_module_permission(self, request): """ Return True if the given request has any permission in the given app label. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to view the module on the admin index page and access the module's index page. Overriding it does not restrict access to the add, change or delete views. Use `ModelAdmin.has_(add|change|delete)_permission` for that. """ return request.user.has_module_perms(self.opts.app_label) class ModelAdmin(BaseModelAdmin): """Encapsulate all admin options and functionality for a given model.""" list_display = ("__str__",) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_max_show_all = 200 list_editable = () search_fields = () search_help_text = None date_hierarchy = None save_as = False save_as_continue = True save_on_top = False paginator = Paginator preserve_filters = True inlines = () # Custom templates (designed to be over-ridden in subclasses) add_form_template = None change_form_template = None change_list_template = None delete_confirmation_template = None delete_selected_confirmation_template = None object_history_template = None popup_response_template = None # Actions actions = () action_form = helpers.ActionForm actions_on_top = True actions_on_bottom = False actions_selection_counter = True checks_class = ModelAdminChecks def __init__(self, model, admin_site): self.model = model self.opts = model._meta self.admin_site = admin_site super().__init__() def __str__(self): return "%s.%s" % (self.model._meta.app_label, self.__class__.__name__) def __repr__(self): return ( f"<{self.__class__.__qualname__}: model={self.model.__qualname__} " f"site={self.admin_site!r}>" ) def get_inline_instances(self, request, obj=None): inline_instances = [] for inline_class in self.get_inlines(request, obj): inline = inline_class(self.model, self.admin_site) if request: if not ( inline.has_view_or_change_permission(request, obj) or inline.has_add_permission(request, obj) or inline.has_delete_permission(request, obj) ): continue if not inline.has_add_permission(request, obj): inline.max_num = 0 inline_instances.append(inline) return inline_instances def get_urls(self): from django.urls import path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) wrapper.model_admin = self return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.model_name return [ path("", wrap(self.changelist_view), name="%s_%s_changelist" % info), path("add/", wrap(self.add_view), name="%s_%s_add" % info), path( "<path:object_id>/history/", wrap(self.history_view), name="%s_%s_history" % info, ), path( "<path:object_id>/delete/", wrap(self.delete_view), name="%s_%s_delete" % info, ), path( "<path:object_id>/change/", wrap(self.change_view), name="%s_%s_change" % info, ), # For backwards compatibility (was the change url before 1.9) path( "<path:object_id>/", wrap( RedirectView.as_view( pattern_name="%s:%s_%s_change" % ((self.admin_site.name,) + info) ) ), ), ] @property def urls(self): return self.get_urls() @property def media(self): extra = "" if settings.DEBUG else ".min" js = [ "vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "core.js", "admin/RelatedObjectLookups.js", "actions.js", "urlify.js", "prepopulate.js", "vendor/xregexp/xregexp%s.js" % extra, ] return forms.Media(js=["admin/js/%s" % url for url in js]) def get_model_perms(self, request): """ Return a dict of all perms for this model. This dict has the keys ``add``, ``change``, ``delete``, and ``view`` mapping to the True/False for each of those actions. """ return { "add": self.has_add_permission(request), "change": self.has_change_permission(request), "delete": self.has_delete_permission(request), "view": self.has_view_permission(request), } def _get_form_for_get_fields(self, request, obj): return self.get_form(request, obj, fields=None) def get_form(self, request, obj=None, change=False, **kwargs): """ Return a Form class for use in the admin add view. This is used by add_view and change_view. """ if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) readonly_fields = self.get_readonly_fields(request, obj) exclude.extend(readonly_fields) # Exclude all fields if it's a change form and the user doesn't have # the change permission. if ( change and hasattr(request, "user") and not self.has_change_permission(request, obj) ): exclude.extend(fields) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # ModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we pass None to be consistent with the # default on modelform_factory exclude = exclude or None # Remove declared form fields which are in readonly_fields. new_attrs = dict.fromkeys( f for f in readonly_fields if f in self.form.declared_fields ) form = type(self.form.__name__, (self.form,), new_attrs) defaults = { "form": form, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS try: return modelform_factory(self.model, **defaults) except FieldError as e: raise FieldError( "%s. Check fields/fieldsets/exclude attributes of class %s." % (e, self.__class__.__name__) ) def get_changelist(self, request, **kwargs): """ Return the ChangeList class for use on the changelist page. """ from django.contrib.admin.views.main import ChangeList return ChangeList def get_changelist_instance(self, request): """ Return a `ChangeList` instance based on `request`. May raise `IncorrectLookupParameters`. """ list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) # Add the action checkboxes if any actions are available. if self.get_actions(request): list_display = ["action_checkbox", *list_display] sortable_by = self.get_sortable_by(request) ChangeList = self.get_changelist(request) return ChangeList( request, self.model, list_display, list_display_links, self.get_list_filter(request), self.date_hierarchy, self.get_search_fields(request), self.get_list_select_related(request), self.list_per_page, self.list_max_show_all, self.list_editable, self, sortable_by, self.search_help_text, ) def get_object(self, request, object_id, from_field=None): """ Return an instance matching the field and value provided, the primary key is used if no field is provided. Return ``None`` if no match is found or the object_id fails validation. """ queryset = self.get_queryset(request) model = queryset.model field = ( model._meta.pk if from_field is None else model._meta.get_field(from_field) ) try: object_id = field.to_python(object_id) return queryset.get(**{field.name: object_id}) except (model.DoesNotExist, ValidationError, ValueError): return None def get_changelist_form(self, request, **kwargs): """ Return a Form class for use in the Formset on the changelist page. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults.get("fields") is None and not modelform_defines_fields( defaults.get("form") ): defaults["fields"] = forms.ALL_FIELDS return modelform_factory(self.model, **defaults) def get_changelist_formset(self, request, **kwargs): """ Return a FormSet class for use on the changelist page if list_editable is used. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } return modelformset_factory( self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults, ) def get_formsets_with_inlines(self, request, obj=None): """ Yield formsets and the corresponding inlines. """ for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj), inline def get_paginator( self, request, queryset, per_page, orphans=0, allow_empty_first_page=True ): return self.paginator(queryset, per_page, orphans, allow_empty_first_page) def log_addition(self, request, obj, message): """ Log that an object has been successfully added. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import ADDITION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=ADDITION, change_message=message, ) def log_change(self, request, obj, message): """ Log that an object has been successfully changed. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import CHANGE, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=CHANGE, change_message=message, ) def log_deletion(self, request, obj, object_repr): """ Log that an object will be deleted. Note that this method must be called before the deletion. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import DELETION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=object_repr, action_flag=DELETION, ) @display(description=mark_safe('<input type="checkbox" id="action-toggle">')) def action_checkbox(self, obj): """ A list_display column containing a checkbox widget. """ return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, str(obj.pk)) @staticmethod def _get_action_description(func, name): return getattr(func, "short_description", capfirst(name.replace("_", " "))) def _get_base_actions(self): """Return the list of actions, prior to any request-based filtering.""" actions = [] base_actions = (self.get_action(action) for action in self.actions or []) # get_action might have returned None, so filter any of those out. base_actions = [action for action in base_actions if action] base_action_names = {name for _, name, _ in base_actions} # Gather actions from the admin site first for (name, func) in self.admin_site.actions: if name in base_action_names: continue description = self._get_action_description(func, name) actions.append((func, name, description)) # Add actions from this ModelAdmin. actions.extend(base_actions) return actions def _filter_actions_by_permissions(self, request, actions): """Filter out any actions that the user doesn't have access to.""" filtered_actions = [] for action in actions: callable = action[0] if not hasattr(callable, "allowed_permissions"): filtered_actions.append(action) continue permission_checks = ( getattr(self, "has_%s_permission" % permission) for permission in callable.allowed_permissions ) if any(has_permission(request) for has_permission in permission_checks): filtered_actions.append(action) return filtered_actions def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is set to None that means actions are disabled on # this page. if self.actions is None or IS_POPUP_VAR in request.GET: return {} actions = self._filter_actions_by_permissions(request, self._get_base_actions()) return {name: (func, name, desc) for func, name, desc in actions} def get_action_choices(self, request, default_choices=models.BLANK_CHOICE_DASH): """ Return a list of choices for use in a form object. Each choice is a tuple (name, description). """ choices = [] + default_choices for func, name, description in self.get_actions(request).values(): choice = (name, description % model_format_dict(self.opts)) choices.append(choice) return choices def get_action(self, action): """ Return a given action from a parameter, which can either be a callable, or the name of a method on the ModelAdmin. Return is a tuple of (callable, name, description). """ # If the action is a callable, just use it. if callable(action): func = action action = action.__name__ # Next, look for a method. Grab it off self.__class__ to get an unbound # method instead of a bound one; this ensures that the calling # conventions are the same for functions and methods. elif hasattr(self.__class__, action): func = getattr(self.__class__, action) # Finally, look for a named method on the admin site else: try: func = self.admin_site.get_action(action) except KeyError: return None description = self._get_action_description(func, action) return func, action, description def get_list_display(self, request): """ Return a sequence containing the fields to be displayed on the changelist. """ return self.list_display def get_list_display_links(self, request, list_display): """ Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display(). """ if ( self.list_display_links or self.list_display_links is None or not list_display ): return self.list_display_links else: # Use only the first item in list_display as link return list(list_display)[:1] def get_list_filter(self, request): """ Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page. """ return self.list_filter def get_list_select_related(self, request): """ Return a list of fields to add to the select_related() part of the changelist items query. """ return self.list_select_related def get_search_fields(self, request): """ Return a sequence containing the fields to be searched whenever somebody submits a search query. """ return self.search_fields def get_search_results(self, request, queryset, search_term): """ Return a tuple containing a queryset to implement the search and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith("^"): return "%s__istartswith" % field_name[1:] elif field_name.startswith("="): return "%s__iexact" % field_name[1:] elif field_name.startswith("@"): return "%s__search" % field_name[1:] # Use field_name if it includes a lookup. opts = queryset.model._meta lookup_fields = field_name.split(LOOKUP_SEP) # Go through the fields, following all relations. prev_field = None for path_part in lookup_fields: if path_part == "pk": path_part = opts.pk.name try: field = opts.get_field(path_part) except FieldDoesNotExist: # Use valid query lookups. if prev_field and prev_field.get_lookup(path_part): return field_name else: prev_field = field if hasattr(field, "path_infos"): # Update opts to follow the relation. opts = field.path_infos[-1].to_opts # Otherwise, use the field with icontains. return "%s__icontains" % field_name may_have_duplicates = False search_fields = self.get_search_fields(request) if search_fields and search_term: orm_lookups = [ construct_search(str(search_field)) for search_field in search_fields ] term_queries = [] for bit in smart_split(search_term): if bit.startswith(('"', "'")) and bit[0] == bit[-1]: bit = unescape_string_literal(bit) or_queries = models.Q( *((orm_lookup, bit) for orm_lookup in orm_lookups), _connector=models.Q.OR, ) term_queries.append(or_queries) queryset = queryset.filter(models.Q(*term_queries)) may_have_duplicates |= any( lookup_spawns_duplicates(self.opts, search_spec) for search_spec in orm_lookups ) return queryset, may_have_duplicates def get_preserved_filters(self, request): """ Return the preserved filters querystring. """ match = request.resolver_match if self.preserve_filters and match: opts = self.model._meta current_url = "%s:%s" % (match.app_name, match.url_name) changelist_url = "admin:%s_%s_changelist" % ( opts.app_label, opts.model_name, ) if current_url == changelist_url: preserved_filters = request.GET.urlencode() else: preserved_filters = request.GET.get("_changelist_filters") if preserved_filters: return urlencode({"_changelist_filters": preserved_filters}) return "" def construct_change_message(self, request, form, formsets, add=False): """ Construct a JSON structure describing changes from a changed object. """ return construct_change_message(form, formsets, add) def message_user( self, request, message, level=messages.INFO, extra_tags="", fail_silently=False ): """ Send a message to the user. The default implementation posts a message using the django.contrib.messages backend. Exposes almost the same API as messages.add_message(), but accepts the positional arguments in a different order to maintain backwards compatibility. For convenience, it accepts the `level` argument as a string rather than the usual level number. """ if not isinstance(level, int): # attempt to get the level if passed a string try: level = getattr(messages.constants, level.upper()) except AttributeError: levels = messages.constants.DEFAULT_TAGS.values() levels_repr = ", ".join("`%s`" % level for level in levels) raise ValueError( "Bad message level string: `%s`. Possible values are: %s" % (level, levels_repr) ) messages.add_message( request, level, message, extra_tags=extra_tags, fail_silently=fail_silently ) def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() def delete_model(self, request, obj): """ Given a model instance delete it from the database. """ obj.delete() def delete_queryset(self, request, queryset): """Given a queryset, delete it from the database.""" queryset.delete() def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() def save_related(self, request, form, formsets, change): """ Given the ``HttpRequest``, the parent ``ModelForm`` instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed, save the related objects to the database. Note that at this point save_form() and save_model() have already been called. """ form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=change) def render_change_form( self, request, context, add=False, change=False, form_url="", obj=None ): opts = self.model._meta app_label = opts.app_label preserved_filters = self.get_preserved_filters(request) form_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, form_url ) view_on_site_url = self.get_view_on_site_url(obj) has_editable_inline_admin_formsets = False for inline in context["inline_admin_formsets"]: if ( inline.has_add_permission or inline.has_change_permission or inline.has_delete_permission ): has_editable_inline_admin_formsets = True break context.update( { "add": add, "change": change, "has_view_permission": self.has_view_permission(request, obj), "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_editable_inline_admin_formsets": ( has_editable_inline_admin_formsets ), "has_file_field": context["adminform"].form.is_multipart() or any( admin_formset.formset.is_multipart() for admin_formset in context["inline_admin_formsets"] ), "has_absolute_url": view_on_site_url is not None, "absolute_url": view_on_site_url, "form_url": form_url, "opts": opts, "content_type_id": get_content_type_for_model(self.model).pk, "save_as": self.save_as, "save_on_top": self.save_on_top, "to_field_var": TO_FIELD_VAR, "is_popup_var": IS_POPUP_VAR, "app_label": app_label, } ) if add and self.add_form_template is not None: form_template = self.add_form_template else: form_template = self.change_form_template request.current_app = self.admin_site.name return TemplateResponse( request, form_template or [ "admin/%s/%s/change_form.html" % (app_label, opts.model_name), "admin/%s/change_form.html" % app_label, "admin/change_form.html", ], context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. """ opts = obj._meta preserved_filters = self.get_preserved_filters(request) obj_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(quote(obj.pk),), current_app=self.admin_site.name, ) # Add a link to the object's change form if the user can edit the obj. if self.has_change_permission(request, obj): obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj) else: obj_repr = str(obj) msg_dict = { "name": opts.verbose_name, "obj": obj_repr, } # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) if to_field: attr = str(to_field) else: attr = obj._meta.pk.attname value = obj.serializable_value(attr) popup_response_data = json.dumps( { "value": str(value), "obj": str(obj), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) elif "_continue" in request.POST or ( # Redirecting after "Save as new". "_saveasnew" in request.POST and self.save_as_continue and self.has_change_permission(request, obj) ): msg = _("The {name} “{obj}” was added successfully.") if self.has_change_permission(request, obj): msg += " " + _("You may edit it again below.") self.message_user(request, format_html(msg, **msg_dict), messages.SUCCESS) if post_url_continue is None: post_url_continue = obj_url post_url_continue = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, post_url_continue, ) return HttpResponseRedirect(post_url_continue) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was added successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_add(request, obj) def response_change(self, request, obj): """ Determine the HttpResponse for the change_view stage. """ if IS_POPUP_VAR in request.POST: opts = obj._meta to_field = request.POST.get(TO_FIELD_VAR) attr = str(to_field) if to_field else opts.pk.attname value = request.resolver_match.kwargs["object_id"] new_value = obj.serializable_value(attr) popup_response_data = json.dumps( { "action": "change", "value": str(value), "obj": str(obj), "new_value": str(new_value), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) opts = self.model._meta preserved_filters = self.get_preserved_filters(request) msg_dict = { "name": opts.verbose_name, "obj": format_html('<a href="{}">{}</a>', urlquote(request.path), obj), } if "_continue" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may edit it " "again below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_saveasnew" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may edit it again " "below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(obj.pk,), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_add" % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was changed successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_change(request, obj) def _response_post_save(self, request, obj): opts = self.model._meta if self.has_view_or_change_permission(request): post_url = reverse( "admin:%s_%s_changelist" % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def response_post_save_add(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when adding a new object. """ return self._response_post_save(request, obj) def response_post_save_change(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when editing an existing object. """ return self._response_post_save(request, obj) def response_action(self, request, queryset): """ Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise. """ # There can be multiple action forms on the page (at the top # and bottom of the change list, for example). Get the action # whose button was pushed. try: action_index = int(request.POST.get("index", 0)) except ValueError: action_index = 0 # Construct the action form. data = request.POST.copy() data.pop(helpers.ACTION_CHECKBOX_NAME, None) data.pop("index", None) # Use the action whose button was pushed try: data.update({"action": data.getlist("action")[action_index]}) except IndexError: # If we didn't get an action from the chosen form that's invalid # POST data, so by deleting action it'll fail the validation check # below. So no need to do anything here pass action_form = self.action_form(data, auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) # If the form's valid we can handle the action. if action_form.is_valid(): action = action_form.cleaned_data["action"] select_across = action_form.cleaned_data["select_across"] func = self.get_actions(request)[action][0] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. Except we want to perform # the action explicitly on all objects. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) if not selected and not select_across: # Reminder that something needs to be selected or nothing will happen msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) return None if not select_across: # Perform the action only on the selected objects queryset = queryset.filter(pk__in=selected) response = func(self, request, queryset) # Actions may return an HttpResponse-like object, which will be # used as the response from the POST. If not, we'll be a good # little HTTP citizen and redirect back to the changelist page. if isinstance(response, HttpResponseBase): return response else: return HttpResponseRedirect(request.get_full_path()) else: msg = _("No action selected.") self.message_user(request, msg, messages.WARNING) return None def response_delete(self, request, obj_display, obj_id): """ Determine the HttpResponse for the delete_view stage. """ opts = self.model._meta if IS_POPUP_VAR in request.POST: popup_response_data = json.dumps( { "action": "delete", "value": str(obj_id), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) self.message_user( request, _("The %(name)s “%(obj)s” was deleted successfully.") % { "name": opts.verbose_name, "obj": obj_display, }, messages.SUCCESS, ) if self.has_change_permission(request, None): post_url = reverse( "admin:%s_%s_changelist" % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def render_delete_form(self, request, context): opts = self.model._meta app_label = opts.app_label request.current_app = self.admin_site.name context.update( to_field_var=TO_FIELD_VAR, is_popup_var=IS_POPUP_VAR, media=self.media, ) return TemplateResponse( request, self.delete_confirmation_template or [ "admin/{}/{}/delete_confirmation.html".format( app_label, opts.model_name ), "admin/{}/delete_confirmation.html".format(app_label), "admin/delete_confirmation.html", ], context, ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): # Edit permissions on parent model are required for editable inlines. can_edit_parent = ( self.has_change_permission(request, obj) if obj else self.has_add_permission(request) ) inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) if can_edit_parent: has_add_permission = inline.has_add_permission(request, obj) has_change_permission = inline.has_change_permission(request, obj) has_delete_permission = inline.has_delete_permission(request, obj) else: # Disable all edit-permissions, and overide formset settings. has_add_permission = ( has_change_permission ) = has_delete_permission = False formset.extra = formset.max_num = 0 has_view_permission = inline.has_view_permission(request, obj) prepopulated = dict(inline.get_prepopulated_fields(request, obj)) inline_admin_formset = helpers.InlineAdminFormSet( inline, formset, fieldsets, prepopulated, readonly, model_admin=self, has_add_permission=has_add_permission, has_change_permission=has_change_permission, has_delete_permission=has_delete_permission, has_view_permission=has_view_permission, ) inline_admin_formsets.append(inline_admin_formset) return inline_admin_formsets def get_changeform_initial_data(self, request): """ Get the initial form data from the request's GET params. """ initial = dict(request.GET.items()) for k in initial: try: f = self.model._meta.get_field(k) except FieldDoesNotExist: continue # We have to special-case M2Ms as a list of comma-separated PKs. if isinstance(f, models.ManyToManyField): initial[k] = initial[k].split(",") return initial def _get_obj_does_not_exist_redirect(self, request, opts, object_id): """ Create a message informing the user that the object doesn't exist and return a redirect to the admin index page. """ msg = _("%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?") % { "name": opts.verbose_name, "key": unquote(object_id), } self.message_user(request, msg, messages.WARNING) url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(url) @csrf_protect_m def changeform_view(self, request, object_id=None, form_url="", extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._changeform_view(request, object_id, form_url, extra_context) def _changeform_view(self, request, object_id, form_url, extra_context): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) model = self.model opts = model._meta if request.method == "POST" and "_saveasnew" in request.POST: object_id = None add = object_id is None if add: if not self.has_add_permission(request): raise PermissionDenied obj = None else: obj = self.get_object(request, unquote(object_id), to_field) if request.method == "POST": if not self.has_change_permission(request, obj): raise PermissionDenied else: if not self.has_view_or_change_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(request, opts, object_id) fieldsets = self.get_fieldsets(request, obj) ModelForm = self.get_form( request, obj, change=not add, fields=flatten_fieldsets(fieldsets) ) if request.method == "POST": form = ModelForm(request.POST, request.FILES, instance=obj) formsets, inline_instances = self._create_formsets( request, form.instance, change=not add, ) form_validated = form.is_valid() if form_validated: new_object = self.save_form(request, form, change=not add) else: new_object = form.instance if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, not add) self.save_related(request, form, formsets, not add) change_message = self.construct_change_message( request, form, formsets, add ) if add: self.log_addition(request, new_object, change_message) return self.response_add(request, new_object) else: self.log_change(request, new_object, change_message) return self.response_change(request, new_object) else: form_validated = False else: if add: initial = self.get_changeform_initial_data(request) form = ModelForm(initial=initial) formsets, inline_instances = self._create_formsets( request, form.instance, change=False ) else: form = ModelForm(instance=obj) formsets, inline_instances = self._create_formsets( request, obj, change=True ) if not add and not self.has_change_permission(request, obj): readonly_fields = flatten_fieldsets(fieldsets) else: readonly_fields = self.get_readonly_fields(request, obj) adminForm = helpers.AdminForm( form, list(fieldsets), # Clear prepopulated fields on a view-only form to avoid a crash. self.get_prepopulated_fields(request, obj) if add or self.has_change_permission(request, obj) else {}, readonly_fields, model_admin=self, ) media = self.media + adminForm.media inline_formsets = self.get_inline_formsets( request, formsets, inline_instances, obj ) for inline_formset in inline_formsets: media = media + inline_formset.media if add: title = _("Add %s") elif self.has_change_permission(request, obj): title = _("Change %s") else: title = _("View %s") context = { **self.admin_site.each_context(request), "title": title % opts.verbose_name, "subtitle": str(obj) if obj else None, "adminform": adminForm, "object_id": object_id, "original": obj, "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, "media": media, "inline_admin_formsets": inline_formsets, "errors": helpers.AdminErrorList(form, formsets), "preserved_filters": self.get_preserved_filters(request), } # Hide the "Save" and "Save and continue" buttons if "Save as New" was # previously chosen to prevent the interface from getting confusing. if ( request.method == "POST" and not form_validated and "_saveasnew" in request.POST ): context["show_save"] = False context["show_save_and_continue"] = False # Use the change template instead of the add template. add = False context.update(extra_context or {}) return self.render_change_form( request, context, add=add, change=not add, obj=obj, form_url=form_url ) def add_view(self, request, form_url="", extra_context=None): return self.changeform_view(request, None, form_url, extra_context) def change_view(self, request, object_id, form_url="", extra_context=None): return self.changeform_view(request, object_id, form_url, extra_context) def _get_edited_object_pks(self, request, prefix): """Return POST data values of list_editable primary keys.""" pk_pattern = re.compile( r"{}-\d+-{}$".format(re.escape(prefix), self.model._meta.pk.name) ) return [value for key, value in request.POST.items() if pk_pattern.match(key)] def _get_list_editable_queryset(self, request, prefix): """ Based on POST data, return a queryset of the objects that were edited via list_editable. """ object_pks = self._get_edited_object_pks(request, prefix) queryset = self.get_queryset(request) validate = queryset.model._meta.pk.to_python try: for pk in object_pks: validate(pk) except ValidationError: # Disable the optimization if the POST data was tampered with. return queryset return queryset.filter(pk__in=object_pks) @csrf_protect_m def changelist_view(self, request, extra_context=None): """ The 'change list' admin view for this model. """ from django.contrib.admin.views.main import ERROR_FLAG opts = self.model._meta app_label = opts.app_label if not self.has_view_or_change_permission(request): raise PermissionDenied try: cl = self.get_changelist_instance(request) except IncorrectLookupParameters: # Wacky lookup parameters were given, so redirect to the main # changelist page, without parameters, and pass an 'invalid=1' # parameter via the query string. If wacky parameters were given # and the 'invalid=1' parameter was already in the query string, # something is screwed up with the database, so display an error # page. if ERROR_FLAG in request.GET: return SimpleTemplateResponse( "admin/invalid_setup.html", { "title": _("Database error"), }, ) return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1") # If the request was POSTed, this might be a bulk action or a bulk # edit. Try to look up an action or confirmation first, but if this # isn't an action the POST will fall through to the bulk edit check, # below. action_failed = False selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) actions = self.get_actions(request) # Actions with no confirmation if ( actions and request.method == "POST" and "index" in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True else: msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) action_failed = True # Actions with confirmation if ( actions and request.method == "POST" and helpers.ACTION_CHECKBOX_NAME in request.POST and "index" not in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True if action_failed: # Redirect back to the changelist page to avoid resubmitting the # form if the user refreshes the browser or uses the "No, take # me back" button on the action confirmation page. return HttpResponseRedirect(request.get_full_path()) # If we're allowing changelist editing, we need to construct a formset # for the changelist given all the fields to be edited. Then we'll # use the formset to validate/process POSTed data. formset = cl.formset = None # Handle POSTed bulk-edit data. if request.method == "POST" and cl.list_editable and "_save" in request.POST: if not self.has_change_permission(request): raise PermissionDenied FormSet = self.get_changelist_formset(request) modified_objects = self._get_list_editable_queryset( request, FormSet.get_default_prefix() ) formset = cl.formset = FormSet( request.POST, request.FILES, queryset=modified_objects ) if formset.is_valid(): changecount = 0 for form in formset.forms: if form.has_changed(): obj = self.save_form(request, form, change=True) self.save_model(request, obj, form, change=True) self.save_related(request, form, formsets=[], change=True) change_msg = self.construct_change_message(request, form, None) self.log_change(request, obj, change_msg) changecount += 1 if changecount: msg = ngettext( "%(count)s %(name)s was changed successfully.", "%(count)s %(name)s were changed successfully.", changecount, ) % { "count": changecount, "name": model_ngettext(opts, changecount), } self.message_user(request, msg, messages.SUCCESS) return HttpResponseRedirect(request.get_full_path()) # Handle GET -- construct a formset for display. elif cl.list_editable and self.has_change_permission(request): FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(queryset=cl.result_list) # Build the list of media to be used by the formset. if formset: media = self.media + formset.media else: media = self.media # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) media += action_form.media else: action_form = None selection_note_all = ngettext( "%(total_count)s selected", "All %(total_count)s selected", cl.result_count ) context = { **self.admin_site.each_context(request), "module_name": str(opts.verbose_name_plural), "selection_note": _("0 of %(cnt)s selected") % {"cnt": len(cl.result_list)}, "selection_note_all": selection_note_all % {"total_count": cl.result_count}, "title": cl.title, "subtitle": None, "is_popup": cl.is_popup, "to_field": cl.to_field, "cl": cl, "media": media, "has_add_permission": self.has_add_permission(request), "opts": cl.opts, "action_form": action_form, "actions_on_top": self.actions_on_top, "actions_on_bottom": self.actions_on_bottom, "actions_selection_counter": self.actions_selection_counter, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_list_template or [ "admin/%s/%s/change_list.html" % (app_label, opts.model_name), "admin/%s/change_list.html" % app_label, "admin/change_list.html", ], context, ) def get_deleted_objects(self, objs, request): """ Hook for customizing the delete process for the delete view and the "delete selected" action. """ return get_deleted_objects(objs, request, self.admin_site) @csrf_protect_m def delete_view(self, request, object_id, extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._delete_view(request, object_id, extra_context) def _delete_view(self, request, object_id, extra_context): "The 'delete' admin view for this model." opts = self.model._meta app_label = opts.app_label to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) obj = self.get_object(request, unquote(object_id), to_field) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(request, opts, object_id) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. ( deleted_objects, model_count, perms_needed, protected, ) = self.get_deleted_objects([obj], request) if request.POST and not protected: # The user has confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = str(obj) attr = str(to_field) if to_field else opts.pk.attname obj_id = obj.serializable_value(attr) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) return self.response_delete(request, obj_display, obj_id) object_name = str(opts.verbose_name) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": object_name} else: title = _("Are you sure?") context = { **self.admin_site.each_context(request), "title": title, "subtitle": None, "object_name": object_name, "object": obj, "deleted_objects": deleted_objects, "model_count": dict(model_count).items(), "perms_lacking": perms_needed, "protected": protected, "opts": opts, "app_label": app_label, "preserved_filters": self.get_preserved_filters(request), "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, **(extra_context or {}), } return self.render_delete_form(request, context) def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry from django.contrib.admin.views.main import PAGE_VAR # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: return self._get_obj_does_not_exist_redirect( request, model._meta, object_id ) if not self.has_view_or_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = ( LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model), ) .select_related() .order_by("action_time") ) paginator = self.get_paginator(request, action_list, 100) page_number = request.GET.get(PAGE_VAR, 1) page_obj = paginator.get_page(page_number) page_range = paginator.get_elided_page_range(page_obj.number) context = { **self.admin_site.each_context(request), "title": _("Change history: %s") % obj, "subtitle": None, "action_list": page_obj, "page_range": page_range, "page_var": PAGE_VAR, "pagination_required": paginator.count > 100, "module_name": str(capfirst(opts.verbose_name_plural)), "object": obj, "opts": opts, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html", ], context, ) def get_formset_kwargs(self, request, obj, inline, prefix): formset_params = { "instance": obj, "prefix": prefix, "queryset": inline.get_queryset(request), } if request.method == "POST": formset_params.update( { "data": request.POST.copy(), "files": request.FILES, "save_as_new": "_saveasnew" in request.POST, } ) return formset_params def _create_formsets(self, request, obj, change): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = {} get_formsets_args = [request] if change: get_formsets_args.append(obj) for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = self.get_formset_kwargs(request, obj, inline, prefix) formset = FormSet(**formset_params) def user_deleted_form(request, obj, formset, index): """Return whether or not the user deleted the form.""" return ( inline.has_delete_permission(request, obj) and "{}-{}-DELETE".format(formset.prefix, index) in request.POST ) # Bypass validation of each view-only inline form (since the form's # data won't be in request.POST), unless the form was deleted. if not inline.has_change_permission(request, obj if change else None): for index, form in enumerate(formset.initial_forms): if user_deleted_form(request, obj, formset, index): continue form._errors = {} form.cleaned_data = form.initial formsets.append(formset) inline_instances.append(inline) return formsets, inline_instances class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None fk_name = None formset = BaseInlineFormSet extra = 3 min_num = None max_num = None template = None verbose_name = None verbose_name_plural = None can_delete = True show_change_link = False checks_class = InlineModelAdminChecks classes = None def __init__(self, parent_model, admin_site): self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) super().__init__() if self.verbose_name_plural is None: if self.verbose_name is None: self.verbose_name_plural = self.model._meta.verbose_name_plural else: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) if self.verbose_name is None: self.verbose_name = self.model._meta.verbose_name @property def media(self): extra = "" if settings.DEBUG else ".min" js = ["vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "inlines.js"] if self.filter_vertical or self.filter_horizontal: js.extend(["SelectBox.js", "SelectFilter2.js"]) if self.classes and "collapse" in self.classes: js.append("collapse.js") return forms.Media(js=["admin/js/%s" % url for url in js]) def get_extra(self, request, obj=None, **kwargs): """Hook for customizing the number of extra inline forms.""" return self.extra def get_min_num(self, request, obj=None, **kwargs): """Hook for customizing the min number of inline forms.""" return self.min_num def get_max_num(self, request, obj=None, **kwargs): """Hook for customizing the max number of extra inline forms.""" return self.max_num def get_formset(self, request, obj=None, **kwargs): """Return a BaseInlineFormSet class for use in admin add/change views.""" if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) exclude.extend(self.get_readonly_fields(request, obj)) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # If exclude is an empty list we use None, since that's the actual # default. exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission(request, obj) defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), "extra": self.get_extra(request, obj, **kwargs), "min_num": self.get_min_num(request, obj, **kwargs), "max_num": self.get_max_num(request, obj, **kwargs), "can_delete": can_delete, **kwargs, } base_model_form = defaults["form"] can_change = self.has_change_permission(request, obj) if request else True can_add = self.has_add_permission(request, obj) if request else True class DeleteProtectedModelForm(base_model_form): def hand_clean_DELETE(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) if self.instance._state.adding: return collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance # representation, suitable to be an item in a # list. _("%(class_name)s %(instance)s") % {"class_name": p._meta.verbose_name, "instance": p} ) params = { "class_name": self._meta.model._meta.verbose_name, "instance": self.instance, "related_objects": get_text_list(objs, _("and")), } msg = _( "Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s" ) raise ValidationError( msg, code="deleting_protected", params=params ) def is_valid(self): result = super().is_valid() self.hand_clean_DELETE() return result def has_changed(self): # Protect against unauthorized edits. if not can_change and not self.instance._state.adding: return False if not can_add and self.instance._state.adding: return False return super().has_changed() defaults["form"] = DeleteProtectedModelForm if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS return inlineformset_factory(self.parent_model, self.model, **defaults) def _get_form_for_get_fields(self, request, obj=None): return self.get_formset(request, obj, fields=None).form def get_queryset(self, request): queryset = super().get_queryset(request) if not self.has_view_or_change_permission(request): queryset = queryset.none() return queryset def _has_any_perms_for_target_model(self, request, perms): """ This method is called only when the ModelAdmin's model is for an ManyToManyField's implicit through model (if self.opts.auto_created). Return True if the user has any of the given permissions ('add', 'change', etc.) for the model that points to the through model. """ opts = self.opts # Find the target model of an auto-created many-to-many relationship. for field in opts.fields: if field.remote_field and field.remote_field.model != self.parent_model: opts = field.remote_field.model._meta break return any( request.user.has_perm( "%s.%s" % (opts.app_label, get_permission_codename(perm, opts)) ) for perm in perms ) def has_add_permission(self, request, obj): if self.opts.auto_created: # Auto-created intermediate models don't have their own # permissions. The user needs to have the change permission for the # related model in order to be able to do anything with the # intermediate model. return self._has_any_perms_for_target_model(request, ["change"]) return super().has_add_permission(request) def has_change_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_change_permission(request) def has_delete_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_delete_permission(request, obj) def has_view_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). The 'change' permission # also implies the 'view' permission. return self._has_any_perms_for_target_model(request, ["view", "change"]) return super().has_view_permission(request) class StackedInline(InlineModelAdmin): template = "admin/edit_inline/stacked.html" class TabularInline(InlineModelAdmin): template = "admin/edit_inline/tabular.html"
c29cdd2a7a7a57f69362e8bfe2d419f211497fb5b9c589043329b429e8359349
from django.core.exceptions import SuspiciousOperation class DisallowedModelAdminLookup(SuspiciousOperation): """Invalid filter was passed to admin view via URL querystring""" pass class DisallowedModelAdminToField(SuspiciousOperation): """Invalid to_field was passed to admin view via URL query string""" pass
4b914d9516c08a4920ea15a8eae2429e984f3f705af03e77dc9b62b2211910ef
import re from functools import update_wrapper from weakref import WeakSet from django.apps import apps from django.conf import settings from django.contrib.admin import ModelAdmin, actions from django.contrib.admin.views.autocomplete import AutocompleteJsonView from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import ImproperlyConfigured from django.db.models.base import ModelBase from django.http import Http404, HttpResponsePermanentRedirect, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import NoReverseMatch, Resolver404, resolve, reverse 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.decorators.cache import never_cache from django.views.decorators.common import no_append_slash from django.views.decorators.csrf import csrf_protect from django.views.i18n import JavaScriptCatalog all_sites = WeakSet() class AlreadyRegistered(Exception): pass class NotRegistered(Exception): pass 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 using 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_title = gettext_lazy("Django site admin") # Text to put in each page's <h1>. site_header = gettext_lazy("Django administration") # Text to put at the top of the admin index page. index_title = gettext_lazy("Site administration") # URL for the "View site" link at the top of each admin page. site_url = "/" enable_nav_sidebar = True empty_value_display = "-" login_form = None index_template = None app_index_template = None login_template = None logout_template = None password_change_template = None password_change_done_template = None final_catch_all_view = True def __init__(self, name="admin"): self._registry = {} # model_class class -> admin_class instance self.name = name self._actions = {"delete_selected": actions.delete_selected} self._global_actions = self._actions.copy() all_sites.add(self) def __repr__(self): return f"{self.__class__.__name__}(name={self.name!r})" def check(self, app_configs): """ Run the system checks on all ModelAdmins, except if they aren't customized at all. """ if app_configs is None: app_configs = apps.get_app_configs() app_configs = set(app_configs) # Speed up lookups below errors = [] modeladmins = ( o for o in self._registry.values() if o.__class__ is not ModelAdmin ) for modeladmin in modeladmins: if modeladmin.model._meta.app_config in app_configs: errors.extend(modeladmin.check()) return errors def register(self, model_or_iterable, admin_class=None, **options): """ Register the given model(s) with the given admin class. The model(s) should be Model classes, not instances. If an admin class isn't given, use ModelAdmin (the default admin options). If keyword arguments are given -- e.g., list_display -- apply them as options to the admin class. If a model is already registered, raise AlreadyRegistered. If a model is abstract, raise ImproperlyConfigured. """ admin_class = admin_class or ModelAdmin if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model._meta.abstract: raise ImproperlyConfigured( "The model %s is abstract, so it cannot be registered with admin." % model.__name__ ) if model in self._registry: registered_admin = str(self._registry[model]) msg = "The model %s is already registered " % model.__name__ if registered_admin.endswith(".ModelAdmin"): # Most likely registered without a ModelAdmin subclass. msg += "in app %r." % re.sub(r"\.ModelAdmin$", "", registered_admin) else: msg += "with %r." % registered_admin raise AlreadyRegistered(msg) # Ignore the registration if the model has been # swapped out. if not model._meta.swapped: # If we got **options then dynamically construct a subclass of # admin_class with those **options. if options: # For reasons I don't quite understand, without a __module__ # the created class appears to "live" in the wrong place, # which causes issues later on. options["__module__"] = __name__ admin_class = type( "%sAdmin" % model.__name__, (admin_class,), options ) # Instantiate the admin class to save in the registry self._registry[model] = admin_class(model, self) def unregister(self, model_or_iterable): """ Unregister the given model(s). If a model isn't already registered, raise NotRegistered. """ if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotRegistered("The model %s is not registered" % model.__name__) del self._registry[model] def is_registered(self, model): """ Check if a model class is registered with this `AdminSite`. """ return model in self._registry def add_action(self, action, name=None): """ Register an action to be available globally. """ name = name or action.__name__ self._actions[name] = action self._global_actions[name] = action def disable_action(self, name): """ Disable a globally-registered action. Raise KeyError for invalid names. """ del self._actions[name] def get_action(self, name): """ Explicitly get a registered global action whether it's enabled or not. Raise KeyError for invalid names. """ return self._global_actions[name] @property def actions(self): """ Get all the enabled actions as an iterable of (name, func). """ return self._actions.items() def has_permission(self, request): """ Return True if the given HttpRequest has permission to view *at least one* page in the admin site. """ return request.user.is_active and request.user.is_staff def admin_view(self, view, cacheable=False): """ Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ path('my_view/', self.admin_view(some_view)) ] return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """ def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse("admin:logout", current_app=self.name): index_path = reverse("admin:index", current_app=self.name) return HttpResponseRedirect(index_path) # Inner import to prevent django.contrib.admin (app) from # importing django.contrib.auth.models.User (unrelated model). from django.contrib.auth.views import redirect_to_login return redirect_to_login( request.get_full_path(), reverse("admin:login", current_app=self.name), ) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, "csrf_exempt", False): inner = csrf_protect(inner) return update_wrapper(inner, view) def get_urls(self): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level, # and django.contrib.contenttypes.views imports ContentType. from django.contrib.contenttypes import views as contenttype_views from django.urls import include, path, re_path def wrap(view, cacheable=False): def wrapper(*args, **kwargs): return self.admin_view(view, cacheable)(*args, **kwargs) wrapper.admin_site = self return update_wrapper(wrapper, view) # Admin-site-wide views. urlpatterns = [ path("", wrap(self.index), name="index"), path("login/", self.login, name="login"), path("logout/", wrap(self.logout), name="logout"), path( "password_change/", wrap(self.password_change, cacheable=True), name="password_change", ), path( "password_change/done/", wrap(self.password_change_done, cacheable=True), name="password_change_done", ), path("autocomplete/", wrap(self.autocomplete_view), name="autocomplete"), path("jsi18n/", wrap(self.i18n_javascript, cacheable=True), name="jsi18n"), path( "r/<int:content_type_id>/<path:object_id>/", wrap(contenttype_views.shortcut), name="view_on_site", ), ] # Add in each model's views, and create a list of valid URLS for the # app_index valid_app_labels = [] for model, model_admin in self._registry.items(): urlpatterns += [ path( "%s/%s/" % (model._meta.app_label, model._meta.model_name), include(model_admin.urls), ), ] if model._meta.app_label not in valid_app_labels: valid_app_labels.append(model._meta.app_label) # If there were ModelAdmins registered, we should have a list of app # labels for which we need to allow access to the app_index view, if valid_app_labels: regex = r"^(?P<app_label>" + "|".join(valid_app_labels) + ")/$" urlpatterns += [ re_path(regex, wrap(self.app_index), name="app_list"), ] if self.final_catch_all_view: urlpatterns.append(re_path(r"(?P<url>.*)$", wrap(self.catch_all_view))) return urlpatterns @property def urls(self): return self.get_urls(), "admin", self.name def each_context(self, request): """ Return a dictionary of variables to put in the template context for *every* page in the admin site. For sites running on a subpath, use the SCRIPT_NAME value if site_url hasn't been customized. """ script_name = request.META["SCRIPT_NAME"] site_url = ( script_name if self.site_url == "/" and script_name else self.site_url ) return { "site_title": self.site_title, "site_header": self.site_header, "site_url": site_url, "has_permission": self.has_permission(request), "available_apps": self.get_app_list(request), "is_popup": False, "is_nav_sidebar_enabled": self.enable_nav_sidebar, } def password_change(self, request, extra_context=None): """ Handle the "change password" task -- both form display and validation. """ from django.contrib.admin.forms import AdminPasswordChangeForm from django.contrib.auth.views import PasswordChangeView url = reverse("admin:password_change_done", current_app=self.name) defaults = { "form_class": AdminPasswordChangeForm, "success_url": url, "extra_context": {**self.each_context(request), **(extra_context or {})}, } if self.password_change_template is not None: defaults["template_name"] = self.password_change_template request.current_app = self.name return PasswordChangeView.as_view(**defaults)(request) def password_change_done(self, request, extra_context=None): """ Display the "success" page after a password change. """ from django.contrib.auth.views import PasswordChangeDoneView defaults = { "extra_context": {**self.each_context(request), **(extra_context or {})}, } if self.password_change_done_template is not None: defaults["template_name"] = self.password_change_done_template request.current_app = self.name return PasswordChangeDoneView.as_view(**defaults)(request) def i18n_javascript(self, request, extra_context=None): """ Display the i18n JavaScript that the Django admin requires. `extra_context` is unused but present for consistency with the other admin views. """ return JavaScriptCatalog.as_view(packages=["django.contrib.admin"])(request) def logout(self, request, extra_context=None): """ Log out the user for the given HttpRequest. This should *not* assume the user is already logged in. """ from django.contrib.auth.views import LogoutView defaults = { "extra_context": { **self.each_context(request), # Since the user isn't logged out at this point, the value of # has_permission must be overridden. "has_permission": False, **(extra_context or {}), }, } if self.logout_template is not None: defaults["template_name"] = self.logout_template request.current_app = self.name return LogoutView.as_view(**defaults)(request) @method_decorator(never_cache) def login(self, request, extra_context=None): """ Display the login form for the given HttpRequest. """ if request.method == "GET" and self.has_permission(request): # Already logged-in, redirect to admin index index_path = reverse("admin:index", current_app=self.name) return HttpResponseRedirect(index_path) # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level, # and django.contrib.admin.forms eventually imports User. from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.views import LoginView context = { **self.each_context(request), "title": _("Log in"), "subtitle": None, "app_path": request.get_full_path(), "username": request.user.get_username(), } if ( REDIRECT_FIELD_NAME not in request.GET and REDIRECT_FIELD_NAME not in request.POST ): context[REDIRECT_FIELD_NAME] = reverse("admin:index", current_app=self.name) context.update(extra_context or {}) defaults = { "extra_context": context, "authentication_form": self.login_form or AdminAuthenticationForm, "template_name": self.login_template or "admin/login.html", } request.current_app = self.name return LoginView.as_view(**defaults)(request) def autocomplete_view(self, request): return AutocompleteJsonView.as_view(admin_site=self)(request) @no_append_slash def catch_all_view(self, request, url): if settings.APPEND_SLASH and not url.endswith("/"): urlconf = getattr(request, "urlconf", None) try: match = resolve("%s/" % request.path_info, urlconf) except Resolver404: pass else: if getattr(match.func, "should_append_slash", True): return HttpResponsePermanentRedirect("%s/" % request.path) raise Http404 def _build_app_dict(self, request, label=None): """ Build the app dictionary. The optional `label` parameter filters models of a specific app. """ app_dict = {} if label: models = { m: m_a for m, m_a in self._registry.items() if m._meta.app_label == label } else: models = self._registry for model, model_admin in models.items(): app_label = model._meta.app_label has_module_perms = model_admin.has_module_permission(request) if not has_module_perms: continue perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True not in perms.values(): continue info = (app_label, model._meta.model_name) model_dict = { "model": model, "name": capfirst(model._meta.verbose_name_plural), "object_name": model._meta.object_name, "perms": perms, "admin_url": None, "add_url": None, } if perms.get("change") or perms.get("view"): model_dict["view_only"] = not perms.get("change") try: model_dict["admin_url"] = reverse( "admin:%s_%s_changelist" % info, current_app=self.name ) except NoReverseMatch: pass if perms.get("add"): try: model_dict["add_url"] = reverse( "admin:%s_%s_add" % info, current_app=self.name ) except NoReverseMatch: pass if app_label in app_dict: app_dict[app_label]["models"].append(model_dict) else: app_dict[app_label] = { "name": apps.get_app_config(app_label).verbose_name, "app_label": app_label, "app_url": reverse( "admin:app_list", kwargs={"app_label": app_label}, current_app=self.name, ), "has_module_perms": has_module_perms, "models": [model_dict], } if label: return app_dict.get(label) return app_dict def get_app_list(self, request): """ Return a sorted list of all the installed apps that have been registered in this site. """ app_dict = self._build_app_dict(request) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x["name"].lower()) # Sort the models alphabetically within each app. for app in app_list: app["models"].sort(key=lambda x: x["name"]) return app_list def index(self, request, extra_context=None): """ Display the main admin index page, which lists all of the installed apps that have been registered in this site. """ app_list = self.get_app_list(request) context = { **self.each_context(request), "title": self.index_title, "subtitle": None, "app_list": app_list, **(extra_context or {}), } request.current_app = self.name return TemplateResponse( request, self.index_template or "admin/index.html", context ) def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404("The requested admin page does not exist.") # Sort the models alphabetically within each app. app_dict["models"].sort(key=lambda x: x["name"]) context = { **self.each_context(request), "title": _("%(app)s administration") % {"app": app_dict["name"]}, "subtitle": None, "app_list": [app_dict], "app_label": app_label, **(extra_context or {}), } request.current_app = self.name return TemplateResponse( request, self.app_index_template or ["admin/%s/app_index.html" % app_label, "admin/app_index.html"], context, ) class DefaultAdminSite(LazyObject): def _setup(self): AdminSiteClass = import_string(apps.get_app_config("admin").default_site) self._wrapped = AdminSiteClass() def __repr__(self): return repr(self._wrapped) # This global object represents the default admin site, for the common case. # You can provide your own AdminSite using the (Simple)AdminConfig.default_site # attribute. You can also instantiate AdminSite in your own code to create a # custom admin site. site = DefaultAdminSite()
be3c006463067f8ae3949488686397fbb49f3f45e69094ffd3ae6c1a1603c83f
""" Built-in, globally-available admin actions. """ from django.contrib import messages from django.contrib.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 import gettext_lazy @action( permissions=["delete"], description=gettext_lazy("Delete selected %(verbose_name_plural)s"), ) def delete_selected(modeladmin, request, queryset): """ 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), 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 related objects that # will also be deleted. ( deletable_objects, model_count, perms_needed, protected, ) = modeladmin.get_deleted_objects(queryset, request) # The user has already confirmed the deletion. # Do the deletion and return None to display the change list view again. if request.POST.get("post") and not protected: if perms_needed: raise PermissionDenied n = queryset.count() if n: for obj in queryset: obj_display = str(obj) modeladmin.log_deletion(request, obj, obj_display) modeladmin.delete_queryset(request, queryset) modeladmin.message_user( request, _("Successfully deleted %(count)d %(items)s.") % {"count": n, "items": model_ngettext(modeladmin.opts, n)}, messages.SUCCESS, ) # Return None to display the change list page again. return None objects_name = model_ngettext(queryset) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Are you sure?") context = { **modeladmin.admin_site.each_context(request), "title": title, "subtitle": None, "objects_name": str(objects_name), "deletable_objects": [deletable_objects], "model_count": dict(model_count).items(), "queryset": queryset, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, "media": modeladmin.media, } request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse( request, modeladmin.delete_selected_confirmation_template or [ "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.model_name), "admin/%s/delete_selected_confirmation.html" % app_label, "admin/delete_selected_confirmation.html", ], context, )
a73b8b1dead9c8c874776d149a394f7447f56149e0e94b4b982ba6e8f45424ff
""" Form Widget classes specific to the Django admin site. """ import copy import json from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.db.models import CASCADE, UUIDField from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.http import urlencode from django.utils.text import Truncator from django.utils.translation import get_language from django.utils.translation import gettext as _ class FilteredSelectMultiple(forms.SelectMultiple): """ A SelectMultiple with a JavaScript filter interface. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ 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.verbose_name = verbose_name self.is_stacked = is_stacked super().__init__(attrs, choices) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["attrs"]["class"] = "selectfilter" if self.is_stacked: context["widget"]["attrs"]["class"] += "stacked" context["widget"]["attrs"]["data-field-name"] = self.verbose_name context["widget"]["attrs"]["data-is-stacked"] = int(self.is_stacked) return context class AdminDateWidget(forms.DateInput): class Media: js = [ "admin/js/calendar.js", "admin/js/admin/DateTimeShortcuts.js", ] def __init__(self, attrs=None, format=None): attrs = {"class": "vDateField", "size": "10", **(attrs or {})} super().__init__(attrs=attrs, format=format) class AdminTimeWidget(forms.TimeInput): class Media: js = [ "admin/js/calendar.js", "admin/js/admin/DateTimeShortcuts.js", ] def __init__(self, attrs=None, format=None): attrs = {"class": "vTimeField", "size": "8", **(attrs or {})} super().__init__(attrs=attrs, format=format) class AdminSplitDateTime(forms.SplitDateTimeWidget): """ A SplitDateTime Widget that has some admin-specific styling. """ template_name = "admin/widgets/split_datetime.html" def __init__(self, attrs=None): widgets = [AdminDateWidget, AdminTimeWidget] # Note that we're calling MultiWidget, not SplitDateTimeWidget, because # we want to define widgets. forms.MultiWidget.__init__(self, widgets, attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["date_label"] = _("Date:") context["time_label"] = _("Time:") return context class AdminRadioSelect(forms.RadioSelect): template_name = "admin/widgets/radio.html" class AdminFileWidget(forms.ClearableFileInput): template_name = "admin/widgets/clearable_file_input.html" def url_params_from_lookup_dict(lookups): """ Convert the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, "items"): for k, v in lookups.items(): if callable(v): v = v() if isinstance(v, (tuple, list)): v = ",".join(str(x) for x in v) elif isinstance(v, bool): v = ("0", "1")[v] else: v = str(v) params[k] = v return params class ForeignKeyRawIdWidget(forms.TextInput): """ A Widget for displaying ForeignKeys in the "raw_id" interface rather than in a <select> box. """ template_name = "admin/widgets/foreign_key_raw_id.html" def __init__(self, rel, admin_site, attrs=None, using=None): self.rel = rel self.admin_site = admin_site self.db = using super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) rel_to = self.rel.model if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse( "admin:%s_%s_changelist" % ( rel_to._meta.app_label, rel_to._meta.model_name, ), current_app=self.admin_site.name, ) params = self.url_parameters() if params: related_url += "?" + urlencode(params) context["related_url"] = related_url context["link_title"] = _("Lookup") # The JavaScript code looks for this class. css_class = "vForeignKeyRawIdAdminField" if isinstance(self.rel.get_related_field(), UUIDField): css_class += " vUUIDField" context["widget"]["attrs"].setdefault("class", css_class) else: context["related_url"] = None if context["widget"]["value"]: context["link_label"], context["link_url"] = self.label_and_url_for_value( value ) else: context["link_label"] = None return context def base_url_parameters(self): limit_choices_to = self.rel.limit_choices_to if callable(limit_choices_to): limit_choices_to = limit_choices_to() return url_params_from_lookup_dict(limit_choices_to) def url_parameters(self): from django.contrib.admin.views.main import TO_FIELD_VAR params = self.base_url_parameters() params.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return params def label_and_url_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.model._default_manager.using(self.db).get(**{key: value}) except (ValueError, self.rel.model.DoesNotExist, ValidationError): return "", "" try: url = reverse( "%s:%s_%s_change" % ( self.admin_site.name, obj._meta.app_label, obj._meta.object_name.lower(), ), args=(obj.pk,), ) except NoReverseMatch: url = "" # Admin not registered for target model. return Truncator(obj).words(14), url class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): """ A Widget for displaying ManyToMany ids in the "raw_id" interface rather than in a <select multiple> box. """ template_name = "admin/widgets/many_to_many_raw_id.html" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.rel.model in self.admin_site._registry: # The related object is registered with the same AdminSite context["widget"]["attrs"]["class"] = "vManyToManyRawIdAdminField" return context def url_parameters(self): return self.base_url_parameters() def label_and_url_for_value(self, value): return "", "" def value_from_datadict(self, data, files, name): value = data.get(name) if value: return value.split(",") def format_value(self, value): return ",".join(str(v) for v in value) if value else "" class RelatedFieldWidgetWrapper(forms.Widget): """ This class is a wrapper to a given widget to add the add icon for the admin interface. """ template_name = "admin/widgets/related_widget_wrapper.html" def __init__( self, widget, rel, admin_site, can_add_related=None, can_change_related=False, can_delete_related=False, can_view_related=False, ): self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.choices = widget.choices self.widget = widget self.rel = rel # Backwards compatible check for whether a user can add related # objects. if can_add_related is None: can_add_related = rel.model in admin_site._registry self.can_add_related = can_add_related # XXX: The UX does not support multiple selected values. multiple = getattr(widget, "allow_multiple_selected", False) self.can_change_related = not multiple and can_change_related # XXX: The deletion UX can be confusing when dealing with cascading deletion. cascade = getattr(rel, "on_delete", None) is CASCADE self.can_delete_related = not multiple and not cascade and can_delete_related self.can_view_related = not multiple and can_view_related # so we can check if the related object is registered with this AdminSite self.admin_site = admin_site def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj @property def is_hidden(self): return self.widget.is_hidden @property def media(self): return self.widget.media def get_related_url(self, info, action, *args): return reverse( "admin:%s_%s_%s" % (info + (action,)), current_app=self.admin_site.name, args=args, ) def get_context(self, name, value, attrs): from django.contrib.admin.views.main import IS_POPUP_VAR, TO_FIELD_VAR rel_opts = self.rel.model._meta info = (rel_opts.app_label, rel_opts.model_name) self.widget.choices = self.choices related_field_name = self.rel.get_related_field().name url_params = "&".join( "%s=%s" % param for param in [ (TO_FIELD_VAR, related_field_name), (IS_POPUP_VAR, 1), ] ) context = { "rendered_widget": self.widget.render(name, value, attrs), "is_hidden": self.is_hidden, "name": name, "url_params": url_params, "model": rel_opts.verbose_name, "can_add_related": self.can_add_related, "can_change_related": self.can_change_related, "can_delete_related": self.can_delete_related, "can_view_related": self.can_view_related, } if self.can_add_related: context["add_related_url"] = self.get_related_url(info, "add") if self.can_delete_related: context["delete_related_template_url"] = self.get_related_url( info, "delete", "__fk__" ) if self.can_view_related or self.can_change_related: context["view_related_url_params"] = f"{TO_FIELD_VAR}={related_field_name}" context["change_related_template_url"] = self.get_related_url( info, "change", "__fk__" ) return context def value_from_datadict(self, data, files, name): return self.widget.value_from_datadict(data, files, name) def value_omitted_from_data(self, data, files, name): return self.widget.value_omitted_from_data(data, files, name) def id_for_label(self, id_): return self.widget.id_for_label(id_) class AdminTextareaWidget(forms.Textarea): def __init__(self, attrs=None): super().__init__(attrs={"class": "vLargeTextField", **(attrs or {})}) class AdminTextInputWidget(forms.TextInput): def __init__(self, attrs=None): super().__init__(attrs={"class": "vTextField", **(attrs or {})}) class AdminEmailInputWidget(forms.EmailInput): def __init__(self, attrs=None): super().__init__(attrs={"class": "vTextField", **(attrs or {})}) class AdminURLFieldWidget(forms.URLInput): template_name = "admin/widgets/url.html" def __init__(self, attrs=None, validator_class=URLValidator): super().__init__(attrs={"class": "vURLField", **(attrs or {})}) self.validator = validator_class() def get_context(self, name, value, attrs): try: self.validator(value if value else "") url_valid = True except ValidationError: url_valid = False context = super().get_context(name, value, attrs) context["current_label"] = _("Currently:") context["change_label"] = _("Change:") context["widget"]["href"] = ( smart_urlquote(context["widget"]["value"]) if value else "" ) context["url_valid"] = url_valid return context class AdminIntegerFieldWidget(forms.NumberInput): class_name = "vIntegerField" def __init__(self, attrs=None): super().__init__(attrs={"class": self.class_name, **(attrs or {})}) class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): class_name = "vBigIntegerField" class AdminUUIDInputWidget(forms.TextInput): def __init__(self, attrs=None): super().__init__(attrs={"class": "vUUIDField", **(attrs or {})}) # Mapping of lowercase language codes [returned by Django's get_language()] to # language codes supported by select2. # See django/contrib/admin/static/admin/js/vendor/select2/i18n/* SELECT2_TRANSLATIONS = { x.lower(): x for x in [ "ar", "az", "bg", "ca", "cs", "da", "de", "el", "en", "es", "et", "eu", "fa", "fi", "fr", "gl", "he", "hi", "hr", "hu", "id", "is", "it", "ja", "km", "ko", "lt", "lv", "mk", "ms", "nb", "nl", "pl", "pt-BR", "pt", "ro", "ru", "sk", "sr-Cyrl", "sr", "sv", "th", "tr", "uk", "vi", ] } SELECT2_TRANSLATIONS.update({"zh-hans": "zh-CN", "zh-hant": "zh-TW"}) def get_select2_language(): lang_code = get_language() supported_code = SELECT2_TRANSLATIONS.get(lang_code) if supported_code is None: # If 'zh-hant-tw' is not supported, try subsequent language codes i.e. # 'zh-hant' and 'zh'. i = None while (i := lang_code.rfind("-", 0, i)) > -1: if supported_code := SELECT2_TRANSLATIONS.get(lang_code[:i]): return supported_code return supported_code class AutocompleteMixin: """ Select widget mixin that loads options from AutocompleteJsonView via AJAX. Renders the necessary data attributes for select2 and adds the static form media. """ url_name = "%s:autocomplete" def __init__(self, field, admin_site, attrs=None, choices=(), using=None): self.field = field self.admin_site = admin_site self.db = using self.choices = choices self.attrs = {} if attrs is None else attrs.copy() self.i18n_name = get_select2_language() def get_url(self): return reverse(self.url_name % self.admin_site.name) def build_attrs(self, base_attrs, extra_attrs=None): """ Set select2's AJAX attributes. Attributes can be set using the html5 data attribute. Nested attributes require a double dash as per https://select2.org/configuration/data-attributes#nested-subkey-options """ attrs = super().build_attrs(base_attrs, extra_attrs=extra_attrs) attrs.setdefault("class", "") attrs.update( { "data-ajax--cache": "true", "data-ajax--delay": 250, "data-ajax--type": "GET", "data-ajax--url": self.get_url(), "data-app-label": self.field.model._meta.app_label, "data-model-name": self.field.model._meta.model_name, "data-field-name": self.field.name, "data-theme": "admin-autocomplete", "data-allow-clear": json.dumps(not self.is_required), "data-placeholder": "", # Allows clearing of the input. "lang": self.i18n_name, "class": attrs["class"] + (" " if attrs["class"] else "") + "admin-autocomplete", } ) return attrs def optgroups(self, name, value, attr=None): """Return selected options based on the ModelChoiceIterator.""" default = (None, [], 0) groups = [default] has_selected = False selected_choices = { str(v) for v in value if str(v) not in self.choices.field.empty_values } if not self.is_required and not self.allow_multiple_selected: default[1].append(self.create_option(name, "", "", False, 0)) remote_model_opts = self.field.remote_field.model._meta to_field_name = getattr( self.field.remote_field, "field_name", remote_model_opts.pk.attname ) to_field_name = remote_model_opts.get_field(to_field_name).attname choices = ( (getattr(obj, to_field_name), self.choices.field.label_from_instance(obj)) for obj in self.choices.queryset.using(self.db).filter( **{"%s__in" % to_field_name: selected_choices} ) ) for option_value, option_label in choices: selected = str(option_value) in value and ( has_selected is False or self.allow_multiple_selected ) has_selected |= selected index = len(default[1]) subgroup = default[1] subgroup.append( self.create_option( name, option_value, option_label, selected_choices, index ) ) return groups @property def media(self): extra = "" if settings.DEBUG else ".min" i18n_file = ( ("admin/js/vendor/select2/i18n/%s.js" % self.i18n_name,) if self.i18n_name else () ) return forms.Media( js=( "admin/js/vendor/jquery/jquery%s.js" % extra, "admin/js/vendor/select2/select2.full%s.js" % extra, ) + i18n_file + ( "admin/js/jquery.init.js", "admin/js/autocomplete.js", ), css={ "screen": ( "admin/css/vendor/select2/select2%s.css" % extra, "admin/css/autocomplete.css", ), }, ) class AutocompleteSelect(AutocompleteMixin, forms.Select): pass class AutocompleteSelectMultiple(AutocompleteMixin, forms.SelectMultiple): pass
04e8ae940e2db1bdf0b8052d2c64c68eb6f2c294975f474ba36a5408657c511c
from django.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 = "django.db.models.AutoField" default_site = "django.contrib.admin.sites.AdminSite" name = "django.contrib.admin" verbose_name = _("Administration") def ready(self): checks.register(check_dependencies, checks.Tags.admin) 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.autodiscover()
0a4b4e48834807b8f1a93f635afb2cbd2e68f34b5853351ce1efa215810c48a7
import datetime import decimal import json from collections import defaultdict from django.core.exceptions import FieldDoesNotExist from django.db import models, router from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import Collector from django.forms.utils import pretty_name from django.urls import NoReverseMatch, reverse from django.utils import formats, timezone from django.utils.html import format_html from django.utils.regex_helper import _lazy_re_compile from 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)" % "|".join([x[1:] for x in UNQUOTE_MAP])) class FieldIsAForeignKeyColumnName(Exception): """A field is a foreign key attname, i.e. <FK>_id.""" pass def lookup_spawns_duplicates(opts, lookup_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_name 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: if hasattr(field, "path_infos"): # This field is a relation; update opts to follow the relation. path_info = field.path_infos opts = path_info[-1].to_opts if any(path.m2m for path in path_info): # This field is a m2m relation so duplicates must be # handled. return True return False def prepare_lookup_value(key, value, separator=","): """ Return a lookup value prepared to be used in queryset filtering. """ # if key ends with __in, split parameter into separate values if key.endswith("__in"): value = value.split(separator) # if key ends with __isnull, special case '' and the string literals 'false' and '0' elif key.endswith("__isnull"): value = value.lower() not in ("", "false", "0") return value def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' and similarly problematic characters. Similar to urllib.parse.quote(), except that the quoting is slightly different so that it doesn't get automatically unquoted by the web browser. """ return s.translate(QUOTE_MAP) if isinstance(s, str) else s def unquote(s): """Undo the effects of quote().""" return UNQUOTE_RE.sub(lambda m: UNQUOTE_MAP[m[0]], s) def flatten(fields): """ Return a list which is a single level of flattening of the original list. """ flat = [] for field in fields: if isinstance(field, (list, tuple)): flat.extend(field) else: flat.append(field) return flat def flatten_fieldsets(fieldsets): """Return a list of field names from an admin fieldsets structure.""" field_names = [] for name, opts in fieldsets: field_names.extend(flatten(opts["fields"])) return field_names def get_deleted_objects(objs, request, admin_site): """ Find all objects related to ``objs`` that should also be deleted. ``objs`` must be a homogeneous iterable of objects (e.g. a QuerySet). Return a nested list of strings suitable for display in the template with the ``unordered_list`` filter. """ try: obj = objs[0] except IndexError: return [], {}, set(), [] else: using = router.db_for_write(obj._meta.model) collector = NestedObjects(using=using, origin=objs) collector.collect(objs) perms_needed = set() def format_callback(obj): model = obj.__class__ has_admin = model in admin_site._registry opts = obj._meta no_edit_link = "%s: %s" % (capfirst(opts.verbose_name), obj) if has_admin: if not admin_site._registry[model].has_delete_permission(request, obj): perms_needed.add(opts.verbose_name) try: admin_url = reverse( "%s:%s_%s_change" % (admin_site.name, opts.app_label, opts.model_name), None, (quote(obj.pk),), ) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link # Display a link to the admin page. return format_html( '{}: <a href="{}">{}</a>', capfirst(opts.verbose_name), admin_url, obj ) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link to_delete = collector.nested(format_callback) protected = [format_callback(obj) for obj in collector.protected] model_count = { model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items() } return to_delete, model_count, perms_needed, protected class NestedObjects(Collector): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.edges = {} # {from_instance: [to_instances]} self.protected = set() self.model_objs = defaultdict(set) def add_edge(self, source, target): self.edges.setdefault(source, []).append(target) def collect(self, objs, source=None, source_attr=None, **kwargs): for obj in objs: if source_attr and not source_attr.endswith("+"): related_name = source_attr % { "class": source._meta.model_name, "app_label": source._meta.app_label, } self.add_edge(getattr(obj, related_name), obj) else: self.add_edge(None, obj) self.model_objs[obj._meta.model].add(obj) try: return super().collect(objs, source_attr=source_attr, **kwargs) except models.ProtectedError as e: self.protected.update(e.protected_objects) except models.RestrictedError as e: self.protected.update(e.restricted_objects) def related_objects(self, related_model, related_fields, objs): qs = super().related_objects(related_model, related_fields, objs) return qs.select_related( *[related_field.name for related_field in related_fields] ) def _nested(self, obj, seen, format_callback): if obj in seen: return [] seen.add(obj) children = [] for child in self.edges.get(obj, ()): children.extend(self._nested(child, seen, format_callback)) if format_callback: ret = [format_callback(obj)] else: ret = [obj] if children: ret.append(children) return ret def nested(self, format_callback=None): """ Return the graph as a nested list. """ seen = set() roots = [] for root in self.edges.get(None, ()): roots.extend(self._nested(root, seen, format_callback)) return roots def can_fast_delete(self, *args, **kwargs): """ We always want to load the objects into memory so that we can display them to the user in confirm page. """ return False def model_format_dict(obj): """ Return a `dict` with keys 'verbose_name' and 'verbose_name_plural', typically for use with string formatting. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. """ if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { "verbose_name": opts.verbose_name, "verbose_name_plural": opts.verbose_name_plural, } def model_ngettext(obj, n=None): """ Return the appropriate `verbose_name` or `verbose_name_plural` value for `obj` depending on the count `n`. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. If `obj` is a `QuerySet` instance, `n` is optional and the length of the `QuerySet` is used. """ if isinstance(obj, models.query.QuerySet): if n is None: n = obj.count() obj = obj.model d = model_format_dict(obj) singular, plural = d["verbose_name"], d["verbose_name_plural"] return ngettext(singular, plural, n or 0) def lookup_field(name, obj, model_admin=None): opts = obj._meta try: f = _get_non_gfk_field(opts, name) except (FieldDoesNotExist, FieldIsAForeignKeyColumnName): # For non-field values, the value is either a method, property or # returned via a callable. if callable(name): attr = name value = attr(obj) elif hasattr(model_admin, name) and name != "__str__": attr = getattr(model_admin, name) value = attr(obj) else: attr = getattr(obj, name) if callable(attr): value = attr() else: value = attr f = None else: attr = None value = getattr(obj, name) return f, attr, value def _get_non_gfk_field(opts, name): """ For historical reasons, the admin app relies on GenericForeignKeys as being "not found" by get_field(). This could likely be cleaned up. Reverse relations should also be excluded as these aren't attributes of the model (rather something like `foo_set`). """ field = opts.get_field(name) if ( field.is_relation and # Generic foreign keys OR reverse relations ((field.many_to_one and not field.related_model) or field.one_to_many) ): raise FieldDoesNotExist() # Avoid coercing <FK>_id fields to FK if ( field.is_relation and not field.many_to_many and hasattr(field, "attname") and field.attname == name ): raise FieldIsAForeignKeyColumnName() return field def label_for_field(name, model, model_admin=None, return_attr=False, form=None): """ Return a sensible label for a field name. The name can be a callable, property (but not created with @property decorator), or the name of an object's attribute, as well as a model field. If return_attr is True, also return the resolved attribute (which could be a callable). This will be None if (and only if) the name refers to a field. """ attr = None try: field = _get_non_gfk_field(model._meta, name) try: label = field.verbose_name except AttributeError: # field is likely a ForeignObjectRel label = field.related_model._meta.verbose_name except FieldDoesNotExist: if name == "__str__": label = str(model._meta.verbose_name) attr = str else: if callable(name): attr = name elif hasattr(model_admin, name): attr = getattr(model_admin, name) elif hasattr(model, name): attr = getattr(model, name) elif form and name in form.fields: attr = form.fields[name] else: message = "Unable to lookup '%s' on %s" % ( name, model._meta.object_name, ) if model_admin: message += " or %s" % model_admin.__class__.__name__ if form: message += " or %s" % form.__class__.__name__ raise AttributeError(message) if hasattr(attr, "short_description"): label = attr.short_description elif ( isinstance(attr, property) and hasattr(attr, "fget") and hasattr(attr.fget, "short_description") ): label = attr.fget.short_description elif callable(attr): if attr.__name__ == "<lambda>": label = "--" else: label = pretty_name(attr.__name__) else: label = pretty_name(name) except FieldIsAForeignKeyColumnName: label = pretty_name(name) attr = name if return_attr: return (label, attr) else: return label def help_text_for_field(name, model): help_text = "" try: field = _get_non_gfk_field(model._meta, name) except (FieldDoesNotExist, FieldIsAForeignKeyColumnName): pass else: if hasattr(field, "help_text"): help_text = field.help_text return help_text def display_for_field(value, field, empty_value_display): from django.contrib.admin.templatetags.admin_list import _boolean_icon if getattr(field, "flatchoices", None): return dict(field.flatchoices).get(value, empty_value_display) # BooleanField needs special-case null-handling, so it comes before the # general null test. elif isinstance(field, models.BooleanField): return _boolean_icon(value) elif value is None: return empty_value_display elif isinstance(field, models.DateTimeField): return formats.localize(timezone.template_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, (models.IntegerField, models.FloatField)): return formats.number_format(value) elif isinstance(field, models.FileField) and value: return format_html('<a href="{}">{}</a>', value.url, value) elif isinstance(field, models.JSONField) and value: try: return json.dumps(value, ensure_ascii=False, cls=field.encoder) except TypeError: return display_for_value(value, empty_value_display) else: return display_for_value(value, empty_value_display) def display_for_value(value, empty_value_display, boolean=False): from django.contrib.admin.templatetags.admin_list import _boolean_icon if boolean: return _boolean_icon(value) elif value is None: return empty_value_display elif isinstance(value, bool): return str(value) elif isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (int, decimal.Decimal, float)): return formats.number_format(value) elif isinstance(value, (list, tuple)): return ", ".join(str(v) for v in value) else: return str(value) class NotRelationField(Exception): pass def get_model_from_relation(field): if hasattr(field, "path_infos"): return field.path_infos[-1].to_opts.model else: raise NotRelationField def reverse_field_path(model, path): """Create a reversed field path. E.g. Given (Order, "user__groups"), return (Group, "user__order"). Final field must be a related model, not a data field. """ reversed_path = [] parent = model pieces = path.split(LOOKUP_SEP) for piece in pieces: field = parent._meta.get_field(piece) # skip trailing data field if extant: if len(reversed_path) == len(pieces) - 1: # final iteration try: get_model_from_relation(field) except NotRelationField: break # Field should point to another model if field.is_relation and not (field.auto_created and not field.concrete): related_name = field.related_query_name() parent = field.remote_field.model else: related_name = field.field.name parent = field.related_model reversed_path.insert(0, related_name) return (parent, LOOKUP_SEP.join(reversed_path)) def get_fields_from_path(model, path): """Return list of Fields given path relative to model. e.g. (ModelX, "user__groups__name") -> [ <django.db.models.fields.related.ForeignKey object at 0x...>, <django.db.models.fields.related.ManyToManyField object at 0x...>, <django.db.models.fields.CharField object at 0x...>, ] """ pieces = path.split(LOOKUP_SEP) fields = [] for piece in pieces: if fields: parent = get_model_from_relation(fields[-1]) else: parent = model fields.append(parent._meta.get_field(piece)) return fields def construct_change_message(form, formsets, add): """ Construct a JSON structure describing changes from a changed object. Translations are deactivated so that strings are stored untranslated. Translation happens later on LogEntry access. """ # Evaluating `form.changed_data` prior to disabling translations is required # to avoid fields affected by localization from being included incorrectly, # e.g. where date formats differ such as MM/DD/YYYY vs DD/MM/YYYY. changed_data = form.changed_data with translation_override(None): # Deactivate translations while fetching verbose_name for form # field labels and using `field_name`, if verbose_name is not provided. # Translations will happen later on LogEntry access. changed_field_labels = _get_changed_field_labels_from_form(form, changed_data) change_message = [] if add: change_message.append({"added": {}}) elif form.changed_data: change_message.append({"changed": {"fields": changed_field_labels}}) if formsets: with translation_override(None): for formset in formsets: for added_object in formset.new_objects: change_message.append( { "added": { "name": str(added_object._meta.verbose_name), "object": str(added_object), } } ) for changed_object, changed_fields in formset.changed_objects: change_message.append( { "changed": { "name": str(changed_object._meta.verbose_name), "object": str(changed_object), "fields": _get_changed_field_labels_from_form( formset.forms[0], changed_fields ), } } ) for deleted_object in formset.deleted_objects: change_message.append( { "deleted": { "name": str(deleted_object._meta.verbose_name), "object": str(deleted_object), } } ) return change_message def _get_changed_field_labels_from_form(form, changed_data): changed_field_labels = [] for field_name in changed_data: try: verbose_field_name = form.fields[field_name].label or field_name except KeyError: verbose_field_name = field_name changed_field_labels.append(str(verbose_field_name)) return changed_field_labels
4c2e49229d28ba73e2d68d76b74dcdf8216f999f658bbf0bb2e4b38269e83c0d
""" This encapsulates the logic for displaying filters in the Django admin. Filters are specified in models with the "list_filter" option. Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ import datetime from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.utils import ( get_model_from_relation, prepare_lookup_value, reverse_field_path, ) from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ class ListFilter: title = None # Human-readable title to appear in the right sidebar. template = "admin/filter.html" def __init__(self, request, params, model, model_admin): # This dictionary will eventually contain the request's query string # parameters actually used by this filter. self.used_parameters = {} if self.title is None: raise ImproperlyConfigured( "The list filter '%s' does not specify a 'title'." % self.__class__.__name__ ) def has_output(self): """ Return True if some choices would be output for this filter. """ raise NotImplementedError( "subclasses 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 NotImplementedError( "subclasses of ListFilter must provide a choices() method" ) def queryset(self, request, queryset): """ Return the filtered queryset. """ raise NotImplementedError( "subclasses of ListFilter must provide a queryset() method" ) def expected_parameters(self): """ Return the list of parameter names that are expected from the request's query string and that will be used by this filter. """ raise NotImplementedError( "subclasses of ListFilter must provide an expected_parameters() method" ) class SimpleListFilter(ListFilter): # The parameter that should be used in the query string for that filter. parameter_name = None def __init__(self, request, params, model, model_admin): super().__init__(request, params, model, model_admin) if self.parameter_name is None: raise ImproperlyConfigured( "The list filter '%s' does not specify a 'parameter_name'." % self.__class__.__name__ ) if self.parameter_name in params: value = params.pop(self.parameter_name) self.used_parameters[self.parameter_name] = value lookup_choices = self.lookups(request, model_admin) if lookup_choices is None: lookup_choices = () self.lookup_choices = list(lookup_choices) def has_output(self): return len(self.lookup_choices) > 0 def value(self): """ Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided. """ return self.used_parameters.get(self.parameter_name) def lookups(self, request, model_admin): """ Must be overridden to return a list of tuples (value, verbose value) """ raise NotImplementedError( "The SimpleListFilter.lookups() method must be overridden to " "return a list of tuples (value, verbose value)." ) def expected_parameters(self): return [self.parameter_name] def choices(self, changelist): yield { "selected": self.value() is None, "query_string": changelist.get_query_string(remove=[self.parameter_name]), "display": _("All"), } for lookup, title in self.lookup_choices: yield { "selected": self.value() == str(lookup), "query_string": changelist.get_query_string( {self.parameter_name: lookup} ), "display": title, } class FieldListFilter(ListFilter): _field_list_filters = [] _take_priority_index = 0 list_separator = "," def __init__(self, field, request, params, model, model_admin, field_path): self.field = field self.field_path = field_path self.title = getattr(field, "verbose_name", field_path) super().__init__(request, params, model, model_admin) for p in self.expected_parameters(): if p in params: value = params.pop(p) self.used_parameters[p] = prepare_lookup_value( p, value, self.list_separator ) def has_output(self): return True def queryset(self, request, queryset): try: return queryset.filter(**self.used_parameters) except (ValueError, ValidationError) as e: # Fields may raise a ValueError or ValidationError when converting # the parameters to the correct type. raise IncorrectLookupParameters(e) @classmethod def register(cls, test, list_filter_class, take_priority=False): if take_priority: # This is to allow overriding the default filters for certain types # of fields with some custom filters. The first found in the list # is used in priority. cls._field_list_filters.insert( cls._take_priority_index, (test, list_filter_class) ) cls._take_priority_index += 1 else: cls._field_list_filters.append((test, list_filter_class)) @classmethod def create(cls, field, request, params, model, model_admin, field_path): for test, list_filter_class in cls._field_list_filters: if test(field): return list_filter_class( field, request, params, model, model_admin, field_path=field_path ) class RelatedFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): other_model = get_model_from_relation(field) self.lookup_kwarg = "%s__%s__exact" % (field_path, field.target_field.name) self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = params.get(self.lookup_kwarg_isnull) super().__init__(field, request, params, model, model_admin, field_path) self.lookup_choices = self.field_choices(field, request, model_admin) if hasattr(field, "verbose_name"): self.lookup_title = field.verbose_name else: self.lookup_title = other_model._meta.verbose_name self.title = self.lookup_title self.empty_value_display = model_admin.get_empty_value_display() @property def include_empty_choice(self): """ Return True if a "(None)" choice should be included, which filters out everything except empty relationships. """ return self.field.null or (self.field.is_relation and self.field.many_to_many) def has_output(self): if self.include_empty_choice: extra = 1 else: extra = 0 return len(self.lookup_choices) + extra > 1 def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def field_admin_ordering(self, field, request, model_admin): """ Return the model admin's ordering for related field, if provided. """ related_admin = model_admin.admin_site._registry.get(field.remote_field.model) if related_admin is not None: return related_admin.get_ordering(request) return () def field_choices(self, field, request, model_admin): ordering = self.field_admin_ordering(field, request, model_admin) return field.get_choices(include_blank=False, ordering=ordering) def choices(self, changelist): yield { "selected": self.lookup_val is None and not self.lookup_val_isnull, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } for pk_val, val in self.lookup_choices: yield { "selected": self.lookup_val == str(pk_val), "query_string": changelist.get_query_string( {self.lookup_kwarg: pk_val}, [self.lookup_kwarg_isnull] ), "display": val, } if self.include_empty_choice: yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": self.empty_value_display, } FieldListFilter.register(lambda f: f.remote_field, RelatedFieldListFilter) class BooleanFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__exact" % field_path self.lookup_kwarg2 = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val2 = params.get(self.lookup_kwarg2) super().__init__(field, request, params, model, model_admin, field_path) if ( self.used_parameters and self.lookup_kwarg in self.used_parameters and self.used_parameters[self.lookup_kwarg] in ("1", "0") ): self.used_parameters[self.lookup_kwarg] = bool( int(self.used_parameters[self.lookup_kwarg]) ) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg2] def choices(self, changelist): field_choices = dict(self.field.flatchoices) for lookup, title in ( (None, _("All")), ("1", field_choices.get(True, _("Yes"))), ("0", field_choices.get(False, _("No"))), ): yield { "selected": self.lookup_val == lookup and not self.lookup_val2, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup}, [self.lookup_kwarg2] ), "display": title, } if self.field.null: yield { "selected": self.lookup_val2 == "True", "query_string": changelist.get_query_string( {self.lookup_kwarg2: "True"}, [self.lookup_kwarg] ), "display": field_choices.get(None, _("Unknown")), } FieldListFilter.register( lambda f: isinstance(f, models.BooleanField), BooleanFieldListFilter ) class ChoicesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__exact" % field_path self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = params.get(self.lookup_kwarg_isnull) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def choices(self, changelist): yield { "selected": self.lookup_val is None, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } none_title = "" for lookup, title in self.field.flatchoices: if lookup is None: none_title = title continue yield { "selected": str(lookup) == self.lookup_val, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup}, [self.lookup_kwarg_isnull] ), "display": title, } if none_title: yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": none_title, } FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter) class DateFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.field_generic = "%s__" % field_path self.date_params = { k: v for k, v in params.items() if k.startswith(self.field_generic) } now = timezone.now() # When time zone support is enabled, convert "now" to the user's time # zone so Django's definition of "Today" matches what the user expects. if timezone.is_aware(now): now = timezone.localtime(now) if isinstance(field, models.DateTimeField): today = now.replace(hour=0, minute=0, second=0, microsecond=0) else: # field is a models.DateField today = now.date() tomorrow = today + datetime.timedelta(days=1) if today.month == 12: next_month = today.replace(year=today.year + 1, month=1, day=1) else: next_month = today.replace(month=today.month + 1, day=1) next_year = today.replace(year=today.year + 1, month=1, day=1) self.lookup_kwarg_since = "%s__gte" % field_path self.lookup_kwarg_until = "%s__lt" % field_path self.links = ( (_("Any date"), {}), ( _("Today"), { self.lookup_kwarg_since: str(today), self.lookup_kwarg_until: str(tomorrow), }, ), ( _("Past 7 days"), { self.lookup_kwarg_since: str(today - datetime.timedelta(days=7)), self.lookup_kwarg_until: str(tomorrow), }, ), ( _("This month"), { self.lookup_kwarg_since: str(today.replace(day=1)), self.lookup_kwarg_until: str(next_month), }, ), ( _("This year"), { self.lookup_kwarg_since: str(today.replace(month=1, day=1)), self.lookup_kwarg_until: str(next_year), }, ), ) if field.null: self.lookup_kwarg_isnull = "%s__isnull" % field_path self.links += ( (_("No date"), {self.field_generic + "isnull": "True"}), (_("Has date"), {self.field_generic + "isnull": "False"}), ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): params = [self.lookup_kwarg_since, self.lookup_kwarg_until] if self.field.null: params.append(self.lookup_kwarg_isnull) return params def choices(self, changelist): for title, param_dict in self.links: yield { "selected": self.date_params == param_dict, "query_string": changelist.get_query_string( param_dict, [self.field_generic] ), "display": title, } FieldListFilter.register(lambda f: isinstance(f, models.DateField), DateFieldListFilter) # This should be registered last, because it's a last resort. For example, # if a field is eligible to use the BooleanFieldListFilter, that'd be much # more appropriate, and the AllValuesFieldListFilter won't get used for it. class AllValuesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = field_path self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = params.get(self.lookup_kwarg_isnull) self.empty_value_display = model_admin.get_empty_value_display() parent_model, reverse_path = reverse_field_path(model, field_path) # Obey parent ModelAdmin queryset when deciding which options to show if model == parent_model: queryset = model_admin.get_queryset(request) else: queryset = parent_model._default_manager.all() self.lookup_choices = ( queryset.distinct().order_by(field.name).values_list(field.name, flat=True) ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def choices(self, changelist): yield { "selected": self.lookup_val is None and self.lookup_val_isnull is None, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } include_none = False for val in self.lookup_choices: if val is None: include_none = True continue val = str(val) yield { "selected": self.lookup_val == val, "query_string": changelist.get_query_string( {self.lookup_kwarg: val}, [self.lookup_kwarg_isnull] ), "display": val, } if include_none: yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": self.empty_value_display, } FieldListFilter.register(lambda f: True, AllValuesFieldListFilter) class RelatedOnlyFieldListFilter(RelatedFieldListFilter): def field_choices(self, field, request, model_admin): pk_qs = ( model_admin.get_queryset(request) .distinct() .values_list("%s__pk" % self.field_path, flat=True) ) ordering = self.field_admin_ordering(field, request, model_admin) return field.get_choices( include_blank=False, limit_choices_to={"pk__in": pk_qs}, ordering=ordering ) class EmptyFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): if not field.empty_strings_allowed and not field.null: raise ImproperlyConfigured( "The list filter '%s' cannot be used with field '%s' which " "doesn't allow empty strings and nulls." % ( self.__class__.__name__, field.name, ) ) self.lookup_kwarg = "%s__isempty" % field_path self.lookup_val = params.get(self.lookup_kwarg) super().__init__(field, request, params, model, model_admin, field_path) def queryset(self, request, queryset): if self.lookup_kwarg not in self.used_parameters: return queryset if self.lookup_val not in ("0", "1"): raise IncorrectLookupParameters lookup_conditions = [] if self.field.empty_strings_allowed: lookup_conditions.append((self.field_path, "")) if self.field.null: lookup_conditions.append((f"{self.field_path}__isnull", True)) lookup_condition = models.Q(*lookup_conditions, _connector=models.Q.OR) if self.lookup_val == "1": return queryset.filter(lookup_condition) return queryset.exclude(lookup_condition) def expected_parameters(self): return [self.lookup_kwarg] def choices(self, changelist): for lookup, title in ( (None, _("All")), ("1", _("Empty")), ("0", _("Not empty")), ): yield { "selected": self.lookup_val == lookup, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup} ), "display": title, }
d14089b2d9a605fa7f73fd00aa500b250632f5bc57a3d7eaa1040809038d184a
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_messages = { **AuthenticationForm.error_messages, "invalid_login": _( "Please enter the correct %(username)s and password for a staff " "account. Note that 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 ValidationError( self.error_messages["invalid_login"], code="invalid_login", params={"username": self.username_field.verbose_name}, ) class AdminPasswordChangeForm(PasswordChangeForm): required_css_class = "required"
2c7dcf4db07857581b05cf27982c3706c4ae03c2dad1f34e6f8712212bc90302
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class HumanizeConfig(AppConfig): name = "django.contrib.humanize" verbose_name = _("Humanize")
56a50f8cd4e31eb2592f9a7230f72b445da59aa2b38d917d9dab3f9a7c888da3
import functools import os from django.apps import apps from django.conf import settings from django.contrib.staticfiles import utils from django.core.checks import Error, Warning from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import FileSystemStorage, Storage, default_storage from django.utils._os import safe_join from django.utils.functional import LazyObject, empty 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 NotImplementedError( "subclasses may provide a check() method to verify the finder is " "configured correctly." ) def find(self, path, all=False): """ Given a relative file path, find an absolute file path. If the ``all`` parameter is False (default) return only the first found file path; if True, return a list of all found files paths. """ raise NotImplementedError( "subclasses of BaseFinder must provide a find() method" ) def list(self, ignore_patterns): """ 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 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 locations with static files self.locations = [] # Maps dir paths to an appropriate storage instance self.storages = {} for root in settings.STATICFILES_DIRS: if isinstance(root, (list, tuple)): prefix, root = root else: prefix = "" if (prefix, root) not in self.locations: self.locations.append((prefix, root)) for prefix, root in self.locations: filesystem_storage = FileSystemStorage(location=root) filesystem_storage.prefix = prefix self.storages[root] = filesystem_storage super().__init__(*args, **kwargs) def check(self, **kwargs): errors = [] if not isinstance(settings.STATICFILES_DIRS, (list, tuple)): errors.append( Error( "The STATICFILES_DIRS setting is not a tuple or list.", hint="Perhaps you forgot a trailing comma?", id="staticfiles.E001", ) ) return errors for root in settings.STATICFILES_DIRS: if isinstance(root, (list, tuple)): prefix, root = root if prefix.endswith("/"): errors.append( Error( "The prefix %r in the STATICFILES_DIRS setting must " "not end with a slash." % prefix, id="staticfiles.E003", ) ) if settings.STATIC_ROOT and os.path.abspath( settings.STATIC_ROOT ) == os.path.abspath(root): errors.append( Error( "The STATICFILES_DIRS setting should not contain the " "STATIC_ROOT setting.", id="staticfiles.E002", ) ) if not os.path.isdir(root): errors.append( Warning( f"The directory '{root}' in the STATICFILES_DIRS setting " f"does not exist.", id="staticfiles.W004", ) ) return errors def find(self, path, all=False): """ Look for files in the extra locations as defined in STATICFILES_DIRS. """ matches = [] for prefix, root in self.locations: if root not in searched_locations: searched_locations.append(root) matched_path = self.find_location(root, path, prefix) if matched_path: if not all: return matched_path matches.append(matched_path) return matches def find_location(self, root, path, prefix=None): """ Find a requested static file in a location and return the found absolute path (or ``None`` if no match). """ if prefix: prefix = "%s%s" % (prefix, os.sep) if not path.startswith(prefix): return None path = path[len(prefix) :] path = safe_join(root, path) if os.path.exists(path): return path def list(self, ignore_patterns): """ List all files in all locations. """ for prefix, root in self.locations: # Skip nonexistent directories. if os.path.isdir(root): storage = self.storages[root] for path in utils.get_files(storage, ignore_patterns): yield path, storage class AppDirectoriesFinder(BaseFinder): """ A static files finder that looks in the directory of each app as specified in the source_dir attribute. """ storage_class = FileSystemStorage source_dir = "static" def __init__(self, app_names=None, *args, **kwargs): # The list of apps that are handled self.apps = [] # Mapping of app names to storage instances self.storages = {} app_configs = apps.get_app_configs() if app_names: app_names = set(app_names) app_configs = [ac for ac in app_configs if ac.name in app_names] for app_config in app_configs: app_storage = self.storage_class( os.path.join(app_config.path, self.source_dir) ) if os.path.isdir(app_storage.location): self.storages[app_config.name] = app_storage if app_config.name not in self.apps: self.apps.append(app_config.name) super().__init__(*args, **kwargs) def list(self, ignore_patterns): """ List all files in all app storages. """ for storage in self.storages.values(): if storage.exists(""): # check if storage location exists for path in utils.get_files(storage, ignore_patterns): yield path, storage def find(self, path, all=False): """ Look for files in the app directories. """ matches = [] for app in self.apps: app_location = self.storages[app].location if app_location not in searched_locations: searched_locations.append(app_location) match = self.find_in_app(app, path) if match: if not all: return match matches.append(match) return matches def find_in_app(self, app, path): """ Find a requested static file in an app's static locations. """ storage = self.storages.get(app) # Only try to find a file if the source dir actually exists. if storage and storage.exists(path): matched_path = storage.path(path) if matched_path: return matched_path class BaseStorageFinder(BaseFinder): """ A base static files finder to be used to extended with an own storage class. """ storage = None def __init__(self, storage=None, *args, **kwargs): if storage is not None: self.storage = storage if self.storage is None: raise ImproperlyConfigured( "The staticfiles storage finder %r " "doesn't have a storage class " "assigned." % self.__class__ ) # Make sure we have a storage instance here. if not isinstance(self.storage, (Storage, LazyObject)): self.storage = self.storage() super().__init__(*args, **kwargs) def find(self, path, all=False): """ Look for files in the default file storage, if it's local. """ try: self.storage.path("") except NotImplementedError: pass else: if self.storage.location not in searched_locations: searched_locations.append(self.storage.location) if self.storage.exists(path): match = self.storage.path(path) if all: match = [match] return match return [] def list(self, ignore_patterns): """ List all files of the storage. """ for path in utils.get_files(self.storage, ignore_patterns): yield path, self.storage class DefaultStorageFinder(BaseStorageFinder): """ A static files finder that uses the default storage backend. """ storage = default_storage def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) base_location = getattr(self.storage, "base_location", empty) if not base_location: raise ImproperlyConfigured( "The storage backend of the " "staticfiles finder %r doesn't have " "a valid location." % self.__class__ ) def find(path, all=False): """ Find a static file with the given path using all enabled finders. If ``all`` is ``False`` (default), return the first matching absolute path (or ``None`` if no match). Otherwise return a list. """ searched_locations[:] = [] matches = [] for finder in get_finders(): result = finder.find(path, all=all) if not all and result: return result if not isinstance(result, (list, tuple)): result = [result] matches.extend(result) if matches: return matches # No match. return [] if all else None def get_finders(): for finder_path in settings.STATICFILES_FINDERS: yield get_finder(finder_path) @functools.lru_cache(maxsize=None) def get_finder(import_path): """ Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class. """ Finder = import_string(import_path) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured( 'Finder "%s" is not a subclass of "%s"' % (Finder, BaseFinder) ) return Finder()
1c6cd51a05789eff2fdb45f1cd7f4bd5d5dd37157b722c18cd6c46d52d0627a7
from urllib.parse import urlparse from urllib.request import url2pathname from asgiref.sync import sync_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_info from django.http import Http404 class StaticFilesHandlerMixin: """ Common methods used by WSGI and ASGI handlers. """ # May be used to differentiate between handler types (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 get_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 * the request's path isn't under the media path (or equal) """ return path.startswith(self.base_url[2]) and not self.base_url[1] def file_path(self, url): """ Return the relative path to the media file on disk for the given URL. """ relative_url = url[len(self.base_url[2]) :] return url2pathname(relative_url) def serve(self, request): """Serve the request path.""" return serve(request, self.file_path(request.path), insecure=True) def get_response(self, request): try: return self.serve(request) except Http404 as e: return response_for_exception(request, e) async def get_response_async(self, request): try: return await sync_to_async(self.serve, thread_sensitive=False)(request) except Http404 as e: return await sync_to_async(response_for_exception, thread_sensitive=False)( request, e ) class StaticFilesHandler(StaticFilesHandlerMixin, WSGIHandler): """ WSGI middleware that intercepts calls to the static files directory, as defined by the STATIC_URL setting, and serves those files. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) super().__init__() def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) return super().__call__(environ, start_response) class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler): """ ASGI application which wraps another and intercepts requests for static files, passing them off to Django's static file serving. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) async def __call__(self, scope, receive, send): # Only even look at HTTP requests if scope["type"] == "http" and self._should_handle(scope["path"]): # Serve static content # (the one thing super() doesn't do is __call__, apparently) return await super().__call__(scope, receive, send) # Hand off to the main app return await self.application(scope, receive, send)
49b788eadd2707da4ee7aaa9c32c516203efbc27c0bdb2d3c0c24303315f9fa5
from django.apps import AppConfig from django.contrib.staticfiles.checks import check_finders from django.core import checks from django.utils.translation import gettext_lazy as _ class StaticFilesConfig(AppConfig): name = "django.contrib.staticfiles" verbose_name = _("Static Files") ignore_patterns = ["CVS", ".*", "*~"] def ready(self): checks.register(check_finders, checks.Tags.staticfiles)
88f5c7034c8c5eedfb3d0c02aeaf738e14b38d97ffcc405727e7471aca99a17f
import fnmatch import os from django.conf import settings 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 patterns) def get_files(storage, ignore_patterns=None, location=""): """ Recursively walk the storage directories yielding the paths of all files that should be copied. """ 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): continue 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_patterns(dir, ignore_patterns): continue if location: dir = os.path.join(location, dir) yield from get_files(storage, ignore_patterns, dir) def check_settings(base_url=None): """ Check if the staticfiles settings have sane values. """ if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the required STATIC_URL setting." ) if settings.MEDIA_URL == base_url: raise ImproperlyConfigured( "The MEDIA_URL and STATIC_URL settings must have different values" ) if ( settings.DEBUG and settings.MEDIA_URL and settings.STATIC_URL and settings.MEDIA_URL.startswith(settings.STATIC_URL) ): raise ImproperlyConfigured( "runserver can't serve media if MEDIA_URL is within STATIC_URL." ) if (settings.MEDIA_ROOT and settings.STATIC_ROOT) and ( settings.MEDIA_ROOT == settings.STATIC_ROOT ): raise ImproperlyConfigured( "The MEDIA_ROOT and STATIC_ROOT settings must have different values" )
5da7315f06e12e5726c61b29783398bcd1743a132d48c3871a8bb1a907f48e55
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import 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 serve(request, path, insecure=False, **kwargs): """ Serve static files below a given point in the directory structure or from locations inferred from the staticfiles finders. To use, 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. """ 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 == "": raise Http404("Directory indexes are not allowed here.") raise Http404("'%s' could not be found" % path) document_root, path = os.path.split(absolute_path) return static.serve(request, path, document_root=document_root, **kwargs)
e4f8cd870742b481767a42e1364b8c7c638ea2677497c002c406375b048ce5b1
import json import os import posixpath import re from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit from django.conf import settings from django.contrib.staticfiles.utils import check_settings, matches_patterns from django.core.exceptions import ImproperlyConfigured from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage, get_storage_class from django.utils.crypto import md5 from django.utils.functional import LazyObject class StaticFilesStorage(FileSystemStorage): """ Standard file system storage for static 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.STATIC_URL check_settings(base_url) super().__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, 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( "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("%(url)s")""" max_post_process_passes = 5 patterns = ( ( "*.css", ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", ( r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""", """@import url("%(url)s")""", ), ( r"(?m)(?P<matched>)^(/\*# (?-i:sourceMappingURL)=(?P<url>.*) \*/)$", "/*# sourceMappingURL=%(url)s */", ), ), ), ( "*.js", ( ( r"(?m)(?P<matched>)^(//# (?-i:sourceMappingURL)=(?P<url>.*))$", "//# sourceMappingURL=%(url)s", ), ), ), ) keep_intermediate_files = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._patterns = {} self.hashed_files = {} for extension, patterns in self.patterns: for pattern in patterns: if isinstance(pattern, (tuple, list)): pattern, template = pattern else: template = self.default_template compiled = re.compile(pattern, re.IGNORECASE) self._patterns.setdefault(extension, []).append((compiled, template)) def file_hash(self, name, content=None): """ Return a hash of the file with the given name and optional content. """ if content is None: return None hasher = md5(usedforsecurity=False) for chunk in content.chunks(): hasher.update(chunk) return hasher.hexdigest()[:12] def hashed_name(self, name, content=None, filename=None): # `filename` is the name of file to hash if `content` isn't given. # `name` is the base name to construct the new hashed filename from. parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() filename = (filename and urlsplit(unquote(filename)).path.strip()) or clean_name opened = content is None if opened: if not self.exists(filename): raise ValueError( "The file '%s' could not be found with %r." % (filename, self) ) try: content = self.open(filename) except OSError: # Handle directory paths and fragments return name try: file_hash = self.file_hash(clean_name, content) finally: if opened: content.close() path, filename = os.path.split(clean_name) root, ext = os.path.splitext(filename) file_hash = (".%s" % file_hash) if file_hash else "" hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext)) unparsed_name = list(parsed_name) unparsed_name[2] = hashed_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) def _url(self, hashed_name_func, name, force=False, hashed_files=None): """ Return the non-hashed URL in DEBUG mode. """ if settings.DEBUG and not force: hashed_name, fragment = name, "" else: clean_name, fragment = urldefrag(name) if urlsplit(clean_name).path.endswith("/"): # don't hash paths hashed_name = name else: args = (clean_name,) if hashed_files is not None: args += (hashed_files,) hashed_name = hashed_name_func(*args) final_url = super().url(hashed_name) # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax query_fragment = "?#" in name # [sic!] if fragment or query_fragment: urlparts = list(urlsplit(final_url)) if fragment and not urlparts[4]: urlparts[4] = fragment if query_fragment and not urlparts[3]: urlparts[2] += "?" final_url = urlunsplit(urlparts) return unquote(final_url) def url(self, name, force=False): """ Return the non-hashed URL in DEBUG mode. """ return self._url(self.stored_name, name, force) def url_converter(self, name, hashed_files, template=None): """ Return the custom URL converter for the given file name. """ if template is None: template = self.default_template def converter(matchobj): """ Convert the matched URL to a normalized and hashed URL. This requires figuring out which files the matched URL resolves to and calling the url() method of the storage. """ matches = matchobj.groupdict() matched = matches["matched"] url = matches["url"] # Ignore absolute/protocol-relative and data-uri URLs. if re.match(r"^[a-z]+:", url): return matched # Ignore absolute URLs that don't point to a static file (dynamic # CSS / JS?). Note that STATIC_URL cannot be empty. if url.startswith("/") and not url.startswith(settings.STATIC_URL): return matched # Strip off the fragment so a path-like fragment won't interfere. url_path, fragment = urldefrag(url) if url_path.startswith("/"): # Otherwise the condition above would have returned prematurely. assert url_path.startswith(settings.STATIC_URL) target_name = url_path[len(settings.STATIC_URL) :] else: # We're using the posixpath module to mix paths and URLs conveniently. source_name = name if os.sep == "/" else name.replace(os.sep, "/") target_name = posixpath.join(posixpath.dirname(source_name), url_path) # Determine the hashed name of the target file with the storage backend. hashed_url = self._url( self._stored_name, unquote(target_name), force=True, hashed_files=hashed_files, ) transformed_url = "/".join( url_path.split("/")[:-1] + hashed_url.split("/")[-1:] ) # Restore the fragment that was stripped off earlier. if fragment: transformed_url += ("?#" if "?#" in url else "#") + fragment # Return the hashed version to the file matches["url"] = unquote(transformed_url) return template % matches return converter def post_process(self, paths, dry_run=False, **options): """ Post process the given dictionary of files (called from collectstatic). Processing is actually two separate operations: 1. renaming files to include a hash of their content for cache-busting, and copying those files to the target storage. 2. adjusting files which contain references to other files so they refer to the cache-busting filenames. If either of these are performed on a file, then that file is considered post-processed. """ # don't even dare to process the files if we're in dry run mode if dry_run: return # where to store the new paths hashed_files = {} # build a list of adjustable files adjustable_paths = [ path for path in paths if matches_patterns(path, self._patterns) ] # Adjustable files to yield at end, keyed by the original path. processed_adjustable_paths = {} # Do a single pass first. Post-process all files once, yielding not # adjustable files and exceptions, and collecting adjustable files. for name, hashed_name, processed, _ in self._post_process( paths, adjustable_paths, hashed_files ): if name not in adjustable_paths or isinstance(processed, Exception): yield name, hashed_name, processed else: processed_adjustable_paths[name] = (name, hashed_name, processed) paths = {path: paths[path] for path in adjustable_paths} substitutions = False for i in range(self.max_post_process_passes): substitutions = False for name, hashed_name, processed, subst in self._post_process( paths, adjustable_paths, hashed_files ): # Overwrite since hashed_name may be newer. processed_adjustable_paths[name] = (name, hashed_name, processed) substitutions = substitutions or subst if not substitutions: break if substitutions: yield "All", None, RuntimeError("Max post-process passes exceeded.") # Store the processed paths self.hashed_files.update(hashed_files) # Yield adjustable files with final, hashed name. yield from processed_adjustable_paths.values() def _post_process(self, paths, adjustable_paths, hashed_files): # Sort the files by directory level def path_level(name): return len(name.split(os.sep)) for name in sorted(paths, key=path_level, reverse=True): substitutions = True # use the original, local file, not the copied-but-unprocessed # file, which might be somewhere far away, like S3 storage, path = paths[name] with storage.open(path) as original_file: cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) # generate the hash with the original content, even for # adjustable files. if hash_key not in hashed_files: hashed_name = self.hashed_name(name, original_file) else: hashed_name = hashed_files[hash_key] # then get the original's file content.. if hasattr(original_file, "seek"): original_file.seek(0) hashed_file_exists = self.exists(hashed_name) processed = False # ..to apply each replacement pattern to the content if name in adjustable_paths: old_hashed_name = hashed_name content = original_file.read().decode("utf-8") for extension, patterns in self._patterns.items(): if matches_patterns(path, (extension,)): for pattern, template in patterns: converter = self.url_converter( name, hashed_files, template ) try: content = pattern.sub(converter, content) except ValueError as exc: yield name, None, exc, False if hashed_file_exists: self.delete(hashed_name) # then save the processed result content_file = ContentFile(content.encode()) if self.keep_intermediate_files: # Save intermediate file for reference self._save(hashed_name, content_file) hashed_name = self.hashed_name(name, content_file) if self.exists(hashed_name): self.delete(hashed_name) saved_name = self._save(hashed_name, content_file) hashed_name = self.clean_name(saved_name) # If the file hash stayed the same, this file didn't change if old_hashed_name == hashed_name: substitutions = False processed = True if not processed: # or handle the case in which neither processing nor # a change to the original file happened if not hashed_file_exists: processed = True saved_name = self._save(hashed_name, original_file) hashed_name = self.clean_name(saved_name) # and then set the cache accordingly hashed_files[hash_key] = hashed_name yield name, hashed_name, processed, substitutions def clean_name(self, name): return name.replace("\\", "/") def hash_key(self, name): return name def _stored_name(self, name, hashed_files): # Normalize the path to avoid multiple names for the same file like # ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same # path. name = posixpath.normpath(name) cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = hashed_files.get(hash_key) if cache_name is None: cache_name = self.clean_name(self.hashed_name(name)) return cache_name def stored_name(self, name): cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = self.hashed_files.get(hash_key) if cache_name: return cache_name # No cached name found, recalculate it from the files. intermediate_name = name for i in range(self.max_post_process_passes + 1): cache_name = self.clean_name( self.hashed_name(name, content=None, filename=intermediate_name) ) if intermediate_name == cache_name: # Store the hashed name if there was a miss. self.hashed_files[hash_key] = cache_name return cache_name else: # Move on to the next intermediate file. intermediate_name = cache_name # If the cache name can't be determined after the max number of passes, # the intermediate files on disk may be corrupt; avoid an infinite loop. raise ValueError("The name '%s' could not be hashed with %r." % (name, self)) class ManifestFilesMixin(HashedFilesMixin): manifest_version = "1.0" # the manifest format standard manifest_name = "staticfiles.json" manifest_strict = True keep_intermediate_files = False def __init__(self, *args, manifest_storage=None, **kwargs): super().__init__(*args, **kwargs) if manifest_storage is None: manifest_storage = self self.manifest_storage = manifest_storage self.hashed_files = self.load_manifest() def read_manifest(self): try: with self.manifest_storage.open(self.manifest_name) as manifest: return manifest.read().decode() except FileNotFoundError: return None def load_manifest(self): content = self.read_manifest() if content is None: return {} try: stored = json.loads(content) except json.JSONDecodeError: pass else: version = stored.get("version") if version == "1.0": return stored.get("paths", {}) raise ValueError( "Couldn't load manifest '%s' (version %s)" % (self.manifest_name, self.manifest_version) ) def post_process(self, *args, **kwargs): self.hashed_files = {} yield from super().post_process(*args, **kwargs) if not kwargs.get("dry_run"): self.save_manifest() def save_manifest(self): payload = {"paths": self.hashed_files, "version": self.manifest_version} if self.manifest_storage.exists(self.manifest_name): self.manifest_storage.delete(self.manifest_name) contents = json.dumps(payload).encode() self.manifest_storage._save(self.manifest_name, ContentFile(contents)) def stored_name(self, name): parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() hash_key = self.hash_key(clean_name) cache_name = self.hashed_files.get(hash_key) if cache_name is None: if self.manifest_strict: raise ValueError( "Missing staticfiles manifest entry for '%s'" % clean_name ) cache_name = self.clean_name(self.hashed_name(name)) unparsed_name = list(parsed_name) unparsed_name[2] = cache_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) class ManifestStaticFilesStorage(ManifestFilesMixin, StaticFilesStorage): """ A static file system storage backend which also saves hashed copies of the files it saves. """ pass class ConfiguredStorage(LazyObject): def _setup(self): self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() staticfiles_storage = ConfiguredStorage()
dee81146c0f00790b7187396bed3b38c997ecb4caaaa361905238cb76e1062ec
from django.contrib.sites.models import Site from django.db import models from django.urls import NoReverseMatch, get_script_prefix, reverse from django.utils.encoding import iri_to_uri from django.utils.translation import gettext_lazy as _ class FlatPage(models.Model): url = models.CharField(_("URL"), max_length=100, db_index=True) title = models.CharField(_("title"), max_length=200) content = models.TextField(_("content"), blank=True) enable_comments = models.BooleanField(_("enable comments"), default=False) template_name = models.CharField( _("template name"), max_length=70, blank=True, help_text=_( "Example: “flatpages/contact_page.html”. If this isn’t provided, " "the system will use “flatpages/default.html”." ), ) registration_required = models.BooleanField( _("registration required"), help_text=_( "If this is checked, only logged-in users will be able to view the page." ), default=False, ) sites = models.ManyToManyField(Site, verbose_name=_("sites")) class Meta: db_table = "django_flatpage" verbose_name = _("flat page") verbose_name_plural = _("flat pages") ordering = ["url"] def __str__(self): return "%s -- %s" % (self.url, self.title) def get_absolute_url(self): from .views import flatpage for url in (self.url.lstrip("/"), self.url): try: return reverse(flatpage, kwargs={"url": url}) except NoReverseMatch: pass # Handle script prefix manually because we bypass reverse() return iri_to_uri(get_script_prefix().rstrip("/") + self.url)
ca77a63920e0bcaa027d114b5d9acfc23dbb53498f5179b176bb9eed23997aa4
from django.contrib import admin from django.contrib.flatpages.forms import FlatpageForm from django.contrib.flatpages.models import FlatPage from django.utils.translation import gettext_lazy as _ @admin.register(FlatPage) class FlatPageAdmin(admin.ModelAdmin): form = FlatpageForm fieldsets = ( (None, {"fields": ("url", "title", "content", "sites")}), ( _("Advanced options"), { "classes": ("collapse",), "fields": ("registration_required", "template_name"), }, ), ) list_display = ("url", "title") list_filter = ("sites", "registration_required") search_fields = ("url", "title")
fce95a0f159b32b52614d092e2ef919c1b20ebbac25acf10ce1fdce7cc2fb570
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class FlatPagesConfig(AppConfig): default_auto_field = "django.db.models.AutoField" name = "django.contrib.flatpages" verbose_name = _("Flat Pages")
0848593ac2f0bf7a8827586ce1e1e513fd0002d62389c6ffc91cecb2d635f5e8
from django.apps import apps as django_apps from django.contrib.sitemaps import Sitemap from django.core.exceptions import ImproperlyConfigured class FlatPageSitemap(Sitemap): def items(self): if not django_apps.is_installed("django.contrib.sites"): raise ImproperlyConfigured( "FlatPageSitemap requires django.contrib.sites, which isn't installed." ) Site = django_apps.get_model("sites.Site") current_site = Site.objects.get_current() return current_site.flatpage_set.filter(registration_required=False)
46cdfb223d7dd923ad4818dde0bc7d62da4835f10c83b5d1634d5d10e63c4608
from django.contrib.flatpages import views from django.urls import path urlpatterns = [ path("<path:url>", views.flatpage, name="django.contrib.flatpages.views.flatpage"), ]
332b84366b0fd569f4d5fadd552ba0ec99da6e2c281dff279be3ed84095ca10c
from django import forms from django.conf import settings from django.contrib.flatpages.models import FlatPage from django.core.exceptions import ValidationError from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ class FlatpageForm(forms.ModelForm): url = forms.RegexField( label=_("URL"), max_length=100, regex=r"^[-\w/\.~]+$", help_text=_( "Example: “/about/contact/”. Make sure to have leading and trailing " "slashes." ), error_messages={ "invalid": _( "This value must contain only letters, numbers, dots, " "underscores, dashes, slashes or tildes." ), }, ) class Meta: model = FlatPage fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self._trailing_slash_required(): self.fields["url"].help_text = _( "Example: “/about/contact”. Make sure to have a leading slash." ) def _trailing_slash_required(self): return ( settings.APPEND_SLASH and "django.middleware.common.CommonMiddleware" in settings.MIDDLEWARE ) def clean_url(self): url = self.cleaned_data["url"] if not url.startswith("/"): raise ValidationError( gettext("URL is missing a leading slash."), code="missing_leading_slash", ) if self._trailing_slash_required() and not url.endswith("/"): raise ValidationError( gettext("URL is missing a trailing slash."), code="missing_trailing_slash", ) return url def clean(self): url = self.cleaned_data.get("url") sites = self.cleaned_data.get("sites") same_url = FlatPage.objects.filter(url=url) if self.instance.pk: same_url = same_url.exclude(pk=self.instance.pk) if sites and same_url.filter(sites__in=sites).exists(): for site in sites: if same_url.filter(sites=site).exists(): raise ValidationError( _("Flatpage with url %(url)s already exists for site %(site)s"), code="duplicate_url", params={"url": url, "site": site}, ) return super().clean()
1f82c6ec96a76fa0dc9fecc834b9a9df9f2147ad098a000a1b38780383cc3da3
from django.conf import settings from django.contrib.flatpages.models import FlatPage from django.contrib.sites.shortcuts import get_current_site from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.template import loader from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_protect DEFAULT_TEMPLATE = "flatpages/default.html" # This view is called from FlatpageFallbackMiddleware.process_response # when a 404 is raised, which often means CsrfViewMiddleware.process_view # has not been called even if CsrfViewMiddleware is installed. So we need # to use @csrf_protect, in case the template needs {% csrf_token %}. # However, we can't just wrap this view; if no matching flatpage exists, # or a redirect is required for authentication, the 404 needs to be returned # without any CSRF checks. Therefore, we only # CSRF protect the internal implementation. def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or :template:`flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.startswith("/"): url = "/" + url site_id = get_current_site(request).id try: f = get_object_or_404(FlatPage, url=url, sites=site_id) except Http404: if not url.endswith("/") and settings.APPEND_SLASH: url += "/" f = get_object_or_404(FlatPage, url=url, sites=site_id) return HttpResponsePermanentRedirect("%s/" % request.path) else: raise return render_flatpage(request, f) @csrf_protect def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated: from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: template = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: template = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) return HttpResponse(template.render({"flatpage": f}, request))
00494692dbc58565c9b6527038aa549487aebf6b6190d33c17a6e896230bf385
""" Creates the default Site 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, apps=global_apps, **kwargs, ): try: Site = apps.get_model("sites", "Site") except LookupError: return if not router.allow_migrate_model(using, Site): return 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 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 example.com Site object") Site( pk=getattr(settings, "SITE_ID", 1), domain="example.com", name="example.com" ).save(using=using) # We set an explicit pk instead of relying on auto-incrementation, # so we need to reset the database sequence. See #17415. sequence_sql = connections[using].ops.sequence_reset_sql(no_style(), [Site]) if sequence_sql: if verbosity >= 2: print("Resetting sequence") with connections[using].cursor() as cursor: for command in sequence_sql: cursor.execute(command)
9de9154000c944e158c0a083edf966583310f6e2c069a2b3b4754a9797a6b967
from django.apps import apps from .requests import RequestSite def get_current_site(request): """ Check if contrib.sites is installed and return either the current ``Site`` object or a ``RequestSite`` object based on the request. """ # Import is inside the function because its point is to avoid importing the # Site models when django.contrib.sites isn't installed. if apps.is_installed("django.contrib.sites"): from .models import Site return Site.objects.get_current(request) else: return RequestSite(request)
6da00173a7e64de8cd9a4f0cddf72843572e236aa927317c638ec0d714adf206
class RequestSite: """ A class that shares the primary interface of Site (i.e., it has ``domain`` and ``name`` attributes) but gets its data from an HttpRequest object rather than from a database. The save() and delete() methods raise NotImplementedError. """ def __init__(self, request): self.domain = self.name = request.get_host() def __str__(self): return self.domain def save(self, force_insert=False, force_update=False): raise NotImplementedError("RequestSite cannot be saved.") def delete(self): raise NotImplementedError("RequestSite cannot be deleted.")
baa0ff0aedcfe0d0a9ed555d1a7d0dbc77e1b19074e4c2e688f9a0a2dfb2833e
from django.conf import settings 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): super().__init__() self.__field_name = field_name def check(self, **kwargs): errors = super().check(**kwargs) errors.extend(self._check_field_name()) return errors def _check_field_name(self): field_name = self._get_field_name() try: field = self.model._meta.get_field(field_name) except FieldDoesNotExist: return [ checks.Error( "CurrentSiteManager could not find a field named '%s'." % field_name, obj=self, id="sites.E001", ) ] if not field.many_to_many and not isinstance(field, (models.ForeignKey)): return [ checks.Error( "CurrentSiteManager cannot use '%s.%s' as it is not a foreign key " "or a many-to-many field." % (self.model._meta.object_name, field_name), obj=self, id="sites.E002", ) ] return [] def _get_field_name(self): """Return self.__field_name or 'site' or 'sites'.""" if not self.__field_name: try: self.model._meta.get_field("site") except FieldDoesNotExist: self.__field_name = "sites" else: self.__field_name = "site" return self.__field_name def get_queryset(self): return ( super() .get_queryset() .filter(**{self._get_field_name() + "__id": settings.SITE_ID}) )
4ac172715570e8971b30d175b4d8027a7f5d8b1f941ab3135b3f066dbf3469d4
from django.conf import settings from django.core.checks import Error def check_site_id(app_configs, **kwargs): if hasattr(settings, "SITE_ID") and not isinstance( settings.SITE_ID, (type(None), int) ): return [ Error("The SITE_ID setting must be an integer", id="sites.E101"), ] return []
35990c12a0f1aee955fb2db202afdd620d58dc6c5b23ba3b09ae0760e03ff7cb
import string from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db 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 common typos. """ checks = ((s in value) for s in string.whitespace) if any(checks): raise ValidationError( _("The domain name cannot contain any spaces or tabs."), 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) 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. if host not in SITE_CACHE: SITE_CACHE[host] = self.get(domain__iexact=host) return SITE_CACHE[host] except Site.DoesNotExist: # Fallback to looking up site after stripping port from the host. domain, port = split_domain_port(host) if domain not in SITE_CACHE: SITE_CACHE[domain] = self.get(domain__iexact=domain) return SITE_CACHE[domain] def get_current(self, request=None): """ Return the current Site based on the SITE_ID in the project's settings. If SITE_ID isn't defined, return the site with domain matching request.get_host(). The ``Site`` object is cached the first time it's retrieved from the database. """ from django.conf import settings if getattr(settings, "SITE_ID", ""): site_id = settings.SITE_ID return self._get_site_by_id(site_id) elif request: return self._get_site_by_request(request) raise ImproperlyConfigured( 'You\'re using the Django "sites framework" without having ' "set the SITE_ID setting. Create a site in your database and " "set the SITE_ID setting or pass a request to " "Site.objects.get_current() to fix this error." ) def clear_cache(self): """Clear the ``Site`` object cache.""" global SITE_CACHE SITE_CACHE = {} def get_by_natural_key(self, domain): return self.get(domain=domain) class Site(models.Model): domain = models.CharField( _("domain name"), max_length=100, validators=[_simple_domain_name_validator], unique=True, ) name = models.CharField(_("display name"), max_length=50) objects = SiteManager() class Meta: db_table = "django_site" verbose_name = _("site") verbose_name_plural = _("sites") ordering = ["domain"] def __str__(self): return self.domain def natural_key(self): return (self.domain,) def clear_site_cache(sender, **kwargs): """ Clear the cache (if primed) each time a site is saved or deleted. """ instance = kwargs["instance"] using = kwargs["using"] try: del SITE_CACHE[instance.pk] except KeyError: pass try: del SITE_CACHE[Site.objects.using(using).get(pk=instance.pk).domain] except (KeyError, Site.DoesNotExist): pass pre_save.connect(clear_site_cache, sender=Site) pre_delete.connect(clear_site_cache, sender=Site)
216bc60d05130cf114b1dfaebb17c7c49ab8b321ad75d34a51d90fd2799550c0
from django.contrib import admin from django.contrib.sites.models import Site @admin.register(Site) class SiteAdmin(admin.ModelAdmin): list_display = ("domain", "name") search_fields = ("domain", "name")
b812c75324284aea3543b3702d3c25bec4ee454d4c5f08f8b7a9515272017709
from django.apps import AppConfig from django.contrib.sites.checks import check_site_id from django.core import checks from django.db.models.signals import post_migrate from django.utils.translation import gettext_lazy as _ from .management import create_default_site class SitesConfig(AppConfig): default_auto_field = "django.db.models.AutoField" name = "django.contrib.sites" verbose_name = _("Sites") def ready(self): post_migrate.connect(create_default_site, sender=self) checks.register(check_site_id, checks.Tags.sites)
28a07ee0539f3ceeb44ccfaec6a2bc9bdb085f3077091c7b226afe8da6ae33f5
from itertools import chain from django.apps import apps from django.core.checks import Error def check_generic_foreign_keys(app_configs=None, **kwargs): from .fields import GenericForeignKey if app_configs is None: models = apps.get_models() else: models = chain.from_iterable( app_config.get_models() for app_config in app_configs ) errors = [] fields = ( obj for model in models for obj in vars(model).values() if isinstance(obj, GenericForeignKey) ) for field in fields: errors.extend(field.check()) return errors def check_model_name_lengths(app_configs=None, **kwargs): if app_configs is None: 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: errors.append( Error( "Model names must be at most 100 characters (got %d)." % (len(model._meta.model_name),), obj=model, id="contenttypes.E005", ) ) return errors
58dcb3421dc73f0bc911d51d6e0daec969d0447e14781326428b5cd7d6555b40
from collections import defaultdict from django.apps import apps from django.db import models from django.utils.translation import gettext_lazy as _ class ContentTypeManager(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: ct = self._cache[self.db][(app_label, model)] except KeyError: ct = self.get(app_label=app_label, model=model) self._add_to_cache(self.db, ct) 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 = (opts.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 are cached so that subsequent lookups for the same model don't hit the database. """ opts = self._get_opts(model, for_concrete_model) try: return self._get_from_cache(opts) except KeyError: pass # The ContentType entry was not found in the cache, therefore we # proceed to load or create it. try: # Start with get() and not get_or_create() in order to use # the db_for_read (see #20401). ct = self.get(app_label=opts.app_label, model=opts.model_name) except self.model.DoesNotExist: # Not found in the database; we proceed to create it. This time # use get_or_create to take care of any race conditions. ct, created = self.get_or_create( app_label=opts.app_label, model=opts.model_name, ) self._add_to_cache(self.db, ct) return ct def get_for_models(self, *models, for_concrete_models=True): """ Given *models, return a dictionary mapping {model: content_type}. """ results = {} # Models that aren't already in the cache. needed_app_labels = set() needed_models = set() # Mapping of opts to the list of models requiring it. needed_opts = defaultdict(list) for model in models: opts = self._get_opts(model, for_concrete_models) try: ct = self._get_from_cache(opts) except KeyError: needed_app_labels.add(opts.app_label) needed_models.add(opts.model_name) needed_opts[opts].append(model) else: results[model] = ct if needed_opts: # Lookup required content types from the DB. cts = self.filter(app_label__in=needed_app_labels, model__in=needed_models) for ct in cts: opts_models = needed_opts.pop(ct.model_class()._meta, []) for model in opts_models: results[model] = ct self._add_to_cache(self.db, ct) # Create content types that weren't in the cache or DB. for opts, opts_models in needed_opts.items(): ct = self.create( app_label=opts.app_label, model=opts.model_name, ) self._add_to_cache(self.db, ct) for model in opts_models: results[model] = ct return results def get_for_id(self, id): """ Lookup a ContentType by ID. Use the same shared cache as get_for_model (though ContentTypes are not created on-the-fly by get_by_id). """ try: ct = self._cache[self.db][id] except KeyError: # This could raise a DoesNotExist; that's correct behavior and will # make sure that only correct ctypes get stored in the cache dict. ct = self.get(pk=id) self._add_to_cache(self.db, ct) return ct def clear_cache(self): """ Clear out the content-type cache. """ self._cache.clear() def _add_to_cache(self, using, ct): """Insert a ContentType into the cache.""" # Note it's possible for ContentType objects to be stale; model_class() # will return None. Hence, there is no reliance on # model._meta.app_label here, just using the model fields instead. key = (ct.app_label, ct.model) self._cache.setdefault(using, {})[key] = ct self._cache.setdefault(using, {})[ct.id] = ct class ContentType(models.Model): app_label = models.CharField(max_length=100) model = models.CharField(_("python model class name"), max_length=100) objects = ContentTypeManager() class Meta: verbose_name = _("content type") verbose_name_plural = _("content types") db_table = "django_content_type" unique_together = [["app_label", "model"]] def __str__(self): return self.app_labeled_name @property def name(self): model = self.model_class() if not model: return self.model return str(model._meta.verbose_name) @property def app_labeled_name(self): model = self.model_class() if not model: return self.model return "%s | %s" % (model._meta.app_label, model._meta.verbose_name) def model_class(self): """Return the model class for this type of content.""" try: return apps.get_model(self.app_label, self.model) except LookupError: return None def get_object_for_this_type(self, **kwargs): """ Return an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type's get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it. """ return self.model_class()._base_manager.using(self._state.db).get(**kwargs) def get_all_objects_for_this_type(self, **kwargs): """ Return all objects of this type for the keyword arguments given. """ return self.model_class()._base_manager.using(self._state.db).filter(**kwargs) def natural_key(self): return (self.app_label, self.model)
6b42ab953f24d9a3c82a7e787cdc020d368055d56bd5f2d8d410f3fc5ac4dedb
from functools import partial from django.contrib.admin.checks import InlineModelAdminChecks from django.contrib.admin.options import InlineModelAdmin, flatten_fieldsets from django.contrib.contenttypes.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_fields class GenericInlineModelAdminChecks(InlineModelAdminChecks): def _check_exclude_of_parent_model(self, obj, parent_model): # There's no FK to exclude, so no exclusion checks are 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 GenericForeignKey. gfks = [ f for f in obj.model._meta.private_fields if isinstance(f, GenericForeignKey) ] if not gfks: return [ checks.Error( "'%s' has no GenericForeignKey." % obj.model._meta.label, obj=obj.__class__, id="admin.E301", ) ] else: # Check that the ct_field and ct_fk_fields exist try: obj.model._meta.get_field(obj.ct_field) except FieldDoesNotExist: return [ checks.Error( "'ct_field' references '%s', which is not a field on '%s'." % ( obj.ct_field, obj.model._meta.label, ), obj=obj.__class__, id="admin.E302", ) ] try: obj.model._meta.get_field(obj.ct_fk_field) except FieldDoesNotExist: return [ checks.Error( "'ct_fk_field' references '%s', which is not a field on '%s'." % ( obj.ct_fk_field, obj.model._meta.label, ), obj=obj.__class__, id="admin.E303", ) ] # There's one or more GenericForeignKeys; make sure that one of them # uses the right ct_field and ct_fk_field. for gfk in gfks: if gfk.ct_field == obj.ct_field and gfk.fk_field == obj.ct_fk_field: return [] return [ checks.Error( "'%s' has no GenericForeignKey using content type field '%s' and " "object ID field '%s'." % ( obj.model._meta.label, obj.ct_field, obj.ct_fk_field, ), obj=obj.__class__, id="admin.E304", ) ] class GenericInlineModelAdmin(InlineModelAdmin): ct_field = "content_type" ct_fk_field = "object_id" formset = BaseGenericInlineFormSet checks_class = GenericInlineModelAdminChecks def get_formset(self, request, obj=None, **kwargs): if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) exclude = [*(self.exclude or []), *self.get_readonly_fields(request, obj)] if ( self.exclude is None and hasattr(self.form, "_meta") and self.form._meta.exclude ): # Take the custom ModelForm's Meta.exclude into account only if the # GenericInlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission(request, obj) defaults = { "ct_field": self.ct_field, "fk_field": self.ct_fk_field, "form": self.form, "formfield_callback": partial(self.formfield_for_dbfield, request=request), "formset": self.formset, "extra": self.get_extra(request, obj), "can_delete": can_delete, "can_order": False, "fields": fields, "min_num": self.get_min_num(request, obj), "max_num": self.get_max_num(request, obj), "exclude": exclude, **kwargs, } if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = ALL_FIELDS return generic_inlineformset_factory(self.model, **defaults) class GenericStackedInline(GenericInlineModelAdmin): template = "admin/edit_inline/stacked.html" class GenericTabularInline(GenericInlineModelAdmin): template = "admin/edit_inline/tabular.html"
d50d665a33ef7d853b11a3b9d09bec5ae0e0ff7b8af03a02c29bdd21d4fb88a6
from django.apps import 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, inject_rename_contenttypes_operations class ContentTypesConfig(AppConfig): default_auto_field = "django.db.models.AutoField" name = "django.contrib.contenttypes" verbose_name = _("Content Types") def ready(self): pre_migrate.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.models)
272f2e727418e02ebb622b218908d295456d275415bdb9af6d1b90c970b7a06f
import functools import itertools from collections import defaultdict from django.contrib.contenttypes.models import ContentType from django.core import checks from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist from django.db import DEFAULT_DB_ALIAS, models, router, transaction from django.db.models import DO_NOTHING, ForeignObject, ForeignObjectRel from django.db.models.base import ModelBase, make_foreign_order_accessors from django.db.models.fields.mixins import FieldCacheMixin from django.db.models.fields.related import ( ReverseManyToOneDescriptor, lazy_related_operation, ) from django.db.models.query_utils import PathInfo from django.db.models.sql import AND from django.db.models.sql.where import WhereNode from django.utils.functional import cached_property class GenericForeignKey(FieldCacheMixin): """ Provide a generic many-to-one relation through the ``content_type`` and ``object_id`` fields. This class also doubles as an accessor to the related object (similar to ForwardManyToOneDescriptor) by adding itself as a model attribute. """ # Field flags auto_created = False concrete = False editable = False hidden = False is_relation = True many_to_many = False many_to_one = True one_to_many = False one_to_one = False related_model = None remote_field = None def __init__( self, ct_field="content_type", fk_field="object_id", for_concrete_model=True ): self.ct_field = ct_field self.fk_field = fk_field self.for_concrete_model = for_concrete_model self.editable = False self.rel = None self.column = None def contribute_to_class(self, cls, name, **kwargs): self.name = name self.model = cls cls._meta.add_field(self, private=True) setattr(cls, name, self) def get_filter_kwargs_for_object(self, obj): """See corresponding method on Field""" return { self.fk_field: getattr(obj, self.fk_field), self.ct_field: getattr(obj, self.ct_field), } def get_forward_related_filter(self, obj): """See corresponding method on RelatedField""" return { self.fk_field: obj.pk, self.ct_field: ContentType.objects.get_for_model(obj).pk, } def __str__(self): model = self.model return "%s.%s" % (model._meta.label, self.name) def check(self, **kwargs): return [ *self._check_field_name(), *self._check_object_id_field(), *self._check_content_type_field(), ] def _check_field_name(self): if self.name.endswith("_"): return [ checks.Error( "Field names must not end with an underscore.", obj=self, id="fields.E001", ) ] else: return [] def _check_object_id_field(self): try: self.model._meta.get_field(self.fk_field) except FieldDoesNotExist: return [ checks.Error( "The GenericForeignKey object ID references the " "nonexistent field '%s'." % self.fk_field, obj=self, id="contenttypes.E001", ) ] else: return [] def _check_content_type_field(self): """ Check if field named `field_name` in model `model` exists and is a valid content_type field (is a ForeignKey to ContentType). """ try: field = self.model._meta.get_field(self.ct_field) except FieldDoesNotExist: return [ checks.Error( "The GenericForeignKey content type references the " "nonexistent field '%s.%s'." % (self.model._meta.object_name, self.ct_field), obj=self, id="contenttypes.E002", ) ] else: if not isinstance(field, models.ForeignKey): return [ checks.Error( "'%s.%s' is not a ForeignKey." % (self.model._meta.object_name, self.ct_field), hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=self, id="contenttypes.E003", ) ] elif field.remote_field.model != ContentType: return [ checks.Error( "'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % (self.model._meta.object_name, self.ct_field), hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." ), obj=self, id="contenttypes.E004", ) ] else: return [] def get_cache_name(self): return self.name def get_content_type(self, obj=None, id=None, using=None): if obj is not None: return ContentType.objects.db_manager(obj._state.db).get_for_model( obj, for_concrete_model=self.for_concrete_model ) elif id is not None: return ContentType.objects.db_manager(using).get_for_id(id) else: # This should never happen. I love comments like this, don't you? raise Exception("Impossible arguments to GFK.get_content_type!") def get_prefetch_queryset(self, instances, queryset=None): if queryset is not None: raise ValueError("Custom queryset can't be used for this lookup.") # For efficiency, group the instances by content type and then do one # query per model fk_dict = defaultdict(set) # We need one instance for each group in order to get the right db: instance_dict = {} ct_attname = self.model._meta.get_field(self.ct_field).get_attname() for instance in instances: # We avoid looking for values if either ct_id or fkey value is None ct_id = getattr(instance, ct_attname) if ct_id is not None: fk_val = getattr(instance, self.fk_field) if fk_val is not None: fk_dict[ct_id].add(fk_val) instance_dict[ct_id] = instance ret_val = [] for ct_id, fkeys in fk_dict.items(): instance = instance_dict[ct_id] ct = self.get_content_type(id=ct_id, using=instance._state.db) ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys)) # For doing the join in Python, we have to match both the FK val and the # content type, so we use a callable that returns a (fk, class) pair. def gfk_key(obj): ct_id = getattr(obj, ct_attname) if ct_id is None: return None else: model = self.get_content_type( id=ct_id, using=obj._state.db ).model_class() return ( model._meta.pk.get_prep_value(getattr(obj, self.fk_field)), model, ) return ( ret_val, lambda obj: (obj.pk, obj.__class__), gfk_key, True, self.name, False, ) def __get__(self, instance, cls=None): if instance is None: return self # Don't use getattr(instance, self.ct_field) here because that might # reload the same ContentType over and over (#5570). Instead, get the # content type ID here, and later when the actual instance is needed, # use ContentType.objects.get_for_id(), which has a global cache. f = self.model._meta.get_field(self.ct_field) ct_id = getattr(instance, f.get_attname(), None) pk_val = getattr(instance, self.fk_field) rel_obj = self.get_cached_value(instance, default=None) if rel_obj is None and self.is_cached(instance): return rel_obj if rel_obj is not None: ct_match = ( ct_id == self.get_content_type(obj=rel_obj, using=instance._state.db).id ) pk_match = rel_obj._meta.pk.to_python(pk_val) == rel_obj.pk if ct_match and pk_match: return rel_obj else: rel_obj = None if ct_id is not None: ct = self.get_content_type(id=ct_id, using=instance._state.db) try: rel_obj = ct.get_object_for_this_type(pk=pk_val) except ObjectDoesNotExist: pass self.set_cached_value(instance, rel_obj) return rel_obj def __set__(self, instance, value): ct = None fk = None if value is not None: ct = self.get_content_type(obj=value) fk = value.pk setattr(instance, self.ct_field, ct) setattr(instance, self.fk_field, fk) self.set_cached_value(instance, value) class GenericRel(ForeignObjectRel): """ Used by GenericRelation to store information about the relation. """ def __init__( self, field, to, related_name=None, related_query_name=None, limit_choices_to=None, ): super().__init__( field, to, related_name=related_query_name or "+", related_query_name=related_query_name, limit_choices_to=limit_choices_to, on_delete=DO_NOTHING, ) class GenericRelation(ForeignObject): """ Provide a reverse to a relation created by a GenericForeignKey. """ # Field flags auto_created = False empty_strings_allowed = False many_to_many = False many_to_one = False one_to_many = True one_to_one = False rel_class = GenericRel mti_inherited = False def __init__( self, to, object_id_field="object_id", content_type_field="content_type", for_concrete_model=True, related_query_name=None, limit_choices_to=None, **kwargs, ): kwargs["rel"] = self.rel_class( self, to, related_query_name=related_query_name, limit_choices_to=limit_choices_to, ) # Reverse relations are always nullable (Django can't enforce that a # foreign key on the related model points to this model). kwargs["null"] = True kwargs["blank"] = True kwargs["on_delete"] = models.CASCADE kwargs["editable"] = False kwargs["serialize"] = False # This construct is somewhat of an abuse of ForeignObject. This field # represents a relation from pk to object_id field. But, this relation # isn't direct, the join is generated reverse along foreign key. So, # the from_field is object_id field, to_field is pk because of the # reverse join. super().__init__(to, from_fields=[object_id_field], to_fields=[], **kwargs) self.object_id_field_name = object_id_field self.content_type_field_name = content_type_field self.for_concrete_model = for_concrete_model def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_generic_foreign_key_existence(), ] def _is_matching_generic_foreign_key(self, field): """ Return True if field is a GenericForeignKey whose content type and object id fields correspond to the equivalent attributes on this GenericRelation. """ return ( isinstance(field, GenericForeignKey) and field.ct_field == self.content_type_field_name and field.fk_field == self.object_id_field_name ) def _check_generic_foreign_key_existence(self): target = self.remote_field.model if isinstance(target, ModelBase): fields = target._meta.private_fields if any(self._is_matching_generic_foreign_key(field) for field in fields): return [] else: return [ checks.Error( "The GenericRelation defines a relation with the model " "'%s', but that model does not have a GenericForeignKey." % target._meta.label, obj=self, id="contenttypes.E004", ) ] else: return [] def resolve_related_fields(self): self.to_fields = [self.model._meta.pk.name] return [ ( self.remote_field.model._meta.get_field(self.object_id_field_name), self.model._meta.pk, ) ] def _get_path_info_with_parent(self, filtered_relation): """ Return the path that joins the current model through any parent models. The idea is that if you have a GFK defined on a parent model then we need to join the parent model first, then the child model. """ # With an inheritance chain ChildTag -> Tag and Tag defines the # GenericForeignKey, and a TaggedItem model has a GenericRelation to # ChildTag, then we need to generate a join from TaggedItem to Tag # (as Tag.object_id == TaggedItem.pk), and another join from Tag to # ChildTag (as that is where the relation is to). Do this by first # generating a join to the parent model, then generating joins to the # child models. path = [] opts = self.remote_field.model._meta.concrete_model._meta parent_opts = opts.get_field(self.object_id_field_name).model._meta target = parent_opts.pk path.append( PathInfo( from_opts=self.model._meta, to_opts=parent_opts, target_fields=(target,), join_field=self.remote_field, m2m=True, direct=False, filtered_relation=filtered_relation, ) ) # Collect joins needed for the parent -> child chain. This is easiest # to do if we collect joins for the child -> parent chain and then # reverse the direction (call to reverse() and use of # field.remote_field.get_path_info()). parent_field_chain = [] while parent_opts != opts: field = opts.get_ancestor_link(parent_opts.model) parent_field_chain.append(field) opts = field.remote_field.model._meta parent_field_chain.reverse() for field in parent_field_chain: path.extend(field.remote_field.path_infos) return path def get_path_info(self, filtered_relation=None): opts = self.remote_field.model._meta object_id_field = opts.get_field(self.object_id_field_name) if object_id_field.model != opts.model: return self._get_path_info_with_parent(filtered_relation) else: target = opts.pk return [ PathInfo( from_opts=self.model._meta, to_opts=opts, target_fields=(target,), join_field=self.remote_field, m2m=True, direct=False, filtered_relation=filtered_relation, ) ] def get_reverse_path_info(self, filtered_relation=None): opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=(opts.pk,), join_field=self, m2m=not self.unique, direct=False, filtered_relation=filtered_relation, ) ] def value_to_string(self, obj): qs = getattr(obj, self.name).all() return str([instance.pk for instance in qs]) def contribute_to_class(self, cls, name, **kwargs): kwargs["private_only"] = True super().contribute_to_class(cls, name, **kwargs) self.model = cls # Disable the reverse relation for fields inherited by subclasses of a # model in multi-table inheritance. The reverse relation points to the # field of the base model. if self.mti_inherited: self.remote_field.related_name = "+" self.remote_field.related_query_name = None setattr(cls, self.name, ReverseGenericManyToOneDescriptor(self.remote_field)) # Add get_RELATED_order() and set_RELATED_order() to the model this # field belongs to, if the model on the other end of this relation # is ordered with respect to its corresponding GenericForeignKey. if not cls._meta.abstract: def make_generic_foreign_order_accessors(related_model, model): if self._is_matching_generic_foreign_key( model._meta.order_with_respect_to ): make_foreign_order_accessors(model, related_model) lazy_related_operation( make_generic_foreign_order_accessors, self.model, self.remote_field.model, ) def set_attributes_from_rel(self): pass def get_internal_type(self): return "ManyToManyField" def get_content_type(self): """ Return the content type associated with this field's model. """ return ContentType.objects.get_for_model( self.model, for_concrete_model=self.for_concrete_model ) def get_extra_restriction(self, alias, remote_alias): field = self.remote_field.model._meta.get_field(self.content_type_field_name) contenttype_pk = self.get_content_type().pk lookup = field.get_lookup("exact")(field.get_col(remote_alias), contenttype_pk) return WhereNode([lookup], connector=AND) def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS): """ Return all objects related to ``objs`` via this ``GenericRelation``. """ return self.remote_field.model._base_manager.db_manager(using).filter( **{ "%s__pk" % self.content_type_field_name: ContentType.objects.db_manager(using) .get_for_model(self.model, for_concrete_model=self.for_concrete_model) .pk, "%s__in" % self.object_id_field_name: [obj.pk for obj in objs], } ) class ReverseGenericManyToOneDescriptor(ReverseManyToOneDescriptor): """ Accessor to the related objects manager on the one-to-many relation created by GenericRelation. In the example:: class Post(Model): comments = GenericRelation(Comment) ``post.comments`` is a ReverseGenericManyToOneDescriptor instance. """ @cached_property def related_manager_cls(self): return create_generic_related_manager( self.rel.model._default_manager.__class__, self.rel, ) @cached_property def related_manager_cache_key(self): # By default, GenericRel instances will be marked as hidden unless # related_query_name is given (their accessor name being "+" when # hidden), which would cause multiple GenericRelations declared on a # single model to collide, so always use the remote field's name. return self.field.get_cache_name() def create_generic_related_manager(superclass, rel): """ Factory function to create a manager that subclasses another manager (generally the default manager of a given model) and adds behaviors specific to generic relations. """ class GenericRelatedObjectManager(superclass): def __init__(self, instance=None): super().__init__() self.instance = instance self.model = rel.model self.get_content_type = functools.partial( ContentType.objects.db_manager(instance._state.db).get_for_model, for_concrete_model=rel.field.for_concrete_model, ) self.content_type = self.get_content_type(instance) self.content_type_field_name = rel.field.content_type_field_name self.object_id_field_name = rel.field.object_id_field_name self.prefetch_cache_name = rel.field.attname self.pk_val = instance.pk self.core_filters = { "%s__pk" % self.content_type_field_name: self.content_type.id, self.object_id_field_name: self.pk_val, } def __call__(self, *, manager): manager = getattr(self.model, manager) manager_class = create_generic_related_manager(manager.__class__, rel) return manager_class(instance=self.instance) do_not_call_in_templates = True def __str__(self): return repr(self) def _apply_rel_filters(self, queryset): """ Filter the queryset for the instance this manager is bound to. """ db = self._db or router.db_for_read(self.model, instance=self.instance) return queryset.using(db).filter(**self.core_filters) def _remove_prefetched_objects(self): try: self.instance._prefetched_objects_cache.pop(self.prefetch_cache_name) except (AttributeError, KeyError): pass # nothing to clear from cache def get_queryset(self): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): queryset = super().get_queryset() return self._apply_rel_filters(queryset) def get_prefetch_queryset(self, instances, queryset=None): if queryset is None: queryset = super().get_queryset() queryset._add_hints(instance=instances[0]) queryset = queryset.using(queryset._db or self._db) # Group instances by content types. content_type_queries = ( models.Q( (f"{self.content_type_field_name}__pk", content_type_id), (f"{self.object_id_field_name}__in", {obj.pk for obj in objs}), ) for content_type_id, objs in itertools.groupby( sorted(instances, key=lambda obj: self.get_content_type(obj).pk), lambda obj: self.get_content_type(obj).pk, ) ) query = models.Q(*content_type_queries, _connector=models.Q.OR) # We (possibly) need to convert object IDs to the type of the # instances' PK in order to match up instances: object_id_converter = instances[0]._meta.pk.to_python content_type_id_field_name = "%s_id" % self.content_type_field_name return ( queryset.filter(query), lambda relobj: ( object_id_converter(getattr(relobj, self.object_id_field_name)), getattr(relobj, content_type_id_field_name), ), lambda obj: (obj.pk, self.get_content_type(obj).pk), False, self.prefetch_cache_name, False, ) def add(self, *objs, bulk=True): self._remove_prefetched_objects() db = router.db_for_write(self.model, instance=self.instance) def check_and_update_obj(obj): if not isinstance(obj, self.model): raise TypeError( "'%s' instance expected, got %r" % (self.model._meta.object_name, obj) ) setattr(obj, self.content_type_field_name, self.content_type) setattr(obj, self.object_id_field_name, self.pk_val) if bulk: pks = [] for obj in objs: if obj._state.adding or obj._state.db != db: raise ValueError( "%r instance isn't saved. Use bulk=False or save " "the object first." % obj ) check_and_update_obj(obj) pks.append(obj.pk) self.model._base_manager.using(db).filter(pk__in=pks).update( **{ self.content_type_field_name: self.content_type, self.object_id_field_name: self.pk_val, } ) else: with transaction.atomic(using=db, savepoint=False): for obj in objs: check_and_update_obj(obj) obj.save() add.alters_data = True def remove(self, *objs, bulk=True): if not objs: return self._clear(self.filter(pk__in=[o.pk for o in objs]), bulk) remove.alters_data = True def clear(self, *, bulk=True): self._clear(self, bulk) clear.alters_data = True def _clear(self, queryset, bulk): self._remove_prefetched_objects() db = router.db_for_write(self.model, instance=self.instance) queryset = queryset.using(db) if bulk: # `QuerySet.delete()` creates its own atomic block which # contains the `pre_delete` and `post_delete` signal handlers. queryset.delete() else: with transaction.atomic(using=db, savepoint=False): for obj in queryset: obj.delete() _clear.alters_data = True def set(self, objs, *, bulk=True, clear=False): # Force evaluation of `objs` in case it's a queryset whose value # could be affected by `manager.clear()`. Refs #19816. objs = tuple(objs) db = router.db_for_write(self.model, instance=self.instance) with transaction.atomic(using=db, savepoint=False): if clear: self.clear() self.add(*objs, bulk=bulk) else: old_objs = set(self.using(db).all()) new_objs = [] for obj in objs: if obj in old_objs: old_objs.remove(obj) else: new_objs.append(obj) self.remove(*old_objs) self.add(*new_objs, bulk=bulk) set.alters_data = True def create(self, **kwargs): self._remove_prefetched_objects() kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super().using(db).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super().using(db).get_or_create(**kwargs) get_or_create.alters_data = True def update_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super().using(db).update_or_create(**kwargs) update_or_create.alters_data = True return GenericRelatedObjectManager
4fa7d96642633eb0fa4778795a8b366bd68333799924b7ab1d287a3571c9a782
from django.contrib.contenttypes.models import ContentType from django.db import models from django.forms 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, save_as_new=False, prefix=None, queryset=None, **kwargs, ): opts = self.model._meta self.instance = instance self.rel_name = ( opts.app_label + "-" + opts.model_name + "-" + self.ct_field.name + "-" + self.ct_fk_field.name ) self.save_as_new = save_as_new if self.instance is None or self.instance.pk is None: qs = self.model._default_manager.none() else: if queryset is None: queryset = self.model._default_manager qs = queryset.filter( **{ self.ct_field.name: ContentType.objects.get_for_model( self.instance, for_concrete_model=self.for_concrete_model ), self.ct_fk_field.name: self.instance.pk, } ) super().__init__(queryset=qs, data=data, files=files, prefix=prefix, **kwargs) def initial_form_count(self): if self.save_as_new: return 0 return super().initial_form_count() @classmethod def get_default_prefix(cls): opts = cls.model._meta return ( opts.app_label + "-" + opts.model_name + "-" + cls.ct_field.name + "-" + cls.ct_fk_field.name ) def save_new(self, form, commit=True): setattr( form.instance, self.ct_field.get_attname(), ContentType.objects.get_for_model(self.instance).pk, ) setattr(form.instance, self.ct_fk_field.get_attname(), self.instance.pk) return form.save(commit=commit) def generic_inlineformset_factory( model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False, absolute_max=None, can_delete_extra=True, ): """ Return a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. """ opts = model._meta # if there is no field called `ct_field` let the exception propagate ct_field = opts.get_field(ct_field) if ( not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType ): raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) fk_field = opts.get_field(fk_field) # let the exception propagate exclude = [*(exclude or []), ct_field.name, fk_field.name] FormSet = modelformset_factory( model, form=form, formfield_callback=formfield_callback, formset=formset, extra=extra, can_delete=can_delete, can_order=can_order, fields=fields, exclude=exclude, max_num=max_num, validate_max=validate_max, min_num=min_num, validate_min=validate_min, absolute_max=absolute_max, can_delete_extra=can_delete_extra, ) FormSet.ct_field = ct_field FormSet.ct_fk_field = fk_field FormSet.for_concrete_model = for_concrete_model return FormSet
1c1a086cda601d340de691fc9ae97bed43043191db6e4107fd07659fe5c581dd
from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ObjectDoesNotExist 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 on a content-type ID and an object ID. """ # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_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 = content_type.get_object_for_this_type(pk=object_id) except (ObjectDoesNotExist, ValueError): raise Http404( _("Content type %(ct_id)s object %(obj_id)s doesn’t exist") % {"ct_id": content_type_id, "obj_id": object_id} ) try: get_absolute_url = obj.get_absolute_url except AttributeError: raise Http404( _("%(ct_name)s objects don’t have a get_absolute_url() method") % {"ct_name": content_type.name} ) absurl = get_absolute_url() # Try to figure out the object's domain, so we can do a cross-site redirect # if necessary. # If the object actually defines a domain, we're done. if absurl.startswith(("http://", "https://", "//")): return HttpResponseRedirect(absurl) # Otherwise, we need to introspect the object's relationships for a # relation to the Site object try: object_domain = get_current_site(request).domain except ObjectDoesNotExist: object_domain = None if apps.is_installed("django.contrib.sites"): Site = apps.get_model("sites.Site") opts = obj._meta for field in opts.many_to_many: # Look for a many-to-many relationship to Site. if field.remote_field.model is Site: site_qs = getattr(obj, field.name).all() if object_domain and site_qs.filter(domain=object_domain).exists(): # The current site's domain matches a site attached to the # object. break # Caveat: In the case of multiple related Sites, this just # selects the *first* one, which is arbitrary. site = site_qs.first() if site: object_domain = site.domain break else: # No many-to-many relationship to Site found. Look for a # many-to-one relationship to Site. for field in obj._meta.fields: if field.remote_field and field.remote_field.model is Site: try: site = getattr(obj, field.name) except Site.DoesNotExist: continue if site is not None: object_domain = site.domain break # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute_url() returned. if object_domain is not None: protocol = request.scheme return HttpResponseRedirect("%s://%s%s" % (protocol, object_domain, absurl)) else: return HttpResponseRedirect(absurl)
d70a121861782055a6d9aa4e69bc6d7501de552e8e9a78af2ff7f08d46062707
""" This module 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 dictionary serialized and encoded as a string. """ session_store_class = self.model.get_session_store_class() return session_store_class().encode(session_dict) def save(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 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(_("expire date"), db_index=True) objects = BaseSessionManager() class Meta: abstract = True verbose_name = _("session") verbose_name_plural = _("sessions") def __str__(self): return self.session_key @classmethod def get_session_store_class(cls): raise NotImplementedError def get_decoded(self): session_store_class = self.get_session_store_class() return session_store_class().decode(self.session_data)
060bb0b90483ce979335786d79844072ca60d6ba29e37d6d8c57995155993587
from django.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 arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID -- not the data itself. 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 vulnerable 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 = SessionManager() @classmethod def get_session_store_class(cls): from django.contrib.sessions.backends.db import SessionStore return SessionStore class Meta(AbstractBaseSession.Meta): db_table = "django_session"
2a19215e21707d47e548ffedeb008b3845f3d588c145329535bacb98684e4cba
from django.core.exceptions import BadRequest, SuspiciousOperation class InvalidSessionKey(SuspiciousOperation): """Invalid characters in session key""" pass class SuspiciousSession(SuspiciousOperation): """The session may be tampered with""" pass class SessionInterrupted(BadRequest): """The session was interrupted.""" pass
e5620ca9adf29aa12f60c9c51dedee59907c5d28a3505fcd4a06a8ad10f9d0b8
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class SessionsConfig(AppConfig): name = "django.contrib.sessions" verbose_name = _("Sessions")
c7c715661b06e5104965a2b8c0ab2e01c1182afeaba29f55f58ee60f24b23b03
# RemovedInDjango50Warning. from django.core.serializers.base import PickleSerializer as BasePickleSerializer from django.core.signing import JSONSerializer as BaseJSONSerializer JSONSerializer = BaseJSONSerializer PickleSerializer = BasePickleSerializer
8215f7d8bf81ea5428929f251fafdfd00bd0ffd621578449de0f5892166ddb73
import time from importlib import import_module from django.conf import settings from django.contrib.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, get_response): super().__init__(get_response) engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore def process_request(self, request): 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 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.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: return response # First check if we need to delete this cookie. # The session should be deleted only if the session is entirely empty. if settings.SESSION_COOKIE_NAME in request.COOKIES and empty: response.delete_cookie( settings.SESSION_COOKIE_NAME, path=settings.SESSION_COOKIE_PATH, domain=settings.SESSION_COOKIE_DOMAIN, samesite=settings.SESSION_COOKIE_SAMESITE, ) patch_vary_headers(response, ("Cookie",)) else: if accessed: patch_vary_headers(response, ("Cookie",)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. # Skip session save for 500 responses, refs #3881. if response.status_code != 500: try: request.session.save() except UpdateError: raise SessionInterrupted( "The request's session was deleted before the " "request completed. The user may have logged " "out in a concurrent request, for example." ) response.set_cookie( settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, samesite=settings.SESSION_COOKIE_SAMESITE, ) return response
69af73163554dfca9a12f45cd2f007fe3d80800111948d35ae98582c76dced38
import zipfile from io import BytesIO from django.conf import settings from django.http import HttpResponse from django.template import loader # NumPy supported? try: import numpy except ImportError: numpy = False def compress_kml(kml): "Return compressed KMZ from the given KML string." kmz = BytesIO() with zipfile.ZipFile(kmz, "a", zipfile.ZIP_DEFLATED) as zf: zf.writestr("doc.kml", kml.encode(settings.DEFAULT_CHARSET)) kmz.seek(0) return kmz.read() def render_to_kml(*args, **kwargs): "Render the response as KML (using the correct MIME type)." return HttpResponse( loader.render_to_string(*args, **kwargs), content_type="application/vnd.google-earth.kml+xml", ) def render_to_kmz(*args, **kwargs): """ Compress the KML content and return as KMZ (using the correct MIME type). """ return HttpResponse( compress_kml(loader.render_to_string(*args, **kwargs)), content_type="application/vnd.google-earth.kmz", )
d083602d68382de463a0eddf526edfebcbd75d699a24605919bb7e189a2f4e57
import re from django.utils.regex_helper import _lazy_re_compile # Regular expression for recognizing HEXEWKB and WKT. A prophylactic measure # to prevent potentially malicious input from reaching the underlying C # library. Not a substitute for good web security programming practices. hex_regex = _lazy_re_compile(r"^[0-9A-F]+$", re.I) wkt_regex = _lazy_re_compile( r"^(SRID=(?P<srid>\-?[0-9]+);)?" r"(?P<wkt>" r"(?P<type>POINT|LINESTRING|LINEARRING|POLYGON|MULTIPOINT|" r"MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION)" r"[ACEGIMLONPSRUTYZ0-9,\.\-\+\(\) ]+)$", re.I, ) json_regex = _lazy_re_compile(r"^(\s+)?\{.*}(\s+)?$", re.DOTALL)
75b0052b1f638fdfd076174d7cbe4a082e3ba6e1ff653c34f7c8ec245c033bd6
from django.apps import AppConfig from django.core import serializers from django.utils.translation import gettext_lazy as _ class GISConfig(AppConfig): default_auto_field = "django.db.models.AutoField" name = "django.contrib.gis" verbose_name = _("GIS") def ready(self): serializers.BUILTIN_SERIALIZERS.setdefault( "geojson", "django.contrib.gis.serializers.geojson" )
35e20107ea65c0eeb5c0638ec4683b7c5c955c8e1ae6f6c019475a27f1668eaa
from ctypes import c_void_p class CPointerBase: """ Base class for objects that have a pointer access property that controls access to the underlying C pointer. """ _ptr = None # Initially the pointer is NULL. ptr_type = c_void_p destructor = None null_ptr_exception_class = AttributeError @property def ptr(self): # Raise an exception if the pointer isn't valid so that NULL pointers # aren't passed to routines -- that's very bad. if self._ptr: return self._ptr raise self.null_ptr_exception_class( "NULL %s pointer encountered." % self.__class__.__name__ ) @ptr.setter def ptr(self, ptr): # Only allow the pointer to be set with pointers of the compatible # type or None (NULL). if not (ptr is None or isinstance(ptr, self.ptr_type)): raise TypeError("Incompatible pointer type: %s." % type(ptr)) self._ptr = ptr def __del__(self): """ Free the memory used by the C++ object. """ if self.destructor and self._ptr: try: self.destructor(self.ptr) except (AttributeError, ImportError, TypeError): pass # Some part might already have been garbage collected
d2f355552708c30d776cec6f9507d700e088b483865925eba0a2a5e905c6079f
from django.contrib.syndication.views import Feed as BaseFeed from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed class GeoFeedMixin: """ This mixin provides the necessary routines for SyndicationFeed subclasses to produce simple GeoRSS or W3C Geo elements. """ def georss_coords(self, coords): """ In GeoRSS coordinate pairs are ordered by lat/lon and separated by a single white space. Given a tuple of coordinates, return a string GeoRSS representation. """ return " ".join("%f %f" % (coord[1], coord[0]) for coord in coords) def add_georss_point(self, handler, coords, w3c_geo=False): """ Adds a GeoRSS point with the given coords using the given handler. Handles the differences between simple GeoRSS and the more popular W3C Geo specification. """ if w3c_geo: lon, lat = coords[:2] handler.addQuickElement("geo:lat", "%f" % lat) handler.addQuickElement("geo:lon", "%f" % lon) else: handler.addQuickElement("georss:point", self.georss_coords((coords,))) def add_georss_element(self, handler, item, w3c_geo=False): """Add a GeoRSS XML element using the given item and handler.""" # Getting the Geometry object. geom = item.get("geometry") if geom is not None: if isinstance(geom, (list, tuple)): # Special case if a tuple/list was passed in. The tuple may be # a point or a box box_coords = None if isinstance(geom[0], (list, tuple)): # Box: ( (X0, Y0), (X1, Y1) ) if len(geom) == 2: box_coords = geom else: raise ValueError("Only should be two sets of coordinates.") else: if len(geom) == 2: # Point: (X, Y) self.add_georss_point(handler, geom, w3c_geo=w3c_geo) elif len(geom) == 4: # Box: (X0, Y0, X1, Y1) box_coords = (geom[:2], geom[2:]) else: raise ValueError("Only should be 2 or 4 numeric elements.") # If a GeoRSS box was given via tuple. if box_coords is not None: if w3c_geo: raise ValueError( "Cannot use simple GeoRSS box in W3C Geo feeds." ) handler.addQuickElement( "georss:box", self.georss_coords(box_coords) ) else: # Getting the lowercase geometry type. gtype = str(geom.geom_type).lower() if gtype == "point": self.add_georss_point(handler, geom.coords, w3c_geo=w3c_geo) else: if w3c_geo: raise ValueError("W3C Geo only supports Point geometries.") # For formatting consistent w/the GeoRSS simple standard: # http://georss.org/1.0#simple if gtype in ("linestring", "linearring"): handler.addQuickElement( "georss:line", self.georss_coords(geom.coords) ) elif gtype in ("polygon",): # Only support the exterior ring. handler.addQuickElement( "georss:polygon", self.georss_coords(geom[0].coords) ) else: raise ValueError( 'Geometry type "%s" not supported.' % geom.geom_type ) # ### SyndicationFeed subclasses ### class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): attrs = super().rss_attributes() attrs["xmlns:georss"] = "http://www.georss.org/georss" return attrs def add_item_elements(self, handler, item): super().add_item_elements(handler, item) self.add_georss_element(handler, item) def add_root_elements(self, handler): super().add_root_elements(handler) self.add_georss_element(handler, self.feed) class GeoAtom1Feed(Atom1Feed, GeoFeedMixin): def root_attributes(self): attrs = super().root_attributes() attrs["xmlns:georss"] = "http://www.georss.org/georss" return attrs def add_item_elements(self, handler, item): super().add_item_elements(handler, item) self.add_georss_element(handler, item) def add_root_elements(self, handler): super().add_root_elements(handler) self.add_georss_element(handler, self.feed) class W3CGeoFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): attrs = super().rss_attributes() attrs["xmlns:geo"] = "http://www.w3.org/2003/01/geo/wgs84_pos#" return attrs def add_item_elements(self, handler, item): super().add_item_elements(handler, item) self.add_georss_element(handler, item, w3c_geo=True) def add_root_elements(self, handler): super().add_root_elements(handler) self.add_georss_element(handler, self.feed, w3c_geo=True) # ### Feed subclass ### class Feed(BaseFeed): """ This is a subclass of the `Feed` from `django.contrib.syndication`. This allows users to define a `geometry(obj)` and/or `item_geometry(item)` methods on their own subclasses so that geo-referenced information may placed in the feed. """ feed_type = GeoRSSFeed def feed_extra_kwargs(self, obj): return {"geometry": self._get_dynamic_attr("geometry", obj)} def item_extra_kwargs(self, item): return {"geometry": self._get_dynamic_attr("item_geometry", item)}
cdd095f107d455fc44146c444ac52d0a272c6d256d64d23f217c9b766b072a23
from django.http import Http404 from django.utils.translation import gettext as _ def feed(request, url, feed_dict=None): """Provided for backwards compatibility.""" if not feed_dict: raise Http404(_("No feeds are registered.")) slug = url.partition("/")[0] try: f = feed_dict[slug] except KeyError: raise Http404(_("Slug %r isn’t registered.") % slug) instance = f() instance.feed_url = getattr(f, "feed_url", None) or request.path instance.title_template = f.title_template or ("feeds/%s_title.html" % slug) instance.description_template = f.description_template or ( "feeds/%s_description.html" % slug ) return instance(request)
2a278b2de405b15db78273f38f55a826f379ba73882b9bfc4138605f4464e128
# Copyright (c) 2007, Robert Coup <[email protected]> # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of Distance nor the names of its contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """ Distance and Area objects to allow for sensible and convenient calculation and conversions. Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio Inspired by GeoPy (https://github.com/geopy/geopy) and Geoff Biggs' PhD work on dimensioned units for robotics. """ from decimal import Decimal from functools import total_ordering __all__ = ["A", "Area", "D", "Distance"] NUMERIC_TYPES = (int, float, Decimal) AREA_PREFIX = "sq_" def pretty_name(obj): return obj.__name__ if obj.__class__ == type else obj.__class__.__name__ @total_ordering class MeasureBase: STANDARD_UNIT = None ALIAS = {} UNITS = {} LALIAS = {} def __init__(self, default_unit=None, **kwargs): value, self._default_unit = self.default_units(kwargs) setattr(self, self.STANDARD_UNIT, value) if default_unit and isinstance(default_unit, str): self._default_unit = default_unit def _get_standard(self): return getattr(self, self.STANDARD_UNIT) def _set_standard(self, value): setattr(self, self.STANDARD_UNIT, value) standard = property(_get_standard, _set_standard) def __getattr__(self, name): if name in self.UNITS: return self.standard / self.UNITS[name] else: raise AttributeError("Unknown unit type: %s" % name) def __repr__(self): return "%s(%s=%s)" % ( pretty_name(self), self._default_unit, getattr(self, self._default_unit), ) def __str__(self): return "%s %s" % (getattr(self, self._default_unit), self._default_unit) # **** Comparison methods **** def __eq__(self, other): if isinstance(other, self.__class__): return self.standard == other.standard else: return NotImplemented def __hash__(self): return hash(self.standard) def __lt__(self, other): if isinstance(other, self.__class__): return self.standard < other.standard else: return NotImplemented # **** Operators methods **** def __add__(self, other): if isinstance(other, self.__class__): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard + other.standard)}, ) else: raise TypeError( "%(class)s must be added with %(class)s" % {"class": pretty_name(self)} ) def __iadd__(self, other): if isinstance(other, self.__class__): self.standard += other.standard return self else: raise TypeError( "%(class)s must be added with %(class)s" % {"class": pretty_name(self)} ) def __sub__(self, other): if isinstance(other, self.__class__): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard - other.standard)}, ) else: raise TypeError( "%(class)s must be subtracted from %(class)s" % {"class": pretty_name(self)} ) def __isub__(self, other): if isinstance(other, self.__class__): self.standard -= other.standard return self else: raise TypeError( "%(class)s must be subtracted from %(class)s" % {"class": pretty_name(self)} ) def __mul__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)}, ) else: raise TypeError( "%(class)s must be multiplied with number" % {"class": pretty_name(self)} ) def __imul__(self, other): if isinstance(other, NUMERIC_TYPES): self.standard *= float(other) return self else: raise TypeError( "%(class)s must be multiplied with number" % {"class": pretty_name(self)} ) def __rmul__(self, other): return self * other def __truediv__(self, other): if isinstance(other, self.__class__): return self.standard / other.standard if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)}, ) else: raise TypeError( "%(class)s must be divided with number or %(class)s" % {"class": pretty_name(self)} ) def __itruediv__(self, other): if isinstance(other, NUMERIC_TYPES): self.standard /= float(other) return self else: raise TypeError( "%(class)s must be divided with number" % {"class": pretty_name(self)} ) def __bool__(self): return bool(self.standard) def default_units(self, kwargs): """ Return the unit value and the default units specified from the given keyword arguments dictionary. """ val = 0.0 default_unit = self.STANDARD_UNIT for unit, value in kwargs.items(): if not isinstance(value, float): value = float(value) if unit in self.UNITS: val += self.UNITS[unit] * value default_unit = unit elif unit in self.ALIAS: u = self.ALIAS[unit] val += self.UNITS[u] * value default_unit = u else: lower = unit.lower() if lower in self.UNITS: val += self.UNITS[lower] * value default_unit = lower elif lower in self.LALIAS: u = self.LALIAS[lower] val += self.UNITS[u] * value default_unit = u else: raise AttributeError("Unknown unit type: %s" % unit) return val, default_unit @classmethod def unit_attname(cls, unit_str): """ Retrieve the unit attribute name for the given unit string. For example, if the given unit string is 'metre', return 'm'. Raise an exception if an attribute cannot be found. """ lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return lower elif lower in cls.LALIAS: return cls.LALIAS[lower] else: raise Exception( 'Could not find a unit keyword associated with "%s"' % unit_str ) class Distance(MeasureBase): STANDARD_UNIT = "m" UNITS = { "chain": 20.1168, "chain_benoit": 20.116782, "chain_sears": 20.1167645, "british_chain_benoit": 20.1167824944, "british_chain_sears": 20.1167651216, "british_chain_sears_truncated": 20.116756, "cm": 0.01, "british_ft": 0.304799471539, "british_yd": 0.914398414616, "clarke_ft": 0.3047972654, "clarke_link": 0.201166195164, "fathom": 1.8288, "ft": 0.3048, "furlong": 201.168, "german_m": 1.0000135965, "gold_coast_ft": 0.304799710181508, "indian_yd": 0.914398530744, "inch": 0.0254, "km": 1000.0, "link": 0.201168, "link_benoit": 0.20116782, "link_sears": 0.20116765, "m": 1.0, "mi": 1609.344, "mm": 0.001, "nm": 1852.0, "nm_uk": 1853.184, "rod": 5.0292, "sears_yd": 0.91439841, "survey_ft": 0.304800609601, "um": 0.000001, "yd": 0.9144, } # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT. ALIAS = { "centimeter": "cm", "foot": "ft", "inches": "inch", "kilometer": "km", "kilometre": "km", "meter": "m", "metre": "m", "micrometer": "um", "micrometre": "um", "millimeter": "mm", "millimetre": "mm", "mile": "mi", "yard": "yd", "British chain (Benoit 1895 B)": "british_chain_benoit", "British chain (Sears 1922)": "british_chain_sears", "British chain (Sears 1922 truncated)": "british_chain_sears_truncated", "British foot (Sears 1922)": "british_ft", "British foot": "british_ft", "British yard (Sears 1922)": "british_yd", "British yard": "british_yd", "Clarke's Foot": "clarke_ft", "Clarke's link": "clarke_link", "Chain (Benoit)": "chain_benoit", "Chain (Sears)": "chain_sears", "Foot (International)": "ft", "Furrow Long": "furlong", "German legal metre": "german_m", "Gold Coast foot": "gold_coast_ft", "Indian yard": "indian_yd", "Link (Benoit)": "link_benoit", "Link (Sears)": "link_sears", "Nautical Mile": "nm", "Nautical Mile (UK)": "nm_uk", "US survey foot": "survey_ft", "U.S. Foot": "survey_ft", "Yard (Indian)": "indian_yd", "Yard (Sears)": "sears_yd", } LALIAS = {k.lower(): v for k, v in ALIAS.items()} def __mul__(self, other): if isinstance(other, self.__class__): return Area( default_unit=AREA_PREFIX + self._default_unit, **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)}, ) elif isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)}, ) else: raise TypeError( "%(distance)s must be multiplied with number or %(distance)s" % { "distance": pretty_name(self.__class__), } ) class Area(MeasureBase): STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT # Getting the square units values and the alias dictionary. UNITS = {"%s%s" % (AREA_PREFIX, k): v**2 for k, v in Distance.UNITS.items()} ALIAS = {k: "%s%s" % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()} LALIAS = {k.lower(): v for k, v in ALIAS.items()} def __truediv__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)}, ) else: raise TypeError( "%(class)s must be divided by a number" % {"class": pretty_name(self)} ) # Shortcuts D = Distance A = Area
714e9b0068430110fb64cd91f5c519b9f10f881f59accecd73711b8214092396
from django.contrib.sitemaps import ping_google from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Ping Google with an updated sitemap, pass optional url of sitemap" def add_arguments(self, parser): parser.add_argument("sitemap_url", nargs="?") parser.add_argument("--sitemap-uses-http", action="store_true") def handle(self, *args, **options): ping_google( sitemap_url=options["sitemap_url"], sitemap_uses_https=not options["sitemap_uses_http"], )
c3119dc546e49694ba2771d75bfa3e542f5c4f2c5ba6dc88c5396bc5939b9083
import binascii import json from django.conf import settings from django.contrib.messages.storage.base import BaseStorage, Message from django.core import signing from django.http import SimpleCookie from 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 False/True to produce more compact json is_safedata = 1 if isinstance(obj.message, SafeData) else 0 message = [self.message_key, is_safedata, obj.level, obj.message] 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 includes 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]) return Message(*obj[2:]) return [self.process_messages(item) for item in obj] if isinstance(obj, dict): return {key: self.process_messages(value) for key, value in obj.items()} return obj def decode(self, s, **kwargs): decoded = super().decode(s, **kwargs) return self.process_messages(decoded) class MessageSerializer: def dumps(self, obj): return json.dumps( obj, separators=(",", ":"), cls=MessageEncoder, ).encode("latin-1") def loads(self, data): return json.loads(data.decode("latin-1"), cls=MessageDecoder) class CookieStorage(BaseStorage): """ Store messages in a cookie. """ cookie_name = "messages" # uwsgi's default configuration enforces a maximum size of 4kb for all the # HTTP headers. In order to leave some room for other cookies and headers, # restrict the session cookie to 1/2 of 4kb. See #18781. max_cookie_size = 2048 not_finished = "__messagesnotfinished__" key_salt = "django.contrib.messages" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.signer = signing.get_cookie_signer(salt=self.key_salt) def _get(self, *args, **kwargs): """ Retrieve a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage. """ data = self.request.COOKIES.get(self.cookie_name) messages = self._decode(data) all_retrieved = not (messages and messages[-1] == self.not_finished) if messages and not all_retrieved: # remove the sentinel value messages.pop() return messages, all_retrieved def _update_cookie(self, encoded_data, response): """ Either set the cookie with the encoded data if there is any data to store, or delete the cookie. """ if encoded_data: response.set_cookie( self.cookie_name, encoded_data, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, samesite=settings.SESSION_COOKIE_SAMESITE, ) else: response.delete_cookie( self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN, samesite=settings.SESSION_COOKIE_SAMESITE, ) def _store(self, messages, response, remove_oldest=True, *args, **kwargs): """ Store the messages to a cookie and return a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, remove messages until the data fits (these are the messages which are returned), and add the not_finished sentinel value to indicate as much. """ unstored_messages = [] encoded_data = self._encode(messages) if self.max_cookie_size: # data is going to be stored eventually by SimpleCookie, which # adds its own overhead, which we must account for. cookie = SimpleCookie() # create outside the loop def stored_length(val): return len(cookie.value_encode(val)[1]) while encoded_data and stored_length(encoded_data) > self.max_cookie_size: if remove_oldest: unstored_messages.append(messages.pop(0)) else: unstored_messages.insert(0, messages.pop()) encoded_data = self._encode( messages + [self.not_finished], encode_empty=unstored_messages ) self._update_cookie(encoded_data, response) return unstored_messages def _encode(self, messages, encode_empty=False): """ Return an encoded version of the messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with. """ if messages or encode_empty: return self.signer.sign_object( messages, serializer=MessageSerializer, compress=True ) def _decode(self, data): """ Safely decode an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, return None. """ if not data: return None try: return self.signer.unsign_object(data, serializer=MessageSerializer) except (signing.BadSignature, binascii.Error, json.JSONDecodeError): pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
92f755a2c6c102f2375c10341b800529fd2fc4b95ecb39706c612097ad037cc4
import json from django.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). """ session_key = "_messages" def __init__(self, request, *args, **kwargs): if not hasattr(request, "session"): raise ImproperlyConfigured( "The session-based temporary message storage requires session " "middleware to be installed, and come before the message " "middleware in the MIDDLEWARE list." ) super().__init__(request, *args, **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. """ return ( self.deserialize_messages(self.request.session.get(self.session_key)), True, ) def _store(self, messages, response, *args, **kwargs): """ Store a list of messages to the request's session. """ if messages: self.request.session[self.session_key] = self.serialize_messages(messages) else: self.request.session.pop(self.session_key, None) return [] def serialize_messages(self, messages): encoder = MessageEncoder() return encoder.encode(messages) def deserialize_messages(self, data): if data and isinstance(data, str): return json.loads(data, cls=MessageDecoder) return data
2b90ab5497d40da90c8c872a491b7559977fd57728d417360103373b795df5a0
from django.contrib.messages.storage.base import BaseStorage 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_classes = (CookieStorage, SessionStorage) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.storages = [ storage_class(*args, **kwargs) 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. """ all_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 messages: self._used_storages.add(storage) all_messages.extend(messages) # If this storage class contained all the messages, no further # retrieval is necessary if all_retrieved: break return all_messages, all_retrieved def _store(self, messages, response, *args, **kwargs): """ Store the messages and return any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend. """ for storage in self.storages: if messages: messages = storage._store(messages, response, remove_oldest=False) # Even if there are no more messages, continue iterating to ensure # storages which contained messages are flushed. elif storage in self._used_storages: storage._store([], response) self._used_storages.remove(storage) return messages
b15912213651b1d603bf2692e6daa3730f3e7f296f71b66947872d969588e5b3
from django.conf import settings from django.contrib.messages import constants, utils LEVEL_TAGS = utils.get_level_tags() class Message: """ 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 self.extra_tags = extra_tags def _prepare(self): """ Prepare the message for serialization by forcing the ``message`` and ``extra_tags`` to str in case they are 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, Message): return NotImplemented return self.level == other.level and self.message == other.message def __str__(self): return str(self.message) @property def tags(self): return " ".join(tag for tag in [self.extra_tags, self.level_tag] if tag) @property def level_tag(self): return LEVEL_TAGS.get(self.level, "") class BaseStorage: """ This is the base backend for temporary message storage. This is not a complete class; to be a usable storage backend, it must be subclassed and the two methods ``_get`` and ``_store`` overridden. """ def __init__(self, request, *args, **kwargs): self.request = request self._queued_messages = [] self.used = False self.added_new = False super().__init__(*args, **kwargs) def __len__(self): return len(self._loaded_messages) + len(self._queued_messages) def __iter__(self): self.used = True if self._queued_messages: self._loaded_messages.extend(self._queued_messages) self._queued_messages = [] return iter(self._loaded_messages) def __contains__(self, item): return item in self._loaded_messages or item in self._queued_messages def __repr__(self): return f"<{self.__class__.__qualname__}: request={self.request!r}>" @property def _loaded_messages(self): """ Return a list of loaded messages, retrieving them first if they have not been loaded yet. """ if not hasattr(self, "_loaded_data"): messages, all_retrieved = self._get() self._loaded_data = messages or [] return self._loaded_data def _get(self, *args, **kwargs): """ Retrieve a list of stored messages. Return a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)``. **This method must be implemented by a subclass.** If it is possible to tell if the backend was not used (as opposed to just containing no messages) then ``None`` should be returned in place of ``messages``. """ raise NotImplementedError( "subclasses of BaseStorage must provide a _get() method" ) def _store(self, messages, response, *args, **kwargs): """ Store a list of messages and return a list of any messages which could not be stored. One type of object must be able to be stored, ``Message``. **This method must be implemented by a subclass.** """ raise NotImplementedError( "subclasses of BaseStorage must provide a _store() method" ) def _prepare_messages(self, messages): """ Prepare a list of messages for storage. """ for message in messages: message._prepare() def update(self, response): """ Store all unread messages. If the backend has yet to be iterated, store previously stored messages again. Otherwise, only store messages added after the last iteration. """ self._prepare_messages(self._queued_messages) if self.used: return self._store(self._queued_messages, response) elif self.added_new: messages = self._loaded_messages + self._queued_messages return self._store(messages, response) def add(self, level, message, extra_tags=""): """ Queue a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``). """ if not message: return # Check that the message level is not less than the recording level. level = int(level) if level < self.level: return # Add the message. self.added_new = True message = Message(level, message, extra_tags=extra_tags) self._queued_messages.append(message) def _get_level(self): """ Return the minimum recorded level. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used. """ if not hasattr(self, "_level"): self._level = getattr(settings, "MESSAGE_LEVEL", constants.INFO) return self._level def _set_level(self, value=None): """ Set a custom minimum recorded level. If set to ``None``, the default level will be used (see the ``_get_level`` method). """ if value is None and hasattr(self, "_level"): del self._level else: self._level = int(value) level = property(_get_level, _set_level, _set_level)
fdcd106252896b9092dbf5c56efd4a0741f01b7c091de43c3f1195c51aca42b9
from django.db.models import CharField, EmailField, TextField __all__ = ["CICharField", "CIEmailField", "CIText", "CITextField"] class CIText: def get_internal_type(self): return "CI" + super().get_internal_type() def db_type(self, connection): return "citext" class CICharField(CIText, CharField): pass class CIEmailField(CIText, EmailField): pass class CITextField(CIText, TextField): pass
33aa11e2ea5de0e808694aa07bb4c9b596cbe5ea06c5795550150a94e2696630
import json from django.contrib.postgres import lookups from django.contrib.postgres.forms import SimpleArrayField from django.contrib.postgres.validators import ArrayMaxLengthValidator from django.core import checks, exceptions from django.db.models import Field, Func, IntegerField, Transform, Value 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 prefix_validation_error from .utils import AttributeSetter __all__ = ["ArrayField"] class ArrayField(CheckFieldDefaultMixin, Field): empty_strings_allowed = False default_error_messages = { "item_invalid": _("Item %(nth)s in the array did not validate:"), "nested_array_mismatch": _("Nested arrays must have the same length."), } _default_hint = ("list", "[]") def __init__(self, base_field, size=None, **kwargs): self.base_field = base_field self.size = size if self.size: self.default_validators = [ *self.default_validators, ArrayMaxLengthValidator(self.size), ] # For performance, only add a from_db_value() method if the base field # implements it. if hasattr(self.base_field, "from_db_value"): self.from_db_value = self._from_db_value super().__init__(**kwargs) @property def model(self): try: return self.__dict__["model"] except KeyError: raise AttributeError( "'%s' object has no attribute 'model'" % self.__class__.__name__ ) @model.setter def model(self, model): self.__dict__["model"] = model self.base_field.model = model @classmethod def _choices_is_value(cls, value): return isinstance(value, (list, tuple)) or super()._choices_is_value(value) def check(self, **kwargs): errors = super().check(**kwargs) if self.base_field.remote_field: errors.append( checks.Error( "Base field for array cannot be a related field.", obj=self, id="postgres.E002", ) ) else: # Remove the field name checks as they are not needed here. base_errors = self.base_field.check() if base_errors: messages = "\n ".join( "%s (%s)" % (error.msg, error.id) for error in base_errors ) errors.append( checks.Error( "Base field for array has errors:\n %s" % messages, obj=self, id="postgres.E001", ) ) return errors def set_attributes_from_name(self, name): super().set_attributes_from_name(name) self.base_field.set_attributes_from_name(name) @property def description(self): return "Array of %s" % self.base_field.description def db_type(self, connection): size = self.size or "" return "%s[%s]" % (self.base_field.db_type(connection), size) def cast_db_type(self, connection): size = self.size or "" return "%s[%s]" % (self.base_field.cast_db_type(connection), size) def get_placeholder(self, value, compiler, connection): return "%s::{}".format(self.db_type(connection)) def get_db_prep_value(self, value, connection, prepared=False): if isinstance(value, (list, tuple)): return [ self.base_field.get_db_prep_value(i, connection, prepared=False) for i in value ] return value def deconstruct(self): name, path, args, kwargs = super().deconstruct() if path == "django.contrib.postgres.fields.array.ArrayField": path = "django.contrib.postgres.fields.ArrayField" kwargs.update( { "base_field": self.base_field.clone(), "size": self.size, } ) return name, path, args, kwargs def to_python(self, value): if isinstance(value, str): # Assume we're deserializing vals = json.loads(value) value = [self.base_field.to_python(val) for val in vals] return value def _from_db_value(self, value, expression, connection): if value is None: return value return [ self.base_field.from_db_value(item, expression, connection) for item in value ] def value_to_string(self, obj): values = [] vals = self.value_from_object(obj) base_field = self.base_field for val in vals: if val is None: values.append(None) else: obj = AttributeSetter(base_field.attname, val) values.append(base_field.value_to_string(obj)) return json.dumps(values) def get_transform(self, name): transform = super().get_transform(name) if transform: return transform if "_" not in name: try: index = int(name) except ValueError: pass else: index += 1 # postgres uses 1-indexing return IndexTransformFactory(index, self.base_field) try: start, end = name.split("_") start = int(start) + 1 end = int(end) # don't add one here because postgres slices are weird except ValueError: pass else: return SliceTransformFactory(start, end) def validate(self, value, model_instance): super().validate(value, model_instance) for index, part in enumerate(value): try: self.base_field.validate(part, model_instance) except exceptions.ValidationError as error: raise prefix_validation_error( error, prefix=self.error_messages["item_invalid"], code="item_invalid", params={"nth": index + 1}, ) if isinstance(self.base_field, ArrayField): if len({len(i) for i in value}) > 1: raise exceptions.ValidationError( self.error_messages["nested_array_mismatch"], code="nested_array_mismatch", ) def run_validators(self, value): super().run_validators(value) for index, part in enumerate(value): try: self.base_field.run_validators(part) except exceptions.ValidationError as error: raise prefix_validation_error( error, prefix=self.error_messages["item_invalid"], code="item_invalid", params={"nth": index + 1}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": SimpleArrayField, "base_field": self.base_field.formfield(), "max_length": self.size, **kwargs, } ) class ArrayRHSMixin: def __init__(self, lhs, rhs): if isinstance(rhs, (tuple, list)): expressions = [] for value in rhs: if not hasattr(value, "resolve_expression"): field = lhs.output_field value = Value(field.base_field.get_prep_value(value)) expressions.append(value) rhs = Func( *expressions, function="ARRAY", template="%(function)s[%(expressions)s]", ) super().__init__(lhs, rhs) def process_rhs(self, compiler, connection): rhs, rhs_params = super().process_rhs(compiler, connection) cast_type = self.lhs.output_field.cast_db_type(connection) return "%s::%s" % (rhs, cast_type), rhs_params @ArrayField.register_lookup class ArrayContains(ArrayRHSMixin, lookups.DataContains): pass @ArrayField.register_lookup class ArrayContainedBy(ArrayRHSMixin, lookups.ContainedBy): pass @ArrayField.register_lookup class ArrayExact(ArrayRHSMixin, Exact): pass @ArrayField.register_lookup class ArrayOverlap(ArrayRHSMixin, lookups.Overlap): pass @ArrayField.register_lookup class ArrayLenTransform(Transform): lookup_name = "len" output_field = IntegerField() def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) # Distinguish NULL and empty arrays return ( "CASE WHEN %(lhs)s IS NULL THEN NULL ELSE " "coalesce(array_length(%(lhs)s, 1), 0) END" ) % {"lhs": lhs}, params @ArrayField.register_lookup class ArrayInLookup(In): def get_prep_lookup(self): values = super().get_prep_lookup() if hasattr(values, "resolve_expression"): return values # In.process_rhs() expects values to be hashable, so convert lists # to tuples. prepared_values = [] for value in values: if hasattr(value, "resolve_expression"): prepared_values.append(value) else: prepared_values.append(tuple(value)) return prepared_values class IndexTransform(Transform): def __init__(self, index, base_field, *args, **kwargs): super().__init__(*args, **kwargs) self.index = index self.base_field = base_field def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return "%s[%%s]" % lhs, params + [self.index] @property def output_field(self): return self.base_field class IndexTransformFactory: def __init__(self, index, base_field): self.index = index self.base_field = base_field def __call__(self, *args, **kwargs): return IndexTransform(self.index, self.base_field, *args, **kwargs) class SliceTransform(Transform): def __init__(self, start, end, *args, **kwargs): super().__init__(*args, **kwargs) self.start = start self.end = end def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return "%s[%%s:%%s]" % lhs, params + [self.start, self.end] class SliceTransformFactory: def __init__(self, start, end): self.start = start self.end = end def __call__(self, *args, **kwargs): return SliceTransform(self.start, self.end, *args, **kwargs)
e64b49d5daec73099ea787e77d11a7408fbcd42af8174364a2e6e148864e1b86
import datetime import json from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange, Range from django.contrib.postgres import forms, lookups from django.db import models from django.db.models.lookups import PostgresOperatorLookup from .utils import AttributeSetter __all__ = [ "RangeField", "IntegerRangeField", "BigIntegerRangeField", "DecimalRangeField", "DateTimeRangeField", "DateRangeField", "RangeBoundary", "RangeOperators", ] class RangeBoundary(models.Expression): """A class that represents range boundaries.""" def __init__(self, inclusive_lower=True, inclusive_upper=False): self.lower = "[" if inclusive_lower else "(" self.upper = "]" if inclusive_upper else ")" def 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_EQUAL = "<>" CONTAINS = "@>" CONTAINED_BY = "<@" OVERLAPS = "&&" FULLY_LT = "<<" FULLY_GT = ">>" NOT_LT = "&>" NOT_GT = "&<" ADJACENT_TO = "-|-" class RangeField(models.Field): empty_strings_allowed = False def __init__(self, *args, **kwargs): if "default_bounds" in kwargs: raise TypeError( f"Cannot use 'default_bounds' with {self.__class__.__name__}." ) # Initializing base_field here ensures that its model matches the model # for self. if hasattr(self, "base_field"): self.base_field = self.base_field() super().__init__(*args, **kwargs) @property def model(self): try: return self.__dict__["model"] except KeyError: raise AttributeError( "'%s' object has no attribute 'model'" % self.__class__.__name__ ) @model.setter def model(self, model): self.__dict__["model"] = model self.base_field.model = model @classmethod def _choices_is_value(cls, value): return isinstance(value, (list, tuple)) or super()._choices_is_value(value) def get_prep_value(self, value): if value is None: return None elif isinstance(value, Range): return value elif isinstance(value, (list, tuple)): return self.range_type(value[0], value[1]) return value def to_python(self, value): if isinstance(value, str): # Assume we're deserializing vals = json.loads(value) for end in ("lower", "upper"): if end in vals: vals[end] = self.base_field.to_python(vals[end]) value = self.range_type(**vals) elif isinstance(value, (list, tuple)): value = self.range_type(value[0], value[1]) return value def set_attributes_from_name(self, name): super().set_attributes_from_name(name) self.base_field.set_attributes_from_name(name) def value_to_string(self, obj): value = self.value_from_object(obj) if value is None: return None if value.isempty: return json.dumps({"empty": True}) base_field = self.base_field result = {"bounds": value._bounds} for end in ("lower", "upper"): val = getattr(value, end) if val is None: result[end] = None else: obj = AttributeSetter(base_field.attname, val) result[end] = base_field.value_to_string(obj) return json.dumps(result) def formfield(self, **kwargs): kwargs.setdefault("form_class", self.form_field) return super().formfield(**kwargs) CANONICAL_RANGE_BOUNDS = "[)" class ContinuousRangeField(RangeField): """ Continuous range field. It allows specifying default bounds for list and tuple inputs. """ def __init__(self, *args, default_bounds=CANONICAL_RANGE_BOUNDS, **kwargs): if default_bounds not in ("[)", "(]", "()", "[]"): raise ValueError("default_bounds must be one of '[)', '(]', '()', or '[]'.") self.default_bounds = default_bounds super().__init__(*args, **kwargs) def get_prep_value(self, value): if isinstance(value, (list, tuple)): return self.range_type(value[0], value[1], self.default_bounds) return super().get_prep_value(value) def formfield(self, **kwargs): kwargs.setdefault("default_bounds", self.default_bounds) return super().formfield(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.default_bounds and self.default_bounds != CANONICAL_RANGE_BOUNDS: kwargs["default_bounds"] = self.default_bounds return name, path, args, kwargs class IntegerRangeField(RangeField): base_field = models.IntegerField range_type = NumericRange form_field = forms.IntegerRangeField def db_type(self, connection): return "int4range" class BigIntegerRangeField(RangeField): base_field = models.BigIntegerField range_type = NumericRange form_field = forms.IntegerRangeField def db_type(self, connection): return "int8range" class DecimalRangeField(ContinuousRangeField): base_field = models.DecimalField range_type = NumericRange form_field = forms.DecimalRangeField def db_type(self, connection): return "numrange" class DateTimeRangeField(ContinuousRangeField): base_field = models.DateTimeField range_type = DateTimeTZRange form_field = forms.DateTimeRangeField def db_type(self, connection): return "tstzrange" class DateRangeField(RangeField): base_field = models.DateField range_type = DateRange form_field = forms.DateRangeField def db_type(self, connection): return "daterange" RangeField.register_lookup(lookups.DataContains) RangeField.register_lookup(lookups.ContainedBy) RangeField.register_lookup(lookups.Overlap) class DateTimeRangeContains(PostgresOperatorLookup): """ Lookup for Date/DateTimeRange containment to cast the rhs to the correct type. """ lookup_name = "contains" postgres_operator = RangeOperators.CONTAINS def process_rhs(self, compiler, connection): # Transform rhs value for db lookup. if isinstance(self.rhs, datetime.date): value = models.Value(self.rhs) self.rhs = value.resolve_expression(compiler.query) return super().process_rhs(compiler, connection) def as_postgresql(self, compiler, connection): sql, params = super().as_postgresql(compiler, connection) # Cast the rhs if needed. cast_sql = "" if ( isinstance(self.rhs, models.Expression) and self.rhs._output_field_or_none and # Skip cast if rhs has a matching range type. not isinstance( self.rhs._output_field_or_none, self.lhs.output_field.__class__ ) ): cast_internal_type = self.lhs.output_field.base_field.get_internal_type() cast_sql = "::{}".format(connection.data_types.get(cast_internal_type)) return "%s%s" % (sql, cast_sql), params DateRangeField.register_lookup(DateTimeRangeContains) DateTimeRangeField.register_lookup(DateTimeRangeContains) class RangeContainedBy(PostgresOperatorLookup): lookup_name = "contained_by" type_mapping = { "smallint": "int4range", "integer": "int4range", "bigint": "int8range", "double precision": "numrange", "numeric": "numrange", "date": "daterange", "timestamp with time zone": "tstzrange", } postgres_operator = RangeOperators.CONTAINED_BY def process_rhs(self, compiler, connection): rhs, rhs_params = super().process_rhs(compiler, connection) # Ignore precision for DecimalFields. db_type = self.lhs.output_field.cast_db_type(connection).split("(")[0] cast_type = self.type_mapping[db_type] return "%s::%s" % (rhs, cast_type), rhs_params def process_lhs(self, compiler, connection): lhs, lhs_params = super().process_lhs(compiler, connection) if isinstance(self.lhs.output_field, models.FloatField): lhs = "%s::numeric" % lhs elif isinstance(self.lhs.output_field, models.SmallIntegerField): lhs = "%s::integer" % lhs return lhs, lhs_params def get_prep_lookup(self): return RangeField().get_prep_value(self.rhs) models.DateField.register_lookup(RangeContainedBy) models.DateTimeField.register_lookup(RangeContainedBy) models.IntegerField.register_lookup(RangeContainedBy) models.FloatField.register_lookup(RangeContainedBy) models.DecimalField.register_lookup(RangeContainedBy) @RangeField.register_lookup class FullyLessThan(PostgresOperatorLookup): lookup_name = "fully_lt" postgres_operator = RangeOperators.FULLY_LT @RangeField.register_lookup class FullGreaterThan(PostgresOperatorLookup): lookup_name = "fully_gt" postgres_operator = RangeOperators.FULLY_GT @RangeField.register_lookup class NotLessThan(PostgresOperatorLookup): lookup_name = "not_lt" postgres_operator = RangeOperators.NOT_LT @RangeField.register_lookup class NotGreaterThan(PostgresOperatorLookup): lookup_name = "not_gt" postgres_operator = RangeOperators.NOT_GT @RangeField.register_lookup class AdjacentToLookup(PostgresOperatorLookup): lookup_name = "adjacent_to" postgres_operator = RangeOperators.ADJACENT_TO @RangeField.register_lookup class RangeStartsWith(models.Transform): lookup_name = "startswith" function = "lower" @property def output_field(self): return self.lhs.output_field.base_field @RangeField.register_lookup class RangeEndsWith(models.Transform): lookup_name = "endswith" function = "upper" @property def output_field(self): return self.lhs.output_field.base_field @RangeField.register_lookup class IsEmpty(models.Transform): lookup_name = "isempty" function = "isempty" output_field = models.BooleanField() @RangeField.register_lookup class LowerInclusive(models.Transform): lookup_name = "lower_inc" function = "LOWER_INC" output_field = models.BooleanField() @RangeField.register_lookup class LowerInfinite(models.Transform): lookup_name = "lower_inf" function = "LOWER_INF" output_field = models.BooleanField() @RangeField.register_lookup class UpperInclusive(models.Transform): lookup_name = "upper_inc" function = "UPPER_INC" output_field = models.BooleanField() @RangeField.register_lookup class UpperInfinite(models.Transform): lookup_name = "upper_inf" function = "UPPER_INF" output_field = models.BooleanField()
596584a017ccb408dddb6eafbe316d1aa6c73071428d2972f811219bd50dd6a4
import json from django.contrib.postgres import forms, lookups from django.contrib.postgres.fields.array import ArrayField 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__ = ["HStoreField"] class HStoreField(CheckFieldDefaultMixin, Field): empty_strings_allowed = False description = _("Map of strings to strings/nulls") default_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, 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 key, val in value.items(): if not isinstance(val, str) and val is not None: raise exceptions.ValidationError( self.error_messages["not_a_string"], code="not_a_string", params={"key": key}, ) def to_python(self, value): if isinstance(value, str): value = json.loads(value) return value def value_to_string(self, obj): return json.dumps(self.value_from_object(obj)) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.HStoreField, **kwargs, } ) def get_prep_value(self, value): value = super().get_prep_value(value) if isinstance(value, dict): prep_value = {} for key, val in value.items(): key = str(key) if val is not None: val = str(val) prep_value[key] = val value = prep_value if isinstance(value, list): value = [str(item) for item in value] return value HStoreField.register_lookup(lookups.DataContains) HStoreField.register_lookup(lookups.ContainedBy) HStoreField.register_lookup(lookups.HasKey) HStoreField.register_lookup(lookups.HasKeys) HStoreField.register_lookup(lookups.HasAnyKeys) class KeyTransform(Transform): output_field = TextField() def __init__(self, key_name, *args, **kwargs): super().__init__(*args, **kwargs) self.key_name = key_name def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return "(%s -> %%s)" % lhs, tuple(params) + (self.key_name,) class KeyTransformFactory: def __init__(self, key_name): self.key_name = key_name def __call__(self, *args, **kwargs): return KeyTransform(self.key_name, *args, **kwargs) @HStoreField.register_lookup class KeysTransform(Transform): lookup_name = "keys" function = "akeys" output_field = ArrayField(TextField()) @HStoreField.register_lookup class ValuesTransform(Transform): lookup_name = "values" function = "avals" output_field = ArrayField(TextField())
9dc3064fa598ef49426dc9a1c2dbb66e34667c331422f0abefa7e852feedaafd
from django.db.models import JSONField as BuiltinJSONField __all__ = ["JSONField"] class JSONField(BuiltinJSONField): system_check_removed_details = { "msg": ( "django.contrib.postgres.fields.JSONField is removed except for " "support in historical migrations." ), "hint": "Use django.db.models.JSONField instead.", "id": "fields.E904", }
2d1514ddfc5778fa6d321de5a25c615f8b1b323352be7cccbcd81c26894a7d97
import copy from itertools import chain from django import forms from django.contrib.postgres.validators import ( ArrayMaxLengthValidator, ArrayMinLengthValidator, ) from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from ..utils import prefix_validation_error class SimpleArrayField(forms.CharField): default_error_messages = { "item_invalid": _("Item %(nth)s in the array did not validate:"), } def __init__( self, base_field, *, delimiter=",", max_length=None, min_length=None, **kwargs ): self.base_field = base_field self.delimiter = delimiter super().__init__(**kwargs) 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_length 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 isinstance(value, list): return self.delimiter.join( str(self.base_field.prepare_value(v)) for v in value ) return value def to_python(self, value): if isinstance(value, list): items = value elif value: items = value.split(self.delimiter) else: items = [] errors = [] values = [] for index, item in enumerate(items): try: values.append(self.base_field.to_python(item)) except ValidationError as error: errors.append( prefix_validation_error( error, prefix=self.error_messages["item_invalid"], code="item_invalid", params={"nth": index + 1}, ) ) if errors: raise ValidationError(errors) return values def validate(self, value): super().validate(value) errors = [] for index, item in enumerate(value): try: self.base_field.validate(item) except ValidationError as error: errors.append( prefix_validation_error( error, prefix=self.error_messages["item_invalid"], code="item_invalid", params={"nth": index + 1}, ) ) if errors: raise ValidationError(errors) def run_validators(self, value): super().run_validators(value) errors = [] for index, item in enumerate(value): try: self.base_field.run_validators(item) except ValidationError as error: errors.append( prefix_validation_error( error, prefix=self.error_messages["item_invalid"], code="item_invalid", params={"nth": index + 1}, ) ) if errors: raise ValidationError(errors) def has_changed(self, initial, data): try: value = self.to_python(data) except ValidationError: pass else: if initial in self.empty_values and value in self.empty_values: return False return super().has_changed(initial, data) class SplitArrayWidget(forms.Widget): template_name = "postgres/widgets/split_array.html" def __init__(self, widget, size, **kwargs): self.widget = widget() if isinstance(widget, type) else widget self.size = size super().__init__(**kwargs) @property def is_hidden(self): return self.widget.is_hidden def value_from_datadict(self, data, files, name): return [ self.widget.value_from_datadict(data, files, "%s_%s" % (name, index)) for index in range(self.size) ] def value_omitted_from_data(self, data, files, name): return all( self.widget.value_omitted_from_data(data, files, "%s_%s" % (name, index)) for index in range(self.size) ) def id_for_label(self, id_): # See the comment for RadioSelect.id_for_label() if id_: id_ += "_0" return id_ def get_context(self, name, value, attrs=None): attrs = {} if attrs is None else attrs context = super().get_context(name, value, attrs) if self.is_localized: self.widget.is_localized = self.is_localized value = value or [] context["widget"]["subwidgets"] = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get("id") for i in range(max(len(value), self.size)): try: widget_value = value[i] except IndexError: widget_value = None if id_: final_attrs = {**final_attrs, "id": "%s_%s" % (id_, i)} context["widget"]["subwidgets"].append( self.widget.get_context(name + "_%s" % i, widget_value, final_attrs)[ "widget" ] ) return context @property def media(self): return self.widget.media def __deepcopy__(self, memo): obj = super().__deepcopy__(memo) obj.widget = copy.deepcopy(self.widget) return obj @property def needs_multipart_form(self): return self.widget.needs_multipart_form class SplitArrayField(forms.Field): default_error_messages = { "item_invalid": _("Item %(nth)s in the array did not validate:"), } def __init__(self, base_field, size, *, remove_trailing_nulls=False, **kwargs): self.base_field = base_field self.size = size self.remove_trailing_nulls = remove_trailing_nulls widget = SplitArrayWidget(widget=base_field.widget, size=size) kwargs.setdefault("widget", widget) super().__init__(**kwargs) def _remove_trailing_nulls(self, values): index = None if self.remove_trailing_nulls: for i, value in reversed(list(enumerate(values))): if value in self.base_field.empty_values: index = i else: break if index is not None: values = values[:index] return values, index def to_python(self, value): value = super().to_python(value) return [self.base_field.to_python(item) for item in value] def clean(self, value): cleaned_data = [] errors = [] if not any(value) and self.required: raise ValidationError(self.error_messages["required"]) max_size = max(self.size, len(value)) for index in range(max_size): item = value[index] try: cleaned_data.append(self.base_field.clean(item)) except ValidationError as error: errors.append( prefix_validation_error( error, self.error_messages["item_invalid"], code="item_invalid", params={"nth": index + 1}, ) ) cleaned_data.append(None) else: errors.append(None) cleaned_data, null_index = self._remove_trailing_nulls(cleaned_data) if null_index is not None: errors = errors[:null_index] errors = list(filter(None, errors)) if errors: raise ValidationError(list(chain.from_iterable(errors))) return cleaned_data def has_changed(self, initial, data): try: data = self.to_python(data) except ValidationError: pass else: data, _ = self._remove_trailing_nulls(data) if initial in self.empty_values and data in self.empty_values: return False return super().has_changed(initial, data)
7ebaea239e7159dbd5a19c1119a553b2c4460bcb9f93f945bf28be86286554b4
from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange from django import forms from django.core import exceptions from django.forms.widgets import HiddenInput, MultiWidget from django.utils.translation import gettext_lazy as _ __all__ = [ "BaseRangeField", "IntegerRangeField", "DecimalRangeField", "DateTimeRangeField", "DateRangeField", "HiddenRangeWidget", "RangeWidget", ] class RangeWidget(MultiWidget): def __init__(self, base_widget, attrs=None): widgets = (base_widget, base_widget) super().__init__(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 <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_ordering": _( "The start of the range must not exceed the end of the range." ), } hidden_widget = HiddenRangeWidget def __init__(self, **kwargs): if "widget" not in kwargs: kwargs["widget"] = RangeWidget(self.base_field.widget) if "fields" not in kwargs: kwargs["fields"] = [ self.base_field(required=False), self.base_field(required=False), ] kwargs.setdefault("required", False) kwargs.setdefault("require_all_fields", False) self.range_kwargs = {} if default_bounds := kwargs.pop("default_bounds", None): self.range_kwargs = {"bounds": default_bounds} super().__init__(**kwargs) def prepare_value(self, value): lower_base, upper_base = self.fields if isinstance(value, self.range_type): return [ lower_base.prepare_value(value.lower), upper_base.prepare_value(value.upper), ] if value is None: return [ lower_base.prepare_value(None), upper_base.prepare_value(None), ] return value def compress(self, values): if not values: return None lower, upper = values if lower is not None and upper is not None and lower > upper: raise exceptions.ValidationError( self.error_messages["bound_ordering"], code="bound_ordering", ) try: range_value = self.range_type(lower, upper, **self.range_kwargs) except TypeError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", ) else: return range_value class IntegerRangeField(BaseRangeField): default_error_messages = {"invalid": _("Enter two whole numbers.")} base_field = forms.IntegerField range_type = NumericRange class DecimalRangeField(BaseRangeField): default_error_messages = {"invalid": _("Enter two numbers.")} base_field = forms.DecimalField range_type = NumericRange class DateTimeRangeField(BaseRangeField): default_error_messages = {"invalid": _("Enter two valid date/times.")} base_field = forms.DateTimeField range_type = DateTimeTZRange class DateRangeField(BaseRangeField): default_error_messages = {"invalid": _("Enter two valid dates.")} base_field = forms.DateField range_type = DateRange
5cde713ab23e8c2793b161448cf5dfe9731a2f325d5e2a80ea94dd1928d674ec
import json from django 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 = { "invalid_json": _("Could not load JSON data."), "invalid_format": _("Input must be a JSON dictionary."), } def prepare_value(self, value): if isinstance(value, dict): return json.dumps(value) return value def to_python(self, value): if not value: return {} if not isinstance(value, dict): try: value = json.loads(value) except json.JSONDecodeError: raise ValidationError( self.error_messages["invalid_json"], code="invalid_json", ) if not isinstance(value, dict): raise ValidationError( self.error_messages["invalid_format"], code="invalid_format", ) # Cast everything to strings for ease. for key, val in value.items(): if val is not None: val = str(val) value[key] = val return value def has_changed(self, initial, data): """ Return True if data differs from initial. """ # For purposes of seeing whether something has changed, None is # the same as an empty dict, if the data or initial value we get # is None, replace it w/ {}. initial_value = self.to_python(initial) return super().has_changed(initial_value, data)
a64a75bb29f626bcb21e162ae9cbcc7df8c1c2690cb67f7d7e8b40f0583ce5f6
import warnings from django.contrib.postgres.fields import ArrayField from django.db.models import Aggregate, BooleanField, JSONField, TextField, Value from django.utils.deprecation import RemovedInDjango50Warning from .mixins import OrderableAggMixin __all__ = [ "ArrayAgg", "BitAnd", "BitOr", "BitXor", "BoolAnd", "BoolOr", "JSONBAgg", "StringAgg", ] # RemovedInDjango50Warning NOT_PROVIDED = object() class DeprecatedConvertValueMixin: def __init__(self, *expressions, default=NOT_PROVIDED, **extra): if default is NOT_PROVIDED: default = None self._default_provided = False else: self._default_provided = True super().__init__(*expressions, default=default, **extra) def convert_value(self, value, expression, connection): if value is None and not self._default_provided: warnings.warn(self.deprecation_msg, category=RemovedInDjango50Warning) return self.deprecation_value return value class ArrayAgg(DeprecatedConvertValueMixin, OrderableAggMixin, Aggregate): function = "ARRAY_AGG" template = "%(function)s(%(distinct)s%(expressions)s %(ordering)s)" allow_distinct = True # RemovedInDjango50Warning deprecation_value = property(lambda self: []) deprecation_msg = ( "In Django 5.0, ArrayAgg() will return None instead of an empty list " "if there are no rows. Pass default=None to opt into the new behavior " "and silence this warning or default=Value([]) to keep the previous " "behavior." ) @property def output_field(self): return ArrayField(self.source_expressions[0].output_field) class BitAnd(Aggregate): function = "BIT_AND" class BitOr(Aggregate): function = "BIT_OR" class BitXor(Aggregate): function = "BIT_XOR" class BoolAnd(Aggregate): function = "BOOL_AND" output_field = BooleanField() class BoolOr(Aggregate): function = "BOOL_OR" output_field = BooleanField() class JSONBAgg(DeprecatedConvertValueMixin, OrderableAggMixin, Aggregate): function = "JSONB_AGG" template = "%(function)s(%(distinct)s%(expressions)s %(ordering)s)" allow_distinct = True output_field = JSONField() # RemovedInDjango50Warning deprecation_value = "[]" deprecation_msg = ( "In Django 5.0, JSONBAgg() will return None instead of an empty list " "if there are no rows. Pass default=None to opt into the new behavior " "and silence this warning or default=Value('[]') to keep the previous " "behavior." ) class StringAgg(DeprecatedConvertValueMixin, OrderableAggMixin, Aggregate): function = "STRING_AGG" template = "%(function)s(%(distinct)s%(expressions)s %(ordering)s)" allow_distinct = True output_field = TextField() # RemovedInDjango50Warning deprecation_value = "" deprecation_msg = ( "In Django 5.0, StringAgg() will return None instead of an empty " "string if there are no rows. Pass default=None to opt into the new " "behavior and silence this warning or default=Value('') to keep the " "previous behavior." ) def __init__(self, expression, delimiter, **extra): delimiter_expr = Value(str(delimiter)) super().__init__(expression, delimiter_expr, **extra)
c525a4e59e595693362d268c80ff7ba717228ce9cf1e23c04dedd7e39a685c22
from django.db.models import Aggregate, FloatField, IntegerField __all__ = [ "CovarPop", "Corr", "RegrAvgX", "RegrAvgY", "RegrCount", "RegrIntercept", "RegrR2", "RegrSlope", "RegrSXX", "RegrSXY", "RegrSYY", "StatAggregate", ] class StatAggregate(Aggregate): output_field = FloatField() def __init__(self, y, x, output_field=None, filter=None, default=None): if not x or not y: raise ValueError("Both y and x must be provided.") super().__init__( 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, default=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" class RegrCount(StatAggregate): function = "REGR_COUNT" output_field = IntegerField() empty_result_set_value = 0 class RegrIntercept(StatAggregate): function = "REGR_INTERCEPT" class RegrR2(StatAggregate): function = "REGR_R2" class RegrSlope(StatAggregate): function = "REGR_SLOPE" class RegrSXX(StatAggregate): function = "REGR_SXX" class RegrSXY(StatAggregate): function = "REGR_SXY" class RegrSYY(StatAggregate): function = "REGR_SYY"
999a949c745b237ee5b3c1569fd28f68beb9277be2387562454850e61a281b3d
from django.db.models.expressions import OrderByList class OrderableAggMixin: def __init__(self, *expressions, ordering=(), **extra): if isinstance(ordering, (list, tuple)): self.order_by = OrderByList(*ordering) else: self.order_by = OrderByList(ordering) super().__init__(*expressions, **extra) def resolve_expression(self, *args, **kwargs): self.order_by = self.order_by.resolve_expression(*args, **kwargs) return super().resolve_expression(*args, **kwargs) def get_source_expressions(self): return super().get_source_expressions() + [self.order_by] def set_source_expressions(self, exprs): *exprs, self.order_by = exprs return super().set_source_expressions(exprs) def as_sql(self, compiler, connection): order_by_sql, order_by_params = compiler.compile(self.order_by) sql, sql_params = super().as_sql(compiler, connection, ordering=order_by_sql) return sql, (*sql_params, *order_by_params)
a945949283396a4e72c15ba557d77328d6f2de20d9806db5d9cf54eb9f4a7508
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("redirects", "0001_initial"), ] operations = [ migrations.AlterField( model_name="redirect", name="new_path", field=models.CharField( blank=True, help_text=( "This can be either an absolute path (as above) or a full " "URL starting with a scheme such as “https://”." ), max_length=200, verbose_name="redirect to", ), ), ]
1660b0e91efe04ad9b408b1eb420033ca8d5fece5b538fe040b5f3b396324ab9
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("sites", "0001_initial"), ] operations = [ migrations.CreateModel( name="Redirect", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "site", models.ForeignKey( to="sites.Site", on_delete=models.CASCADE, verbose_name="site", ), ), ( "old_path", models.CharField( help_text=( "This should be an absolute path, excluding the domain " "name. Example: “/events/search/”." ), max_length=200, verbose_name="redirect from", db_index=True, ), ), ( "new_path", models.CharField( help_text=( "This can be either an absolute path (as above) or a full " "URL starting with “http://”." ), max_length=200, verbose_name="redirect to", blank=True, ), ), ], options={ "ordering": ["old_path"], "unique_together": {("site", "old_path")}, "db_table": "django_redirect", "verbose_name": "redirect", "verbose_name_plural": "redirects", }, bases=(models.Model,), ), ]
f40bc41bc6025c57b89a6fdb8f18e9ebee48bc87a8bba6ff40fecaaf91530fe5
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0011_update_proxy_permissions"), ] operations = [ migrations.AlterField( model_name="user", name="first_name", field=models.CharField( blank=True, max_length=150, verbose_name="first name" ), ), ]
36f14a97d231700133d8e8b6d6edd74af90ad4323a6588347a65bfecf40ca9ef
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0004_alter_user_username_opts"), ] operations = [ migrations.AlterField( model_name="user", name="last_login", field=models.DateTimeField( null=True, verbose_name="last login", blank=True ), ), ]
8fb6026e592e573e745f5a5974ccd159725277006b1c43add64c9501edc0b2a6
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0009_alter_user_last_name_max_length"), ] operations = [ migrations.AlterField( model_name="group", name="name", field=models.CharField(max_length=150, unique=True, verbose_name="name"), ), ]
39f8f71c6212ac5df9a6a983f9506bd6b95b2d3b33c5a78f597ad42d10dcd203
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0001_initial"), ] operations = [ migrations.AlterField( model_name="permission", name="name", field=models.CharField(max_length=255, verbose_name="name"), ), ]
10110f36e489b57063e7c9b6c7eaebdd658249cdf4b2c1d6234362ebf83d82d9
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("auth", "0005_alter_user_last_login_null"), ("contenttypes", "0002_remove_content_type_name"), ] operations = [ # Ensure the contenttypes migration is applied before sending # post_migrate signals (which create ContentTypes). ]
f1879b6e37b62d0328f1196f2e18ae3715d3fc58e8eb4cc43121b059372d0f60
from django.contrib.auth import validators from 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", name="username", field=models.CharField( error_messages={"unique": "A user with that username already exists."}, max_length=30, validators=[validators.UnicodeUsernameValidator()], help_text=( "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ " "only." ), unique=True, verbose_name="username", ), ), ]
0e8d3a52b59b704e9dfed9aa92145f53c4eca714978be4c830f713d5d194e7b9
import sys from django.core.management.color import 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} and {new}. """ def update_proxy_model_permissions(apps, schema_editor, reverse=False): """ Update the content_type of proxy model permissions to use the ContentType of the proxy model. """ 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_models(): 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(codename__in=proxy_default_permissions_codenames) for codename, name in opts.permissions: permissions_query = permissions_query | Q(codename=codename, name=name) content_type_manager = ContentType.objects.db_manager(alias) concrete_content_type = content_type_manager.get_for_model( Model, for_concrete_model=True ) proxy_content_type = content_type_manager.get_for_model( Model, for_concrete_model=False ) old_content_type = proxy_content_type if reverse else concrete_content_type new_content_type = concrete_content_type if reverse else proxy_content_type try: with transaction.atomic(using=alias): Permission.objects.using(alias).filter( permissions_query, content_type=old_content_type, ).update(content_type=new_content_type) except IntegrityError: old = "{}_{}".format(old_content_type.app_label, old_content_type.model) new = "{}_{}".format(new_content_type.app_label, new_content_type.model) sys.stdout.write( style.WARNING(WARNING.format(old=old, new=new, query=permissions_query)) ) def revert_proxy_model_permissions(apps, schema_editor): """ Update the content_type of proxy model permissions to use the ContentType of the concrete model. """ update_proxy_model_permissions(apps, schema_editor, reverse=True) class Migration(migrations.Migration): dependencies = [ ("auth", "0010_alter_group_name_max_length"), ("contenttypes", "0002_remove_content_type_name"), ] operations = [ migrations.RunPython( update_proxy_model_permissions, revert_proxy_model_permissions ), ]
4f9fb2e115587b947d761acfd95bc5ae6aeeb8db3e509f1b1cbe391487d0b633
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0008_alter_user_username_max_length"), ] operations = [ migrations.AlterField( model_name="user", name="last_name", field=models.CharField( blank=True, max_length=150, verbose_name="last name" ), ), ]
828b3771674ae9bbac8268c7e1d50147e4bdffb9be2c8605ec0b5322519116ae
import django.contrib.auth.models from django.contrib.auth import validators from django.db import migrations, models from django.utils import timezone class Migration(migrations.Migration): dependencies = [ ("contenttypes", "__first__"), ] operations = [ migrations.CreateModel( name="Permission", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("name", models.CharField(max_length=50, verbose_name="name")), ( "content_type", models.ForeignKey( to="contenttypes.ContentType", on_delete=models.CASCADE, verbose_name="content type", ), ), ("codename", models.CharField(max_length=100, verbose_name="codename")), ], options={ "ordering": [ "content_type__app_label", "content_type__model", "codename", ], "unique_together": {("content_type", "codename")}, "verbose_name": "permission", "verbose_name_plural": "permissions", }, managers=[ ("objects", django.contrib.auth.models.PermissionManager()), ], ), migrations.CreateModel( name="Group", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "name", models.CharField(unique=True, max_length=80, verbose_name="name"), ), ( "permissions", models.ManyToManyField( to="auth.Permission", verbose_name="permissions", blank=True ), ), ], options={ "verbose_name": "group", "verbose_name_plural": "groups", }, managers=[ ("objects", django.contrib.auth.models.GroupManager()), ], ), migrations.CreateModel( name="User", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("password", models.CharField(max_length=128, verbose_name="password")), ( "last_login", models.DateTimeField( default=timezone.now, verbose_name="last login" ), ), ( "is_superuser", models.BooleanField( default=False, help_text=( "Designates that this user has all permissions without " "explicitly assigning them." ), verbose_name="superuser status", ), ), ( "username", models.CharField( help_text=( "Required. 30 characters or fewer. Letters, digits and " "@/./+/-/_ only." ), unique=True, max_length=30, verbose_name="username", validators=[validators.UnicodeUsernameValidator()], ), ), ( "first_name", models.CharField( max_length=30, verbose_name="first name", blank=True ), ), ( "last_name", models.CharField( max_length=30, verbose_name="last name", blank=True ), ), ( "email", models.EmailField( max_length=75, verbose_name="email address", blank=True ), ), ( "is_staff", models.BooleanField( default=False, help_text=( "Designates whether the user can log into this admin site." ), verbose_name="staff status", ), ), ( "is_active", models.BooleanField( default=True, verbose_name="active", help_text=( "Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts." ), ), ), ( "date_joined", models.DateTimeField( default=timezone.now, verbose_name="date joined" ), ), ( "groups", models.ManyToManyField( to="auth.Group", verbose_name="groups", blank=True, related_name="user_set", related_query_name="user", help_text=( "The groups this user belongs to. A user will get all " "permissions granted to each of their groups." ), ), ), ( "user_permissions", models.ManyToManyField( to="auth.Permission", verbose_name="user permissions", blank=True, help_text="Specific permissions for this user.", related_name="user_set", related_query_name="user", ), ), ], options={ "swappable": "AUTH_USER_MODEL", "verbose_name": "user", "verbose_name_plural": "users", }, managers=[ ("objects", django.contrib.auth.models.UserManager()), ], ), ]
eec1627b82cbaa97bbe1d641ea08f299cd8f27a166f11d62fbf2ffd4eb6bdb4e
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0002_alter_permission_name_max_length"), ] operations = [ migrations.AlterField( model_name="user", name="email", field=models.EmailField( max_length=254, verbose_name="email address", blank=True ), ), ]
bca2ac98fbb9ffa12ac880eb4910722a7f6386b77efce1a04b043ee3ec7f6514
from django.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", field=models.CharField( error_messages={"unique": "A user with that username already exists."}, help_text=( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ " "only." ), max_length=150, unique=True, validators=[validators.UnicodeUsernameValidator()], verbose_name="username", ), ), ]
da63a0660af78a7d5453c24044e72e94f2a6ffc86a4936cf3c55775e015cfcaa
from 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", field=models.CharField( error_messages={"unique": "A user with that username already exists."}, help_text=( "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ " "only." ), max_length=30, unique=True, validators=[validators.UnicodeUsernameValidator()], verbose_name="username", ), ), ]
b8a13bed15fa8904836f407a64ff904edfa48d27a598163a1504aac57bf7cef2
""" Creates permissions for all installed apps that need permissions. """ import getpass import unicodedata from django.apps import apps as global_apps from django.contrib.auth import get_permission_codename from django.contrib.contenttypes.management import create_contenttypes from django.core import exceptions from django.db import DEFAULT_DB_ALIAS, router 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 (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete', 'view') """ perms = [] for action in opts.default_permissions: perms.append( ( get_permission_codename(action, opts), "Can %s %s" % (action, opts.verbose_name_raw), ) ) return perms def create_permissions( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs, ): if not app_config.models_module: return # Ensure that contenttypes are created for this app. Needed if # 'django.contrib.auth' is in INSTALLED_APPS before # 'django.contrib.contenttypes'. create_contenttypes( app_config, verbosity=verbosity, interactive=interactive, using=using, apps=apps, **kwargs, ) app_label = app_config.label try: app_config = apps.get_app_config(app_label) ContentType = apps.get_model("contenttypes", "ContentType") Permission = apps.get_model("auth", "Permission") except LookupError: return if not router.allow_migrate_model(using, Permission): return # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = [] # The codenames and ctypes that should exist. ctypes = set() for klass in app_config.get_models(): # Force looking up the content types in the current database # before creating foreign keys to them. ctype = ContentType.objects.db_manager(using).get_for_model( klass, for_concrete_model=False ) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.using(using) .filter( content_type__in=ctypes, ) .values_list("content_type", "codename") ) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm) def get_system_username(): """ Return the current system user's username, or an empty string if the username could not be determined. """ try: result = getpass.getuser() except (ImportError, KeyError): # KeyError will be raised by os.getpwuid() (called by getuser()) # if there is no corresponding entry in the /etc/passwd file # (a very restricted chroot environment, for example). return "" return result def get_default_username(check_db=True, database=DEFAULT_DB_ALIAS): """ Try to determine the current system user's username to use as a default. :param check_db: If ``True``, requires that the username does not match an existing ``auth.User`` (otherwise returns an empty string). :param database: The database where the unique check will be performed. :returns: The username, or an empty string if no username can be determined or the suggested username is already taken. """ # This file is used in apps.py, it should not trigger models import. from django.contrib.auth import models as auth_app # If the User model has been swapped out, we can't make any assumptions # about the default user name. if auth_app.User._meta.swapped: return "" default_username = get_system_username() try: default_username = ( unicodedata.normalize("NFKD", default_username) .encode("ascii", "ignore") .decode("ascii") .replace(" ", "") .lower() ) except UnicodeDecodeError: return "" # Run the username validator try: auth_app.User._meta.get_field("username").run_validators(default_username) except exceptions.ValidationError: return "" # Don't return the default username if it is already taken. if check_db and default_username: try: auth_app.User._default_manager.db_manager(database).get( username=default_username, ) except auth_app.User.DoesNotExist: pass else: return "" return default_username
b8c0346e6f17cb6268bcff4ce16ad5759178ab18112cc69e6f1dec113d812926
import getpass from django.contrib.auth import get_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 UserModel = get_user_model() class Command(BaseCommand): help = "Change a user's password for django.contrib.auth." requires_migrations_checks = True requires_system_checks = [] def _get_pass(self, prompt="Password: "): p = getpass.getpass(prompt=prompt) if not p: raise CommandError("aborted") return p def add_arguments(self, parser): parser.add_argument( "username", nargs="?", help=( "Username to change password for; by default, it's the current " "username." ), ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".', ) def handle(self, *args, **options): if options["username"]: username = options["username"] else: username = getpass.getuser() try: u = UserModel._default_manager.using(options["database"]).get( **{UserModel.USERNAME_FIELD: username} ) except UserModel.DoesNotExist: raise CommandError("user '%s' does not exist" % username) self.stdout.write("Changing password for user '%s'" % u) MAX_TRIES = 3 count = 0 p1, p2 = 1, 2 # To make them initially mismatch. password_validated = False while (p1 != p2 or not password_validated) and count < MAX_TRIES: p1 = self._get_pass() p2 = self._get_pass("Password (again): ") if p1 != p2: self.stdout.write("Passwords do not match. Please try again.") count += 1 # Don't validate passwords that don't match. continue try: validate_password(p2, u) except ValidationError as err: self.stderr.write("\n".join(err.messages)) count += 1 else: password_validated = True if count == MAX_TRIES: raise CommandError( "Aborting password change for user '%s' after %s attempts" % (u, count) ) u.set_password(p1) u.save() return "Password changed successfully for user '%s'" % u
e6e920c3cf3433abbba5bbe05a3afaeae2ca763a0412f6ad0bd946c93d37514d
""" Management utility to create superusers. """ import getpass import os import sys from django.contrib.auth import get_user_model from django.contrib.auth.management import get_default_username from django.contrib.auth.password_validation import validate_password from django.core import exceptions from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS 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 = ("stdin",) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.UserModel = get_user_model() self.username_field = self.UserModel._meta.get_field( self.UserModel.USERNAME_FIELD ) def add_arguments(self, parser): parser.add_argument( "--%s" % self.UserModel.USERNAME_FIELD, help="Specifies the login for the superuser.", ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help=( "Tells Django to NOT prompt the user for input of any kind. " "You must use --%s with --noinput, along with an option for " "any other required field. Superusers created with --noinput will " "not be able to log in until they're given a valid password." % self.UserModel.USERNAME_FIELD ), ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".', ) for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) if field.many_to_many: if ( field.remote_field.through and not field.remote_field.through._meta.auto_created ): raise CommandError( "Required field '%s' specifies a many-to-many " "relation through model, which is not supported." % field_name ) else: parser.add_argument( "--%s" % field_name, action="append", help=( "Specifies the %s for the superuser. Can be used " "multiple times." % field_name, ), ) else: parser.add_argument( "--%s" % field_name, help="Specifies the %s for the superuser." % field_name, ) def execute(self, *args, **options): self.stdin = options.get("stdin", sys.stdin) # Used for testing return super().execute(*args, **options) def handle(self, *args, **options): username = options[self.UserModel.USERNAME_FIELD] database = options["database"] user_data = {} verbose_field_name = self.username_field.verbose_name try: self.UserModel._meta.get_field(PASSWORD_FIELD) except exceptions.FieldDoesNotExist: pass else: # If not provided, create the user with an unusable password. user_data[PASSWORD_FIELD] = None try: if options["interactive"]: # Same as user_data but without many to many fields and with # foreign keys as fake model instances instead of raw IDs. fake_user_data = {} if hasattr(self.stdin, "isatty") and not self.stdin.isatty(): raise NotRunningInTTYException default_username = get_default_username(database=database) if username: error_msg = self._validate_username( username, verbose_field_name, database ) if error_msg: self.stderr.write(error_msg) username = None elif username == "": raise CommandError( "%s cannot be blank." % capfirst(verbose_field_name) ) # Prompt for username. while username is None: message = self._get_input_message( self.username_field, default_username ) username = self.get_input_data( self.username_field, message, default_username ) if username: error_msg = self._validate_username( username, verbose_field_name, database ) if error_msg: self.stderr.write(error_msg) username = None continue user_data[self.UserModel.USERNAME_FIELD] = username fake_user_data[self.UserModel.USERNAME_FIELD] = ( self.username_field.remote_field.model(username) if self.username_field.remote_field else username ) # Prompt for required fields. for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = options[field_name] if user_data[field_name] is not None: user_data[field_name] = field.clean(user_data[field_name], None) while user_data[field_name] is None: message = self._get_input_message(field) input_value = self.get_input_data(field, message) user_data[field_name] = input_value if field.many_to_many and input_value: if not input_value.strip(): user_data[field_name] = None self.stderr.write("Error: This field cannot be blank.") continue user_data[field_name] = [ pk.strip() for pk in input_value.split(",") ] if not field.many_to_many: fake_user_data[field_name] = user_data[field_name] # Wrap any foreign keys in fake model instances. if field.many_to_one: fake_user_data[field_name] = field.remote_field.model( user_data[field_name] ) # Prompt for a password if the model has one. while PASSWORD_FIELD in user_data and user_data[PASSWORD_FIELD] is None: password = getpass.getpass() password2 = getpass.getpass("Password (again): ") if password != password2: self.stderr.write("Error: Your passwords didn't match.") # Don't validate passwords that don't match. continue if password.strip() == "": self.stderr.write("Error: Blank passwords aren't allowed.") # Don't validate blank passwords. continue try: validate_password(password2, self.UserModel(**fake_user_data)) except exceptions.ValidationError as err: self.stderr.write("\n".join(err.messages)) response = input( "Bypass password validation and create user anyway? [y/N]: " ) if response.lower() != "y": continue user_data[PASSWORD_FIELD] = password else: # Non-interactive mode. # Use password from environment variable, if provided. if ( PASSWORD_FIELD in user_data and "DJANGO_SUPERUSER_PASSWORD" in os.environ ): user_data[PASSWORD_FIELD] = os.environ["DJANGO_SUPERUSER_PASSWORD"] # Use username from environment variable, if not provided in # options. if username is None: username = os.environ.get( "DJANGO_SUPERUSER_" + self.UserModel.USERNAME_FIELD.upper() ) if username is None: raise CommandError( "You must use --%s with --noinput." % self.UserModel.USERNAME_FIELD ) else: error_msg = self._validate_username( username, verbose_field_name, database ) if error_msg: raise CommandError(error_msg) user_data[self.UserModel.USERNAME_FIELD] = username for field_name in self.UserModel.REQUIRED_FIELDS: env_var = "DJANGO_SUPERUSER_" + field_name.upper() value = options[field_name] or os.environ.get(env_var) if not value: raise CommandError( "You must use --%s with --noinput." % field_name ) field = self.UserModel._meta.get_field(field_name) user_data[field_name] = field.clean(value, None) if field.many_to_many and isinstance(user_data[field_name], str): user_data[field_name] = [ pk.strip() for pk in user_data[field_name].split(",") ] self.UserModel._default_manager.db_manager(database).create_superuser( **user_data ) if options["verbosity"] >= 1: self.stdout.write("Superuser created successfully.") except KeyboardInterrupt: self.stderr.write("\nOperation cancelled.") sys.exit(1) except exceptions.ValidationError as e: raise CommandError("; ".join(e.messages)) except NotRunningInTTYException: self.stdout.write( "Superuser creation skipped due to not running in a TTY. " "You can run `manage.py createsuperuser` in your project " "to create one manually." ) def get_input_data(self, field, message, default=None): """ Override this method if you want to customize data inputs or validation exceptions. """ raw_value = input(message) if default and raw_value == "": raw_value = default try: val = field.clean(raw_value, None) except exceptions.ValidationError as e: self.stderr.write("Error: %s" % "; ".join(e.messages)) val = None return val def _get_input_message(self, field, default=None): return "%s%s%s: " % ( capfirst(field.verbose_name), " (leave blank to use '%s')" % default if default else "", " (%s.%s)" % ( field.remote_field.model._meta.object_name, field.m2m_target_field_name() if field.many_to_many else field.remote_field.field_name, ) if field.remote_field else "", ) def _validate_username(self, username, verbose_field_name, database): """Validate username. If invalid, return a string error message.""" if self.username_field.unique: try: self.UserModel._default_manager.db_manager(database).get_by_natural_key( username ) except self.UserModel.DoesNotExist: pass else: return "Error: That %s is already taken." % verbose_field_name if not username: return "%s cannot be blank." % capfirst(verbose_field_name) try: self.username_field.clean(username, None) except exceptions.ValidationError as e: return "; ".join(e.messages)
16375ae93f5900b3a4d00a68bb16cf7b93e1e110866628298181198a9a85b53e
from django.db import migrations, models from django.utils import timezone class Migration(migrations.Migration): dependencies = [ ("admin", "0001_initial"), ] # No database changes; removes auto_add and adds default/editable. operations = [ migrations.AlterField( model_name="logentry", name="action_time", field=models.DateTimeField( verbose_name="action time", default=timezone.now, editable=False, ), ), ]
398bab5f7fa9cbb7cb99fbb0cb38440fd79f83be2602eb7dd92f8d12a80120d7
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("admin", "0002_logentry_remove_auto_add"), ] # No database changes; adds choices to action_flag. operations = [ migrations.AlterField( model_name="logentry", name="action_flag", field=models.PositiveSmallIntegerField( choices=[(1, "Addition"), (2, "Change"), (3, "Deletion")], verbose_name="action flag", ), ), ]
cc52b7e219961eb306155ca8a16ba0f5375544fcdbabd62d969ccc51affec266
import django.contrib.admin.models from django.conf 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", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "action_time", models.DateTimeField(auto_now=True, verbose_name="action time"), ), ( "object_id", models.TextField(null=True, verbose_name="object id", blank=True), ), ( "object_repr", models.CharField(max_length=200, verbose_name="object repr"), ), ( "action_flag", models.PositiveSmallIntegerField(verbose_name="action flag"), ), ( "change_message", models.TextField(verbose_name="change message", blank=True), ), ( "content_type", models.ForeignKey( on_delete=models.SET_NULL, blank=True, null=True, to="contenttypes.ContentType", verbose_name="content type", ), ), ( "user", models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="user", ), ), ], options={ "ordering": ["-action_time"], "db_table": "django_admin_log", "verbose_name": "log entry", "verbose_name_plural": "log entries", }, bases=(models.Model,), managers=[ ("objects", django.contrib.admin.models.LogEntryManager()), ], ), ]
e27758758a0f2e15ac76eb4c1342f1b2671fe9414fe59da8bb7fe932380d6f0f
from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test def staff_member_required( view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url="admin:login" ): """ Decorator for views that checks that the user is logged in and is a staff member, redirecting to the login page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_active and u.is_staff, login_url=login_url, redirect_field_name=redirect_field_name, ) if view_func: return actual_decorator(view_func) return actual_decorator
db2e3992f7de70d8ff344396b452ace014884240a513ae456f64f3d4f253b057
from datetime import datetime, timedelta from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import FieldListFilter from django.contrib.admin.exceptions import ( DisallowedModelAdminLookup, DisallowedModelAdminToField, ) from django.contrib.admin.options import ( IS_POPUP_VAR, TO_FIELD_VAR, IncorrectLookupParameters, ) from django.contrib.admin.utils import ( get_fields_from_path, lookup_spawns_duplicates, prepare_lookup_value, quote, ) from django.core.exceptions import ( FieldDoesNotExist, ImproperlyConfigured, SuspiciousOperation, ) from django.core.paginator import InvalidPage from django.db.models import Exists, F, Field, ManyToOneRel, OrderBy, OuterRef 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 # Changelist settings ALL_VAR = "all" ORDER_VAR = "o" PAGE_VAR = "p" SEARCH_VAR = "q" ERROR_FLAG = "e" IGNORED_PARAMS = (ALL_VAR, ORDER_VAR, SEARCH_VAR, IS_POPUP_VAR, TO_FIELD_VAR) class ChangeListSearchForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Populate "fields" dynamically because SEARCH_VAR is a variable: self.fields = { SEARCH_VAR: forms.CharField(required=False, strip=False), } class ChangeList: search_form_class = ChangeListSearchForm def __init__( self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin, sortable_by, search_help_text, ): self.model = model self.opts = model._meta self.lookup_opts = self.opts self.root_queryset = model_admin.get_queryset(request) self.list_display = list_display self.list_display_links = list_display_links self.list_filter = list_filter self.has_filters = None self.has_active_filters = None self.clear_all_filters_qs = None self.date_hierarchy = date_hierarchy self.search_fields = search_fields self.list_select_related = list_select_related self.list_per_page = list_per_page self.list_max_show_all = list_max_show_all self.model_admin = model_admin self.preserved_filters = model_admin.get_preserved_filters(request) self.sortable_by = sortable_by self.search_help_text = search_help_text # Get search parameters from the query string. _search_form = self.search_form_class(request.GET) if not _search_form.is_valid(): for error in _search_form.errors.values(): messages.error(request, ", ".join(error)) self.query = _search_form.cleaned_data.get(SEARCH_VAR) or "" try: self.page_num = int(request.GET.get(PAGE_VAR, 1)) except ValueError: self.page_num = 1 self.show_all = ALL_VAR in request.GET self.is_popup = IS_POPUP_VAR in request.GET to_field = request.GET.get(TO_FIELD_VAR) if to_field and not model_admin.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) self.to_field = to_field self.params = dict(request.GET.items()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] if self.is_popup: self.list_editable = () else: self.list_editable = list_editable self.queryset = self.get_queryset(request) self.get_results(request) if self.is_popup: title = gettext("Select %s") elif self.model_admin.has_change_permission(request): title = gettext("Select %s to change") else: title = gettext("Select %s to view") self.title = title % self.opts.verbose_name self.pk_attname = self.lookup_opts.pk.attname def __repr__(self): return "<%s: model=%s model_admin=%s>" % ( self.__class__.__qualname__, self.model.__qualname__, self.model_admin.__class__.__qualname__, ) def get_filters_params(self, params=None): """ Return all params except IGNORED_PARAMS. """ params = params or self.params lookup_params = params.copy() # a dictionary of the query string # Remove all the parameters that are globally and systematically # ignored. for ignored in IGNORED_PARAMS: if ignored in lookup_params: del lookup_params[ignored] return lookup_params def get_filters(self, request): lookup_params = self.get_filters_params() may_have_duplicates = False has_active_filters = False for key, value in lookup_params.items(): if not self.model_admin.lookup_allowed(key, value): raise DisallowedModelAdminLookup("Filtering by %s not allowed" % key) filter_specs = [] for list_filter in self.list_filter: lookup_params_count = len(lookup_params) if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(request, lookup_params, self.model, self.model_admin) else: field_path = None if isinstance(list_filter, (tuple, list)): # This is a custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # This is simply a field name, so use the default # FieldListFilter class that has been registered for the # type of the given field. field, field_list_filter_class = list_filter, FieldListFilter.create if not isinstance(field, Field): field_path = field field = get_fields_from_path(self.model, field_path)[-1] spec = field_list_filter_class( field, request, lookup_params, self.model, self.model_admin, field_path=field_path, ) # field_list_filter_class removes any lookup_params it # processes. If that happened, check if duplicates should be # removed. if lookup_params_count > len(lookup_params): may_have_duplicates |= lookup_spawns_duplicates( self.lookup_opts, field_path, ) if spec and spec.has_output(): filter_specs.append(spec) if lookup_params_count > len(lookup_params): has_active_filters = True if self.date_hierarchy: # Create bounded lookup parameters so that the query is more # efficient. year = lookup_params.pop("%s__year" % self.date_hierarchy, None) if year is not None: month = lookup_params.pop("%s__month" % self.date_hierarchy, None) day = lookup_params.pop("%s__day" % self.date_hierarchy, None) try: from_date = datetime( int(year), int(month if month is not None else 1), int(day if day is not None else 1), ) except ValueError as e: raise IncorrectLookupParameters(e) from e if day: to_date = from_date + timedelta(days=1) elif month: # In this branch, from_date will always be the first of a # month, so advancing 32 days gives the next month. to_date = (from_date + timedelta(days=32)).replace(day=1) else: to_date = from_date.replace(year=from_date.year + 1) if settings.USE_TZ: from_date = make_aware(from_date) to_date = make_aware(to_date) lookup_params.update( { "%s__gte" % self.date_hierarchy: from_date, "%s__lt" % self.date_hierarchy: to_date, } ) # At this point, all the parameters used by the various ListFilters # have been removed from lookup_params, which now only contains other # parameters passed via the query string. We now loop through the # remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them spawns duplicates. If # the lookup parameters aren't real fields, then bail out. try: for key, value in lookup_params.items(): lookup_params[key] = prepare_lookup_value(key, value) may_have_duplicates |= lookup_spawns_duplicates(self.lookup_opts, key) return ( filter_specs, bool(filter_specs), lookup_params, may_have_duplicates, has_active_filters, ) except FieldDoesNotExist as e: raise IncorrectLookupParameters(e) from e def get_query_string(self, new_params=None, remove=None): if new_params is None: new_params = {} if remove is None: remove = [] p = self.params.copy() for r in remove: for k in list(p): if k.startswith(r): del p[k] for k, v in new_params.items(): if v is None: if k in p: del p[k] else: p[k] = v return "?%s" % urlencode(sorted(p.items())) def get_results(self, request): paginator = self.model_admin.get_paginator( request, self.queryset, self.list_per_page ) # Get the number of objects, with admin filters applied. result_count = paginator.count # Get the total number of objects, with no admin filters applied. if self.model_admin.show_full_result_count: full_result_count = self.root_queryset.count() else: full_result_count = None can_show_all = result_count <= self.list_max_show_all multi_page = result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = self.queryset._clone() else: try: result_list = paginator.page(self.page_num).object_list except InvalidPage: raise IncorrectLookupParameters self.result_count = result_count self.show_full_result_count = self.model_admin.show_full_result_count # Admin actions are shown if there is at least one entry # or if entries are not counted because show_full_result_count is disabled self.show_admin_actions = not self.show_full_result_count or bool( full_result_count ) self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator def _get_default_ordering(self): ordering = [] if self.model_admin.ordering: ordering = self.model_admin.ordering elif self.lookup_opts.ordering: ordering = self.lookup_opts.ordering return ordering def get_ordering_field(self, field_name): """ Return the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Return None if no proper model field name can be matched. """ try: field = self.lookup_opts.get_field(field_name) return field.name except FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self.model_admin, field_name): attr = getattr(self.model_admin, field_name) else: attr = getattr(self.model, field_name) if isinstance(attr, property) and hasattr(attr, "fget"): attr = attr.fget return getattr(attr, "admin_order_field", None) def get_ordering(self, request, queryset): """ Return the list of ordering fields for the change list. First check the get_ordering() method in model admin, then check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by calling _get_deterministic_ordering() with the constructed ordering. """ params = self.params ordering = list( self.model_admin.get_ordering(request) or self._get_default_ordering() ) if ORDER_VAR in params: # Clear ordering and used params ordering = [] order_params = params[ORDER_VAR].split(".") for p in order_params: try: none, pfx, idx = p.rpartition("-") field_name = self.list_display[int(idx)] order_field = self.get_ordering_field(field_name) if not order_field: continue # No 'admin_order_field', skip it if isinstance(order_field, OrderBy): if pfx == "-": order_field = order_field.copy() order_field.reverse_ordering() ordering.append(order_field) elif hasattr(order_field, "resolve_expression"): # order_field is an expression. ordering.append( order_field.desc() if pfx == "-" else order_field.asc() ) # reverse order if order_field has already "-" as prefix elif order_field.startswith("-") and pfx == "-": ordering.append(order_field[1:]) else: ordering.append(pfx + order_field) except (IndexError, ValueError): continue # Invalid ordering specified, skip it. # Add the given query's ordering fields, if any. ordering.extend(queryset.query.order_by) return self._get_deterministic_ordering(ordering) def _get_deterministic_ordering(self, ordering): """ Ensure a deterministic order across all database backends. Search for a single field or unique together set of fields providing a total ordering. If these are missing, augment the ordering with a descendant primary key. """ ordering = list(ordering) ordering_fields = set() total_ordering_fields = {"pk"} | { field.attname for field in self.lookup_opts.fields if field.unique and not field.null } for part in ordering: # Search for single field providing a total ordering. field_name = None if isinstance(part, str): field_name = part.lstrip("-") elif isinstance(part, F): field_name = part.name elif isinstance(part, OrderBy) and isinstance(part.expression, F): field_name = part.expression.name if field_name: # Normalize attname references by using get_field(). try: field = self.lookup_opts.get_field(field_name) except FieldDoesNotExist: # Could be "?" for random ordering or a related field # lookup. Skip this part of introspection for now. continue # Ordering by a related field name orders by the referenced # model's ordering. Skip this part of introspection for now. if field.remote_field and field_name == field.name: continue if field.attname in total_ordering_fields: break ordering_fields.add(field.attname) else: # No single total ordering field, try unique_together and total # unique constraints. constraint_field_names = ( *self.lookup_opts.unique_together, *( constraint.fields for constraint in self.lookup_opts.total_unique_constraints ), ) for field_names in constraint_field_names: # Normalize attname references by using get_field(). fields = [ self.lookup_opts.get_field(field_name) for field_name in field_names ] # Composite unique constraints containing a nullable column # cannot ensure total ordering. if any(field.null for field in fields): continue if ordering_fields.issuperset(field.attname for field in fields): break else: # If no set of unique fields is present in the ordering, rely # on the primary key to provide total ordering. ordering.append("-pk") return ordering def get_ordering_field_columns(self): """ Return a dictionary of ordering field column numbers and asc/desc. """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = {} if ORDER_VAR not in self.params: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if isinstance(field, (Combinable, OrderBy)): if not isinstance(field, OrderBy): field = field.asc() if isinstance(field.expression, F): order_type = "desc" if field.descending else "asc" field = field.expression.name else: continue elif field.startswith("-"): field = field[1:] order_type = "desc" else: order_type = "asc" for index, attr in enumerate(self.list_display): if self.get_ordering_field(attr) == field: ordering_fields[index] = order_type break else: for p in self.params[ORDER_VAR].split("."): none, pfx, idx = p.rpartition("-") try: idx = int(idx) except ValueError: continue # skip it ordering_fields[idx] = "desc" if pfx == "-" else "asc" return ordering_fields def get_queryset(self, request): # First, we collect all the declared list filters. ( self.filter_specs, self.has_filters, remaining_lookup_params, filters_may_have_duplicates, self.has_active_filters, ) = self.get_filters(request) # Then, we let every list filter modify the queryset to its liking. qs = self.root_queryset for filter_spec in self.filter_specs: new_qs = filter_spec.queryset(request, qs) if new_qs is not None: qs = new_qs try: # Finally, we apply the remaining lookup parameters from the query # string (i.e. those that haven't already been processed by the # filters). qs = qs.filter(**remaining_lookup_params) except (SuspiciousOperation, ImproperlyConfigured): # Allow certain types of errors to be re-raised as-is so that the # caller can treat them in a special way. raise except Exception as e: # Every other error is caught with a naked except, because we don't # have any other way of validating lookup parameters. They might be # invalid if the keyword arguments are incorrect, or if the values # are not in the correct type, so we might get FieldError, # ValueError, ValidationError, or ?. raise IncorrectLookupParameters(e) # Apply search results qs, search_may_have_duplicates = self.model_admin.get_search_results( request, qs, self.query, ) # Set query string for clearing all filters. self.clear_all_filters_qs = self.get_query_string( new_params=remaining_lookup_params, remove=self.get_filters_params(), ) # Remove duplicates from results, if necessary if filters_may_have_duplicates | search_may_have_duplicates: qs = qs.filter(pk=OuterRef("pk")) qs = self.root_queryset.filter(Exists(qs)) # Set ordering. ordering = self.get_ordering(request, qs) qs = qs.order_by(*ordering) if not qs.query.select_related: qs = self.apply_select_related(qs) return qs def apply_select_related(self, qs): if self.list_select_related is True: return qs.select_related() if self.list_select_related is False: if self.has_related_field_in_list_display(): return qs.select_related() if self.list_select_related: return qs.select_related(*self.list_select_related) return qs def has_related_field_in_list_display(self): for field_name in self.list_display: try: field = self.lookup_opts.get_field(field_name) except FieldDoesNotExist: pass else: if isinstance(field.remote_field, ManyToOneRel): # <FK>_id field names don't require a join. if field_name != field.get_attname(): return True return False def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse( "admin:%s_%s_change" % (self.opts.app_label, self.opts.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name, )
c83a7993ecc808fd7ac7e11763fe27b4f5f71dec13cdc3c32d059095a1db604b
from django.apps import apps from django.core.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, request, *args, **kwargs): """ Return a JsonResponse with search results as defined in serialize_result(), by default: { results: [{id: "123" text: "foo"}], pagination: {more: true} } """ ( self.term, self.model_admin, self.source_field, to_field_name, ) = self.process_request(request) if not self.has_perm(request): raise PermissionDenied self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse( { "results": [ self.serialize_result(obj, to_field_name) for obj in context["object_list"] ], "pagination": {"more": context["page_obj"].has_next()}, } ) def serialize_result(self, obj, to_field_name): """ Convert the provided model object to a dictionary that is added to the results list. """ return {"id": str(getattr(obj, to_field_name)), "text": str(obj)} def get_paginator(self, *args, **kwargs): """Use the ModelAdmin's paginator.""" return self.model_admin.get_paginator(self.request, *args, **kwargs) def get_queryset(self): """Return queryset based on ModelAdmin.get_search_results().""" qs = self.model_admin.get_queryset(self.request) qs = qs.complex_filter(self.source_field.get_limit_choices_to()) qs, search_use_distinct = self.model_admin.get_search_results( self.request, qs, self.term ) if search_use_distinct: qs = qs.distinct() return qs def process_request(self, request): """ Validate request integrity, extract and return request parameters. Since the subsequent view permission check requires the target model admin, which is determined here, raise PermissionDenied if the requested app, model or field are malformed. Raise Http404 if the target model admin is not configured properly with search_fields. """ term = request.GET.get("term", "") try: app_label = request.GET["app_label"] model_name = request.GET["model_name"] field_name = request.GET["field_name"] except KeyError as e: raise PermissionDenied from e # Retrieve objects from parameters. try: source_model = apps.get_model(app_label, model_name) except LookupError as e: raise PermissionDenied from e try: source_field = source_model._meta.get_field(field_name) except FieldDoesNotExist as e: raise PermissionDenied from e try: remote_model = source_field.remote_field.model except AttributeError as e: raise PermissionDenied from e try: model_admin = self.admin_site._registry[remote_model] except KeyError as e: raise PermissionDenied from e # Validate suitability of objects. if not model_admin.get_search_fields(request): raise Http404( "%s must have search_fields for the autocomplete_view." % type(model_admin).__qualname__ ) to_field_name = getattr( source_field.remote_field, "field_name", remote_model._meta.pk.attname ) to_field_name = remote_model._meta.get_field(to_field_name).attname if not model_admin.to_field_allowed(request, to_field_name): raise PermissionDenied return term, model_admin, source_field, to_field_name def has_perm(self, request, obj=None): """Check if user has permission to access the related model.""" return self.model_admin.has_view_permission(request, obj=obj)
4b223f0f08793afb5d3f40da3cd7a1a6f8e06649e5266aee71c939b45dde5076
from inspect import getfullargspec from django.template.library import InclusionNode, parse_bits class InclusionAdminNode(InclusionNode): """ Template tag that allows its template to be overridden per model, per app, or globally. """ def __init__(self, parser, token, func, template_name, takes_context=True): self.template_name = template_name params, varargs, varkw, defaults, kwonly, kwonly_defaults, _ = getfullargspec( func ) bits = token.split_contents() args, kwargs = parse_bits( parser, bits[1:], params, varargs, varkw, defaults, kwonly, kwonly_defaults, takes_context, bits[0], ) super().__init__(func, takes_context, args, kwargs, filename=None) def render(self, context): opts = context["opts"] app_label = opts.app_label.lower() object_name = opts.object_name.lower() # Load template for this render call. (Setting self.filename isn't # thread-safe.) context.render_context[self] = context.template.engine.select_template( [ "admin/%s/%s/%s" % (app_label, object_name, self.template_name), "admin/%s/%s" % (app_label, self.template_name), "admin/%s" % self.template_name, ] ) return super().render(context)
dcc4f958ab1a73c4b91f527692433e81ab1873d7da17dd5bf794c4b77cbc13e9
from django import template from django.contrib.admin.models import LogEntry register = template.Library() class AdminLogNode(template.Node): def __init__(self, limit, varname, user): self.limit, self.varname, self.user = limit, varname, user def __repr__(self): return "<GetAdminLog Node>" def render(self, context): if self.user is None: entries = LogEntry.objects.all() else: user_id = self.user if not user_id.isdigit(): user_id = context[self.user].pk entries = LogEntry.objects.filter(user__pk=user_id) context[self.varname] = entries.select_related("content_type", "user")[ : 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:: {% get_admin_log [limit] as [varname] for_user [context_var_with_user_obj] %} 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 %} Note that ``context_var_containing_user_obj`` can be a hard-coded integer (user ID) or the name of a template context variable containing the user object whose ID you want. """ tokens = token.contents.split() if len(tokens) < 4: raise template.TemplateSyntaxError( "'get_admin_log' statements require two arguments" ) if not tokens[1].isdigit(): raise template.TemplateSyntaxError( "First argument to 'get_admin_log' must be an integer" ) if tokens[2] != "as": raise template.TemplateSyntaxError( "Second argument to 'get_admin_log' must be 'as'" ) if len(tokens) > 4: if tokens[4] != "for_user": raise template.TemplateSyntaxError( "Fourth argument to 'get_admin_log' must be 'for_user'" ) return AdminLogNode( limit=tokens[1], varname=tokens[3], user=(tokens[5] if len(tokens) > 5 else None), )
a0a9ea66042b5253087920de10a28556d2f2b93cecce916031f3d35753361a09
import datetime from django.conf import settings from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.utils import ( display_for_field, display_for_value, get_fields_from_path, label_for_field, lookup_field, ) from django.contrib.admin.views.main import ( ALL_VAR, IS_POPUP_VAR, ORDER_VAR, PAGE_VAR, SEARCH_VAR, ) from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.template import Library from django.template.loader import get_template from django.templatetags.static import static from django.urls import NoReverseMatch from django.utils import formats, timezone from django.utils.html import format_html from django.utils.safestring import 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.paginator.ELLIPSIS: return format_html("{} ", cl.paginator.ELLIPSIS) elif i == cl.page_num: return format_html('<span class="this-page">{}</span> ', i) else: return format_html( '<a href="{}"{}>{}</a> ', cl.get_query_string({PAGE_VAR: i}), mark_safe(' class="end"' if i == cl.paginator.num_pages else ""), i, ) def pagination(cl): """ Generate 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 [] ) need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page return { "cl": cl, "pagination_required": pagination_required, "show_all_url": need_show_all_link and cl.get_query_string({ALL_VAR: ""}), "page_range": page_range, "ALL_VAR": ALL_VAR, "1": 1, } @register.tag(name="pagination") def pagination_tag(parser, token): return InclusionAdminNode( parser, token, func=pagination, template_name="pagination.html", takes_context=False, ) def result_headers(cl): """ Generate the list column headers. """ ordering_field_columns = cl.get_ordering_field_columns() for i, field_name in enumerate(cl.list_display): text, attr = label_for_field( field_name, cl.model, model_admin=cl.model_admin, return_attr=True ) is_field_sortable = cl.sortable_by is None or field_name in cl.sortable_by if attr: field_name = _coerce_field_name(field_name, i) # Potentially not sortable # if the field is the action checkbox: no sorting and special class if field_name == "action_checkbox": yield { "text": text, "class_attrib": mark_safe(' class="action-checkbox-column"'), "sortable": False, } continue admin_order_field = getattr(attr, "admin_order_field", None) # Set ordering for attr that is a property, if defined. if isinstance(attr, property) and hasattr(attr, "fget"): admin_order_field = getattr(attr.fget, "admin_order_field", None) if not admin_order_field: is_field_sortable = False if not is_field_sortable: # Not sortable yield { "text": text, "class_attrib": format_html(' class="column-{}"', field_name), "sortable": False, } continue # OK, it is sortable if we got this far th_classes = ["sortable", "column-{}".format(field_name)] order_type = "" new_order_type = "asc" sort_priority = 0 # Is it currently being sorted on? is_sorted = i in ordering_field_columns if is_sorted: order_type = ordering_field_columns.get(i).lower() sort_priority = list(ordering_field_columns).index(i) + 1 th_classes.append("sorted %sending" % order_type) new_order_type = {"asc": "desc", "desc": "asc"}[order_type] # build new ordering param o_list_primary = [] # URL for making this field the primary sort o_list_remove = [] # URL for removing this field from sort o_list_toggle = [] # URL for toggling order type for this field def make_qs_param(t, n): return ("-" if t == "desc" else "") + str(n) for j, ot in ordering_field_columns.items(): if j == i: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front o_list_primary.insert(0, param) o_list_toggle.append(param) # o_list_remove - omit else: param = make_qs_param(ot, j) o_list_primary.append(param) o_list_toggle.append(param) o_list_remove.append(param) if i not in ordering_field_columns: o_list_primary.insert(0, make_qs_param(new_order_type, i)) yield { "text": text, "sortable": True, "sorted": is_sorted, "ascending": order_type == "asc", "sort_priority": sort_priority, "url_primary": cl.get_query_string({ORDER_VAR: ".".join(o_list_primary)}), "url_remove": cl.get_query_string({ORDER_VAR: ".".join(o_list_remove)}), "url_toggle": cl.get_query_string({ORDER_VAR: ".".join(o_list_toggle)}), "class_attrib": format_html(' class="{}"', " ".join(th_classes)) if th_classes else "", } def _boolean_icon(field_val): icon_url = static( "admin/img/icon-%s.svg" % {True: "yes", False: "no", None: "unknown"}[field_val] ) return format_html('<img src="{}" alt="{}">', icon_url, field_val) def _coerce_field_name(field_name, field_index): """ Coerce a field_name (which may be a callable) to a string. """ if callable(field_name): if field_name.__name__ == "<lambda>": return "lambda" + str(field_index) else: return field_name.__name__ return field_name def items_for_result(cl, result, form): """ Generate the actual list of data. """ def link_in_col(is_first, field_name, cl): if cl.list_display_links is None: return False if is_first and not cl.list_display_links: return True return field_name in cl.list_display_links first = True pk = cl.lookup_opts.pk.attname for field_index, field_name in enumerate(cl.list_display): empty_value_display = cl.model_admin.get_empty_value_display() row_classes = ["field-%s" % _coerce_field_name(field_name, field_index)] try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except ObjectDoesNotExist: result_repr = empty_value_display else: empty_value_display = getattr( attr, "empty_value_display", empty_value_display ) if f is None or f.auto_created: if field_name == "action_checkbox": row_classes = ["action-checkbox"] boolean = getattr(attr, "boolean", False) result_repr = display_for_value(value, empty_value_display, boolean) if isinstance(value, (datetime.date, datetime.time)): row_classes.append("nowrap") else: if isinstance(f.remote_field, models.ManyToOneRel): field_val = getattr(result, f.name) if field_val is None: result_repr = empty_value_display else: result_repr = field_val else: result_repr = display_for_field(value, f, empty_value_display) if isinstance( f, (models.DateField, models.TimeField, models.ForeignKey) ): row_classes.append("nowrap") row_class = mark_safe(' class="%s"' % " ".join(row_classes)) # If list_display_links not defined, add the link tag to the first field if link_in_col(first, field_name, cl): table_tag = "th" if first else "td" first = False # Display link to the result's change_view if the url exists, else # display just the result's representation. try: url = cl.url_for_result(result) except NoReverseMatch: link_or_text = result_repr else: url = add_preserved_filters( {"preserved_filters": cl.preserved_filters, "opts": cl.opts}, url ) # Convert the pk to something that can be used in JavaScript. # Problem cases are non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) link_or_text = format_html( '<a href="{}"{}>{}</a>', url, format_html(' data-popup-opener="{}"', value) if cl.is_popup else "", result_repr, ) yield format_html( "<{}{}>{}</{}>", table_tag, row_class, link_or_text, table_tag ) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if ( form and field_name in form.fields and not ( field_name == cl.model._meta.pk.name and form[cl.model._meta.pk.name].is_hidden ) ): bf = form[field_name] result_repr = mark_safe(str(bf.errors) + str(bf)) yield format_html("<td{}>{}</td>", row_class, result_repr) if form and not form[cl.model._meta.pk.name].is_hidden: yield format_html("<td>{}</td>", form[cl.model._meta.pk.name]) class ResultList(list): """ Wrapper class used to return items in a list_editable changelist, annotated with the form object for error reporting purposes. Needed to maintain backwards compatibility with existing admin templates. """ def __init__(self, form, *items): self.form = form super().__init__(*items) def results(cl): if cl.formset: for res, form in zip(cl.result_list, cl.formset.forms): yield ResultList(form, items_for_result(cl, res, form)) else: for res in cl.result_list: yield ResultList(None, items_for_result(cl, res, None)) def result_hidden_fields(cl): if cl.formset: for res, form in zip(cl.result_list, cl.formset.forms): if form[cl.model._meta.pk.name].is_hidden: yield mark_safe(form[cl.model._meta.pk.name]) def result_list(cl): """ Display the headers and data list together. """ headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h["sortable"] and h["sorted"]: num_sorted_fields += 1 return { "cl": cl, "result_hidden_fields": list(result_hidden_fields(cl)), "result_headers": headers, "num_sorted_fields": num_sorted_fields, "results": list(results(cl)), } @register.tag(name="result_list") def result_list_tag(parser, token): return InclusionAdminNode( parser, token, func=result_list, template_name="change_list_results.html", takes_context=False, ) def date_hierarchy(cl): """ Display the date hierarchy for date drill-down functionality. """ if cl.date_hierarchy: field_name = cl.date_hierarchy field = get_fields_from_path(cl.model, field_name)[-1] if isinstance(field, models.DateTimeField): dates_or_datetimes = "datetimes" qs_kwargs = {"is_dst": True} if settings.USE_DEPRECATED_PYTZ else {} else: dates_or_datetimes = "dates" qs_kwargs = {} year_field = "%s__year" % field_name month_field = "%s__month" % field_name day_field = "%s__day" % field_name field_generic = "%s__" % field_name year_lookup = cl.params.get(year_field) month_lookup = cl.params.get(month_field) day_lookup = cl.params.get(day_field) def link(filters): return cl.get_query_string(filters, [field_generic]) if not (year_lookup or month_lookup or day_lookup): # select appropriate start level date_range = cl.queryset.aggregate( first=models.Min(field_name), last=models.Max(field_name) ) if date_range["first"] and date_range["last"]: if dates_or_datetimes == "datetimes": date_range = { k: timezone.localtime(v) if timezone.is_aware(v) else v for k, v in date_range.items() } if date_range["first"].year == date_range["last"].year: year_lookup = date_range["first"].year if date_range["first"].month == date_range["last"].month: month_lookup = date_range["first"].month if year_lookup and month_lookup and day_lookup: day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup)) return { "show": True, "back": { "link": link({year_field: year_lookup, month_field: month_lookup}), "title": capfirst(formats.date_format(day, "YEAR_MONTH_FORMAT")), }, "choices": [ {"title": capfirst(formats.date_format(day, "MONTH_DAY_FORMAT"))} ], } elif year_lookup and month_lookup: days = getattr(cl.queryset, dates_or_datetimes)( field_name, "day", **qs_kwargs ) return { "show": True, "back": { "link": link({year_field: year_lookup}), "title": str(year_lookup), }, "choices": [ { "link": link( { year_field: year_lookup, month_field: month_lookup, day_field: day.day, } ), "title": capfirst(formats.date_format(day, "MONTH_DAY_FORMAT")), } for day in days ], } elif year_lookup: months = getattr(cl.queryset, dates_or_datetimes)( field_name, "month", **qs_kwargs ) return { "show": True, "back": {"link": link({}), "title": _("All dates")}, "choices": [ { "link": link( {year_field: year_lookup, month_field: month.month} ), "title": capfirst( formats.date_format(month, "YEAR_MONTH_FORMAT") ), } for month in months ], } else: years = getattr(cl.queryset, dates_or_datetimes)( field_name, "year", **qs_kwargs ) return { "show": True, "back": None, "choices": [ { "link": link({year_field: str(year.year)}), "title": str(year.year), } for year in years ], } @register.tag(name="date_hierarchy") def date_hierarchy_tag(parser, token): return InclusionAdminNode( parser, token, func=date_hierarchy, template_name="date_hierarchy.html", takes_context=False, ) def search_form(cl): """ Display a search form for searching the list. """ return { "cl": cl, "show_result_count": cl.result_count != cl.full_result_count, "search_var": SEARCH_VAR, "is_popup_var": IS_POPUP_VAR, } @register.tag(name="search_form") def search_form_tag(parser, token): return InclusionAdminNode( parser, token, func=search_form, template_name="search_form.html", takes_context=False, ) @register.simple_tag def admin_list_filter(cl, spec): tpl = get_template(spec.template) return tpl.render( { "title": spec.title, "choices": list(spec.choices(cl)), "spec": spec, } ) def admin_actions(context): """ Track the number of times the action field has been rendered on the page, so we know which value to use. """ context["action_index"] = context.get("action_index", -1) + 1 return context @register.tag(name="admin_actions") def admin_actions_tag(parser, token): return InclusionAdminNode( parser, token, func=admin_actions, template_name="actions.html" ) @register.tag(name="change_list_object_tools") def change_list_object_tools_tag(parser, token): """Display the row of change list object tools.""" return InclusionAdminNode( parser, token, func=lambda context: context, template_name="change_list_object_tools.html", )
19a0ce6f5d30d243c83d836f97011a008aa12af2caa47403a98055a4e4215d05
from urllib.parse import parse_qsl, unquote, urlparse, urlunparse 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, value.model_name, arg) @register.filter def admin_urlquote(value): return quote(value) @register.simple_tag(takes_context=True) def add_preserved_filters(context, url, popup=False, to_field=None): opts = context.get("opts") preserved_filters = context.get("preserved_filters") parsed_url = list(urlparse(url)) parsed_qs = dict(parse_qsl(parsed_url[4])) merged_qs = {} if opts and preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters)) match_url = "/%s" % unquote(url).partition(get_script_prefix())[2] try: match = resolve(match_url) except Resolver404: pass else: current_url = "%s:%s" % (match.app_name, match.url_name) changelist_url = "admin:%s_%s_changelist" % ( opts.app_label, opts.model_name, ) if ( changelist_url == current_url and "_changelist_filters" in preserved_filters ): preserved_filters = dict( parse_qsl(preserved_filters["_changelist_filters"]) ) merged_qs.update(preserved_filters) if popup: from django.contrib.admin.options import IS_POPUP_VAR merged_qs[IS_POPUP_VAR] = 1 if to_field: from django.contrib.admin.options import TO_FIELD_VAR merged_qs[TO_FIELD_VAR] = to_field merged_qs.update(parsed_qs) parsed_url[4] = urlencode(merged_qs) return urlunparse(parsed_url)
ea18ba156e4c8ac3455b93fd1287ecbbdd5ad42238624c7215f7b5c216a17e05
import json from django import template from django.template.context import Context from .base import InclusionAdminNode register = template.Library() def prepopulated_fields_js(context): """ 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 context: for inline_admin_formset in context["inline_admin_formsets"]: for inline_admin_form in inline_admin_formset: if inline_admin_form.original is None: prepopulated_fields.extend(inline_admin_form.prepopulated_fields) prepopulated_fields_json = [] for field in prepopulated_fields: prepopulated_fields_json.append( { "id": "#%s" % field["field"].auto_id, "name": field["field"].name, "dependency_ids": [ "#%s" % dependency.auto_id for dependency in field["dependencies"] ], "dependency_list": [ dependency.name for dependency in field["dependencies"] ], "maxLength": field["field"].field.max_length or 50, "allowUnicode": getattr(field["field"].field, "allow_unicode", False), } ) context.update( { "prepopulated_fields": prepopulated_fields, "prepopulated_fields_json": json.dumps(prepopulated_fields_json), } ) return context @register.tag(name="prepopulated_fields_js") def prepopulated_fields_js_tag(parser, token): return InclusionAdminNode( parser, token, func=prepopulated_fields_js, template_name="prepopulated_fields_js.html", ) def submit_row(context): """ Display the row of buttons for delete and save. """ add = context["add"] change = context["change"] is_popup = context["is_popup"] save_as = context["save_as"] show_save = context.get("show_save", True) show_save_and_add_another = context.get("show_save_and_add_another", True) show_save_and_continue = context.get("show_save_and_continue", True) has_add_permission = context["has_add_permission"] has_change_permission = context["has_change_permission"] has_view_permission = context["has_view_permission"] has_editable_inline_admin_formsets = context["has_editable_inline_admin_formsets"] can_save = ( (has_change_permission and change) or (has_add_permission and add) or has_editable_inline_admin_formsets ) can_save_and_add_another = ( has_add_permission and not is_popup and (not save_as or add) and can_save and show_save_and_add_another ) can_save_and_continue = ( not is_popup and can_save and has_view_permission and show_save_and_continue ) can_change = has_change_permission or has_editable_inline_admin_formsets ctx = Context(context) ctx.update( { "can_change": can_change, "show_delete_link": ( not is_popup and context["has_delete_permission"] and change and context.get("show_delete", True) ), "show_save_as_new": not is_popup and has_change_permission and change and save_as, "show_save_and_add_another": can_save_and_add_another, "show_save_and_continue": can_save_and_continue, "show_save": show_save and can_save, "show_close": not (show_save and can_save), } ) return ctx @register.tag(name="submit_row") def submit_row_tag(parser, token): return InclusionAdminNode( parser, token, func=submit_row, template_name="submit_line.html" ) @register.tag(name="change_form_object_tools") def change_form_object_tools_tag(parser, token): """Display the row of change form object tools.""" return InclusionAdminNode( parser, token, func=lambda context: context, template_name="change_form_object_tools.html", ) @register.filter def cell_count(inline_admin_form): """Return the number of cells used in a tabular inline.""" count = 1 # Hidden cell with hidden 'id' field for fieldset in inline_admin_form: # Count all visible fields. for line in fieldset: for field in line: if not field.field.is_hidden: count += 1 if inline_admin_form.formset.can_delete: # Delete checkbox count += 1 return count
a275dea84c6562ba6cb381426833fe428b11ce757567afb71fd0963cb8f6436a
import re from datetime import date, datetime from decimal import Decimal from django import template from django.template import defaultfilters from django.utils.formats import number_format from django.utils.safestring import mark_safe from django.utils.timezone import is_aware, utc from django.utils.translation import gettext as _ from django.utils.translation import ( gettext_lazy, 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 integer. """ try: value = int(value) except (TypeError, ValueError): return value if value % 100 in (11, 12, 13): # Translators: Ordinal format for 11 (11th), 12 (12th), and 13 (13th). value = 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 value ends with 1, e.g. 81st, except 11. pgettext("ordinal 1", "{}st"), # Translators: Ordinal format when value ends with 2, e.g. 82nd, except 12. pgettext("ordinal 2", "{}nd"), # Translators: Ordinal format when value ends with 3, e.g. 83rd, except 13. pgettext("ordinal 3", "{}rd"), # Translators: Ordinal format when value ends with 4, e.g. 84th. pgettext("ordinal 4", "{}th"), # Translators: Ordinal format when value ends with 5, e.g. 85th. pgettext("ordinal 5", "{}th"), # Translators: Ordinal format when value ends with 6, e.g. 86th. pgettext("ordinal 6", "{}th"), # Translators: Ordinal format when value ends with 7, e.g. 87th. pgettext("ordinal 7", "{}th"), # Translators: Ordinal format when value ends with 8, e.g. 88th. pgettext("ordinal 8", "{}th"), # Translators: Ordinal format when value ends with 9, e.g. 89th. pgettext("ordinal 9", "{}th"), ) value = templates[value % 10].format(value) # Mark value safe so i18n does not break with <sup> or <sub> see #19988 return mark_safe(value) @register.filter(is_safe=True) def intcomma(value, use_l10n=True): """ Convert an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ if use_l10n: try: if not isinstance(value, (float, Decimal)): value = int(value) except (TypeError, ValueError): return intcomma(value, False) else: return number_format(value, use_l10n=True, force_grouping=True) orig = str(value) new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1>,\g<2>", orig) if orig == new: return new else: return intcomma(new, use_l10n) # A tuple of standard large number to their converters intword_converters = ( (6, lambda number: ngettext("%(value)s million", "%(value)s million", number)), (9, lambda number: ngettext("%(value)s billion", "%(value)s billion", number)), (12, lambda number: ngettext("%(value)s trillion", "%(value)s trillion", number)), ( 15, lambda number: ngettext( "%(value)s quadrillion", "%(value)s quadrillion", number ), ), ( 18, lambda number: ngettext( "%(value)s quintillion", "%(value)s quintillion", number ), ), ( 21, lambda number: ngettext("%(value)s sextillion", "%(value)s sextillion", number), ), ( 24, lambda number: ngettext("%(value)s septillion", "%(value)s septillion", number), ), (27, lambda number: ngettext("%(value)s octillion", "%(value)s octillion", number)), (30, lambda number: ngettext("%(value)s nonillion", "%(value)s nonillion", number)), (33, lambda number: ngettext("%(value)s decillion", "%(value)s decillion", number)), (100, lambda number: ngettext("%(value)s googol", "%(value)s googol", number)), ) @register.filter(is_safe=False) def intword(value): """ Convert a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. """ try: value = int(value) except (TypeError, ValueError): return value abs_value = abs(value) if abs_value < 1000000: return value for exponent, converter in intword_converters: large_number = 10**exponent if abs_value < large_number * 1000: new_value = value / large_number rounded_value = round_away_from_one(new_value) return converter(abs(rounded_value)) % { "value": defaultfilters.floatformat(new_value, 1), } return value @register.filter(is_safe=True) def apnumber(value): """ For numbers 1-9, return the number spelled out. Otherwise, return the number. This follows Associated Press style. """ try: value = int(value) except (TypeError, ValueError): return value if not 0 < value < 10: return value return ( _("one"), _("two"), _("three"), _("four"), _("five"), _("six"), _("seven"), _("eight"), _("nine"), )[value - 1] # Perform the comparison in the default time zone when USE_TZ = True # (unless a specific time zone has been applied with the |timezone filter). @register.filter(expects_localtime=True) def naturalday(value, arg=None): """ For date values that are tomorrow, today or yesterday compared to present day return representing string. Otherwise, return a string formatted according to settings.DATE_FORMAT. """ tzinfo = getattr(value, "tzinfo", None) try: value = date(value.year, value.month, value.day) except AttributeError: # Passed value wasn't a date object return value today = datetime.now(tzinfo).date() delta = value - today if delta.days == 0: return _("today") elif delta.days == 1: return _("tomorrow") elif delta.days == -1: return _("yesterday") return defaultfilters.date(value, arg) # This filter doesn't require expects_localtime=True because it deals properly # with both naive and aware datetimes. Therefore avoid the cost of conversion. @register.filter def naturaltime(value): """ For date and time values show how many seconds, minutes, or hours ago compared to current timestamp return representing string. """ return NaturalTimeFormatter.string_for(value) class NaturalTimeFormatter: time_strings = { # Translators: delta will contain a string like '2 months' or '1 month, 2 weeks' "past-day": gettext_lazy("%(delta)s ago"), # Translators: please keep a non-breaking space (U+00A0) between count # and time unit. "past-hour": ngettext_lazy("an hour ago", "%(count)s hours ago", "count"), # Translators: please keep a non-breaking space (U+00A0) between count # and time unit. "past-minute": ngettext_lazy("a minute ago", "%(count)s minutes ago", "count"), # Translators: please keep a non-breaking space (U+00A0) between count # and time unit. "past-second": ngettext_lazy("a second ago", "%(count)s seconds ago", "count"), "now": gettext_lazy("now"), # Translators: please keep a non-breaking space (U+00A0) between count # and time unit. "future-second": ngettext_lazy( "a second from now", "%(count)s seconds from now", "count" ), # Translators: please keep a non-breaking space (U+00A0) between count # and time unit. "future-minute": ngettext_lazy( "a minute from now", "%(count)s minutes from now", "count" ), # Translators: please keep a non-breaking space (U+00A0) between count # and time unit. "future-hour": ngettext_lazy( "an hour from now", "%(count)s hours from now", "count" ), # Translators: delta will contain a string like '2 months' or '1 month, 2 weeks' "future-day": gettext_lazy("%(delta)s from now"), } past_substrings = { # Translators: 'naturaltime-past' strings will be included in '%(delta)s ago' "year": npgettext_lazy( "naturaltime-past", "%(num)d year", "%(num)d years", "num" ), "month": npgettext_lazy( "naturaltime-past", "%(num)d month", "%(num)d months", "num" ), "week": npgettext_lazy( "naturaltime-past", "%(num)d week", "%(num)d weeks", "num" ), "day": npgettext_lazy("naturaltime-past", "%(num)d day", "%(num)d days", "num"), "hour": npgettext_lazy( "naturaltime-past", "%(num)d hour", "%(num)d hours", "num" ), "minute": npgettext_lazy( "naturaltime-past", "%(num)d minute", "%(num)d minutes", "num" ), } future_substrings = { # Translators: 'naturaltime-future' strings will be included in # '%(delta)s from now'. "year": npgettext_lazy( "naturaltime-future", "%(num)d year", "%(num)d years", "num" ), "month": npgettext_lazy( "naturaltime-future", "%(num)d month", "%(num)d months", "num" ), "week": npgettext_lazy( "naturaltime-future", "%(num)d week", "%(num)d weeks", "num" ), "day": npgettext_lazy( "naturaltime-future", "%(num)d day", "%(num)d days", "num" ), "hour": npgettext_lazy( "naturaltime-future", "%(num)d hour", "%(num)d hours", "num" ), "minute": npgettext_lazy( "naturaltime-future", "%(num)d minute", "%(num)d minutes", "num" ), } @classmethod def string_for(cls, value): if not isinstance(value, date): # datetime is a subclass of date return value now = datetime.now(utc if is_aware(value) else None) if value < now: delta = now - value if delta.days != 0: return cls.time_strings["past-day"] % { "delta": defaultfilters.timesince( value, now, time_strings=cls.past_substrings ), } elif delta.seconds == 0: return cls.time_strings["now"] elif delta.seconds < 60: return cls.time_strings["past-second"] % {"count": delta.seconds} elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings["past-minute"] % {"count": count} else: count = delta.seconds // 60 // 60 return cls.time_strings["past-hour"] % {"count": count} else: delta = value - now if delta.days != 0: return cls.time_strings["future-day"] % { "delta": defaultfilters.timeuntil( value, now, time_strings=cls.future_substrings ), } elif delta.seconds == 0: return cls.time_strings["now"] elif delta.seconds < 60: return cls.time_strings["future-second"] % {"count": delta.seconds} elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings["future-minute"] % {"count": count} else: count = delta.seconds // 60 // 60 return cls.time_strings["future-hour"] % {"count": count}
53fee8098f0b257e499f5c6532ffaa178110a14be54f495d07913fd2c26646dc
from django.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 add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "--nostatic", action="store_false", dest="use_static_handler", help="Tells Django to NOT automatically serve static files at STATIC_URL.", ) parser.add_argument( "--insecure", action="store_true", dest="insecure_serving", 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. Otherwise return the default handler. """ handler = super().get_handler(*args, **options) use_static_handler = options["use_static_handler"] insecure_serving = options["insecure_serving"] if use_static_handler and (settings.DEBUG or insecure_serving): return StaticFilesHandler(handler) return handler
65deb9760283f099579a80dbde283ab6f6646b880c57fe9e81b2dca112c9d520
import os from django.apps import apps from django.contrib.staticfiles.finders import get_finders from django.contrib.staticfiles.storage import staticfiles_storage from django.core.checks import Tags from django.core.files.storage import FileSystemStorage from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.utils.functional import 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().__init__(*args, **kwargs) self.copied_files = [] self.symlinked_files = [] self.unmodified_files = [] self.post_processed_files = [] self.storage = staticfiles_storage self.style = no_style() @cached_property def local(self): try: self.storage.path("") except NotImplementedError: return False return True def add_arguments(self, parser): parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Do NOT prompt the user for input of any kind.", ) parser.add_argument( "--no-post-process", action="store_false", dest="post_process", help="Do NOT post process collected files.", ) parser.add_argument( "-i", "--ignore", action="append", default=[], dest="ignore_patterns", metavar="PATTERN", help="Ignore files or directories matching this glob-style " "pattern. Use multiple times to ignore more.", ) parser.add_argument( "-n", "--dry-run", action="store_true", help="Do everything except modify the filesystem.", ) parser.add_argument( "-c", "--clear", action="store_true", help="Clear the existing files using the storage " "before trying to copy or link the original file.", ) parser.add_argument( "-l", "--link", action="store_true", help="Create a symbolic link to each file instead of copying.", ) parser.add_argument( "--no-default-ignore", action="store_false", dest="use_default_ignore_patterns", help=( "Don't ignore the common private glob-style patterns (defaults to " "'CVS', '.*' and '*~')." ), ) def set_options(self, **options): """ Set instance variables based on an options dict """ self.interactive = options["interactive"] self.verbosity = options["verbosity"] self.symlink = options["link"] self.clear = options["clear"] self.dry_run = options["dry_run"] ignore_patterns = options["ignore_patterns"] if options["use_default_ignore_patterns"]: ignore_patterns += apps.get_app_config("staticfiles").ignore_patterns self.ignore_patterns = list({os.path.normpath(p) for p in ignore_patterns}) self.post_process = options["post_process"] def collect(self): """ Perform the bulk of the work of collectstatic. Split off from handle() to facilitate testing. """ if self.symlink and not self.local: raise CommandError("Can't symlink to a remote destination.") if self.clear: self.clear_dir("") if self.symlink: handler = self.link_file else: handler = self.copy_file found_files = {} for finder in get_finders(): for path, storage in finder.list(self.ignore_patterns): # Prefix the relative path if the source storage contains it if getattr(storage, "prefix", None): prefixed_path = os.path.join(storage.prefix, path) else: prefixed_path = path if prefixed_path not in found_files: found_files[prefixed_path] = (storage, path) handler(path, prefixed_path, storage) else: self.log( "Found another file with the destination path '%s'. It " "will be ignored since only the first encountered file " "is collected. If this is not what you want, make sure " "every static file has a unique path." % prefixed_path, level=1, ) # Storage backends may define a post_process() method. if self.post_process and hasattr(self.storage, "post_process"): processor = self.storage.post_process(found_files, dry_run=self.dry_run) for original_path, processed_path, processed in processor: if isinstance(processed, Exception): self.stderr.write("Post-processing '%s' failed!" % original_path) # Add a blank line before the traceback, otherwise it's # too easy to miss the relevant part of the error message. self.stderr.write() raise processed if processed: self.log( "Post-processed '%s' as '%s'" % (original_path, processed_path), level=2, ) self.post_processed_files.append(original_path) else: self.log("Skipped post-processing '%s'" % original_path) return { "modified": self.copied_files + self.symlinked_files, "unmodified": self.unmodified_files, "post_processed": self.post_processed_files, } def handle(self, **options): self.set_options(**options) message = ["\n"] if self.dry_run: message.append( "You have activated the --dry-run option so no files will be " "modified.\n\n" ) message.append( "You have requested to collect static files at the destination\n" "location as specified in your settings" ) if self.is_local_storage() and self.storage.location: destination_path = self.storage.location message.append(":\n\n %s\n\n" % destination_path) should_warn_user = self.storage.exists(destination_path) and any( self.storage.listdir(destination_path) ) else: destination_path = None message.append(".\n\n") # Destination files existence not checked; play it safe and warn. should_warn_user = True if self.interactive and should_warn_user: if self.clear: message.append("This will DELETE ALL FILES in this location!\n") else: message.append("This will overwrite existing files!\n") message.append( "Are you sure you want to do this?\n\n" "Type 'yes' to continue, or 'no' to cancel: " ) if input("".join(message)) != "yes": raise CommandError("Collecting static files cancelled.") collected = self.collect() if self.verbosity >= 1: modified_count = len(collected["modified"]) unmodified_count = len(collected["unmodified"]) post_processed_count = len(collected["post_processed"]) return ( "\n%(modified_count)s %(identifier)s %(action)s" "%(destination)s%(unmodified)s%(post_processed)s." ) % { "modified_count": modified_count, "identifier": "static file" + ("" if modified_count == 1 else "s"), "action": "symlinked" if self.symlink else "copied", "destination": ( " to '%s'" % destination_path if destination_path else "" ), "unmodified": ( ", %s unmodified" % unmodified_count if collected["unmodified"] else "" ), "post_processed": ( collected["post_processed"] and ", %s post-processed" % post_processed_count or "" ), } def log(self, msg, level=2): """ Small log helper """ if self.verbosity >= level: self.stdout.write(msg) def is_local_storage(self): return isinstance(self.storage, FileSystemStorage) def clear_dir(self, path): """ Delete the given relative path using the destination storage backend. """ if not self.storage.exists(path): return dirs, files = self.storage.listdir(path) for f in files: fpath = os.path.join(path, f) if self.dry_run: self.log("Pretending to delete '%s'" % fpath, level=1) else: self.log("Deleting '%s'" % fpath, level=1) try: full_path = self.storage.path(fpath) except NotImplementedError: self.storage.delete(fpath) else: if not os.path.exists(full_path) and os.path.lexists(full_path): # Delete broken symlinks os.unlink(full_path) else: self.storage.delete(fpath) for d in dirs: self.clear_dir(os.path.join(path, d)) def delete_file(self, path, prefixed_path, source_storage): """ Check if the target file should be deleted if it already exists. """ if self.storage.exists(prefixed_path): try: # When was the target file modified last time? target_last_modified = self.storage.get_modified_time(prefixed_path) except (OSError, NotImplementedError, AttributeError): # The storage doesn't support get_modified_time() or failed pass else: try: # When was the source file modified last time? source_last_modified = source_storage.get_modified_time(path) except (OSError, NotImplementedError, AttributeError): pass else: # The full path of the target file if self.local: full_path = self.storage.path(prefixed_path) # If it's --link mode and the path isn't a link (i.e. # the previous collectstatic wasn't with --link) or if # it's non-link mode and the path is a link (i.e. the # previous collectstatic was with --link), the old # links/files must be deleted so it's not safe to skip # unmodified files. can_skip_unmodified_files = not ( self.symlink ^ os.path.islink(full_path) ) else: # In remote storages, skipping is only based on the # modified times since symlinks aren't relevant. can_skip_unmodified_files = True # Avoid sub-second precision (see #14665, #19540) file_is_unmodified = target_last_modified.replace( microsecond=0 ) >= source_last_modified.replace(microsecond=0) if file_is_unmodified and can_skip_unmodified_files: if prefixed_path not in self.unmodified_files: self.unmodified_files.append(prefixed_path) self.log("Skipping '%s' (not modified)" % path) return False # Then delete the existing file if really needed if self.dry_run: self.log("Pretending to delete '%s'" % path) else: self.log("Deleting '%s'" % path) self.storage.delete(prefixed_path) return True def link_file(self, path, prefixed_path, source_storage): """ Attempt to link ``path`` """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: return self.log("Skipping '%s' (already linked earlier)" % path) # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return # The full path of the source file source_path = source_storage.path(path) # Finally link the file if self.dry_run: self.log("Pretending to link '%s'" % source_path, level=1) else: self.log("Linking '%s'" % source_path, level=2) full_path = self.storage.path(prefixed_path) os.makedirs(os.path.dirname(full_path), exist_ok=True) try: if os.path.lexists(full_path): os.unlink(full_path) os.symlink(source_path, full_path) except NotImplementedError: import platform raise CommandError( "Symlinking is not supported in this " "platform (%s)." % platform.platform() ) except OSError as e: raise CommandError(e) if prefixed_path not in self.symlinked_files: self.symlinked_files.append(prefixed_path) def copy_file(self, path, prefixed_path, source_storage): """ Attempt to copy ``path`` with storage """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: return self.log("Skipping '%s' (already copied earlier)" % path) # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return # The full path of the source file source_path = source_storage.path(path) # Finally start copying if self.dry_run: self.log("Pretending to copy '%s'" % source_path, level=1) else: self.log("Copying '%s'" % source_path, level=2) with source_storage.open(path) as source_file: self.storage.save(prefixed_path, source_file) self.copied_files.append(prefixed_path)
4cc30695b57e0756aad5bdbb9c0e8eb6eea1578e29a80cdeb84b535760cf9a9d
import os from django.contrib.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( "--first", action="store_false", dest="all", help="Only return the first match for each static file.", ) def handle_label(self, path, **options): verbosity = options["verbosity"] result = finders.find(path, all=options["all"]) if verbosity >= 2: searched_locations = ( "\nLooking in the following locations:\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] result = (os.path.realpath(path) for path in result) if verbosity >= 1: file_list = "\n ".join(result) return "Found '%s' here:\n %s%s" % ( path, file_list, searched_locations, ) else: return "\n".join(result) else: message = ["No matching file found for '%s'." % path] if verbosity >= 2: message.append(searched_locations) if verbosity >= 1: self.stderr.write("\n".join(message))