hash
stringlengths
64
64
content
stringlengths
0
1.51M
34040ce91512b5b457465e7893f6dd045319a535e35ba2f5c0aa2c41b4d75b33
import mimetypes from email import ( charset as Charset, encoders as Encoders, generator, message_from_string, ) from email.errors import InvalidHeaderDefect, NonASCIILocalPartDefect from email.header import Header from email.headerregistry import Address from email.message import Message from email.mime.base import MIMEBase from email.mime.message import MIMEMessage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate, getaddresses, make_msgid, parseaddr from io import BytesIO, StringIO from pathlib import Path from django.conf import settings from django.core.mail.utils import DNS_NAME from django.utils.encoding import force_text # Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from # some spam filters. utf8_charset = Charset.Charset('utf-8') utf8_charset.body_encoding = None # Python defaults to BASE64 utf8_charset_qp = Charset.Charset('utf-8') utf8_charset_qp.body_encoding = Charset.QP # Default MIME type to use on attachments (if it is not explicitly given # and cannot be guessed). DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream' RFC5322_EMAIL_LINE_LENGTH_LIMIT = 998 class BadHeaderError(ValueError): pass # Header names that contain structured address data (RFC #5322) ADDRESS_HEADERS = { 'from', 'sender', 'reply-to', 'to', 'cc', 'bcc', 'resent-from', 'resent-sender', 'resent-to', 'resent-cc', 'resent-bcc', } def forbid_multi_line_headers(name, val, encoding): """Forbid multi-line headers to prevent header injection.""" encoding = encoding or settings.DEFAULT_CHARSET val = str(val) # val may be lazy if '\n' in val or '\r' in val: raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name)) try: val.encode('ascii') except UnicodeEncodeError: if name.lower() in ADDRESS_HEADERS: val = ', '.join(sanitize_address(addr, encoding) for addr in getaddresses((val,))) else: val = Header(val, encoding).encode() else: if name.lower() == 'subject': val = Header(val).encode() return name, val def split_addr(addr, encoding): """ Split the address into local part and domain and encode them. When non-ascii characters are present in the local part, it must be MIME-word encoded. The domain name must be idna-encoded if it contains non-ascii characters. """ if '@' in addr: localpart, domain = addr.split('@', 1) # Try to get the simplest encoding - ascii if possible so that # [email protected] doesn't become [email protected]. This # makes unit testing a bit easier and more readable. try: localpart.encode('ascii') except UnicodeEncodeError: localpart = Header(localpart, encoding).encode() domain = domain.encode('idna').decode('ascii') else: localpart = Header(addr, encoding).encode() domain = '' return (localpart, domain) def sanitize_address(addr, encoding): """ Format a pair of (name, address) or an email address string. """ if not isinstance(addr, tuple): addr = parseaddr(addr) nm, addr = addr localpart, domain = None, None nm = Header(nm, encoding).encode() try: addr.encode('ascii') except UnicodeEncodeError: # IDN or non-ascii in the local part localpart, domain = split_addr(addr, encoding) # An `email.headerregistry.Address` object is used since # email.utils.formataddr() naively encodes the name as ascii (see #25986). if localpart and domain: address = Address(nm, username=localpart, domain=domain) return str(address) try: address = Address(nm, addr_spec=addr) except (InvalidHeaderDefect, NonASCIILocalPartDefect): localpart, domain = split_addr(addr, encoding) address = Address(nm, username=localpart, domain=domain) return str(address) class MIMEMixin: def as_string(self, unixfrom=False, linesep='\n'): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = StringIO() g = generator.Generator(fp, mangle_from_=False) g.flatten(self, unixfrom=unixfrom, linesep=linesep) return fp.getvalue() def as_bytes(self, unixfrom=False, linesep='\n'): """Return the entire formatted message as bytes. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_bytes() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = BytesIO() g = generator.BytesGenerator(fp, mangle_from_=False) g.flatten(self, unixfrom=unixfrom, linesep=linesep) return fp.getvalue() class SafeMIMEMessage(MIMEMixin, MIMEMessage): def __setitem__(self, name, val): # message/rfc822 attachments must be ASCII name, val = forbid_multi_line_headers(name, val, 'ascii') MIMEMessage.__setitem__(self, name, val) class SafeMIMEText(MIMEMixin, MIMEText): def __init__(self, _text, _subtype='plain', _charset=None): self.encoding = _charset MIMEText.__init__(self, _text, _subtype=_subtype, _charset=_charset) def __setitem__(self, name, val): name, val = forbid_multi_line_headers(name, val, self.encoding) MIMEText.__setitem__(self, name, val) def set_payload(self, payload, charset=None): if charset == 'utf-8': has_long_lines = any( len(l.encode()) > RFC5322_EMAIL_LINE_LENGTH_LIMIT for l in payload.splitlines() ) # Quoted-Printable encoding has the side effect of shortening long # lines, if any (#22561). charset = utf8_charset_qp if has_long_lines else utf8_charset MIMEText.set_payload(self, payload, charset=charset) class SafeMIMEMultipart(MIMEMixin, MIMEMultipart): def __init__(self, _subtype='mixed', boundary=None, _subparts=None, encoding=None, **_params): self.encoding = encoding MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params) def __setitem__(self, name, val): name, val = forbid_multi_line_headers(name, val, self.encoding) MIMEMultipart.__setitem__(self, name, val) class EmailMessage: """A container for email information.""" content_subtype = 'plain' mixed_subtype = 'mixed' encoding = None # None => use settings default def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None, reply_to=None): """ Initialize a single email message (which can be sent to multiple recipients). """ if to: if isinstance(to, str): raise TypeError('"to" argument must be a list or tuple') self.to = list(to) else: self.to = [] if cc: if isinstance(cc, str): raise TypeError('"cc" argument must be a list or tuple') self.cc = list(cc) else: self.cc = [] if bcc: if isinstance(bcc, str): raise TypeError('"bcc" argument must be a list or tuple') self.bcc = list(bcc) else: self.bcc = [] if reply_to: if isinstance(reply_to, str): raise TypeError('"reply_to" argument must be a list or tuple') self.reply_to = list(reply_to) else: self.reply_to = [] self.from_email = from_email or settings.DEFAULT_FROM_EMAIL self.subject = subject self.body = body or '' self.attachments = [] if attachments: for attachment in attachments: if isinstance(attachment, MIMEBase): self.attach(attachment) else: self.attach(*attachment) self.extra_headers = headers or {} self.connection = connection def get_connection(self, fail_silently=False): from django.core.mail import get_connection if not self.connection: self.connection = get_connection(fail_silently=fail_silently) return self.connection def message(self): encoding = self.encoding or settings.DEFAULT_CHARSET msg = SafeMIMEText(self.body, self.content_subtype, encoding) msg = self._create_message(msg) msg['Subject'] = self.subject msg['From'] = self.extra_headers.get('From', self.from_email) self._set_list_header_if_not_empty(msg, 'To', self.to) self._set_list_header_if_not_empty(msg, 'Cc', self.cc) self._set_list_header_if_not_empty(msg, 'Reply-To', self.reply_to) # Email header names are case-insensitive (RFC 2045), so we have to # accommodate that when doing comparisons. header_names = [key.lower() for key in self.extra_headers] if 'date' not in header_names: # formatdate() uses stdlib methods to format the date, which use # the stdlib/OS concept of a timezone, however, Django sets the # TZ environment variable based on the TIME_ZONE setting which # will get picked up by formatdate(). msg['Date'] = formatdate(localtime=settings.EMAIL_USE_LOCALTIME) if 'message-id' not in header_names: # Use cached DNS_NAME for performance msg['Message-ID'] = make_msgid(domain=DNS_NAME) for name, value in self.extra_headers.items(): if name.lower() != 'from': # From is already handled msg[name] = value return msg def recipients(self): """ Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). """ return [email for email in (self.to + self.cc + self.bcc) if email] def send(self, fail_silently=False): """Send the email message.""" if not self.recipients(): # Don't bother creating the network connection if there's nobody to # send to. return 0 return self.get_connection(fail_silently).send_messages([self]) def attach(self, filename=None, content=None, mimetype=None): """ Attach a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass, insert it directly into the resulting message attachments. For a text/* mimetype (guessed or specified), when a bytes object is specified as content, decode it as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content. """ if isinstance(filename, MIMEBase): assert content is None assert mimetype is None self.attachments.append(filename) else: assert content is not None mimetype = mimetype or mimetypes.guess_type(filename)[0] or DEFAULT_ATTACHMENT_MIME_TYPE basetype, subtype = mimetype.split('/', 1) if basetype == 'text': if isinstance(content, bytes): try: content = content.decode() except UnicodeDecodeError: # If mimetype suggests the file is text but it's # actually binary, read() raises a UnicodeDecodeError. mimetype = DEFAULT_ATTACHMENT_MIME_TYPE self.attachments.append((filename, content, mimetype)) def attach_file(self, path, mimetype=None): """ Attach a file from the filesystem. Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified and cannot be guessed. For a text/* mimetype (guessed or specified), decode the file's content as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content. """ path = Path(path) with path.open('rb') as file: content = file.read() self.attach(path.name, content, mimetype) def _create_message(self, msg): return self._create_attachments(msg) def _create_attachments(self, msg): if self.attachments: encoding = self.encoding or settings.DEFAULT_CHARSET body_msg = msg msg = SafeMIMEMultipart(_subtype=self.mixed_subtype, encoding=encoding) if self.body or body_msg.is_multipart(): msg.attach(body_msg) for attachment in self.attachments: if isinstance(attachment, MIMEBase): msg.attach(attachment) else: msg.attach(self._create_attachment(*attachment)) return msg def _create_mime_attachment(self, content, mimetype): """ Convert the content, mimetype pair into a MIME attachment object. If the mimetype is message/rfc822, content may be an email.Message or EmailMessage object, as well as a str. """ basetype, subtype = mimetype.split('/', 1) if basetype == 'text': encoding = self.encoding or settings.DEFAULT_CHARSET attachment = SafeMIMEText(content, subtype, encoding) elif basetype == 'message' and subtype == 'rfc822': # Bug #18967: per RFC2046 s5.2.1, message/rfc822 attachments # must not be base64 encoded. if isinstance(content, EmailMessage): # convert content into an email.Message first content = content.message() elif not isinstance(content, Message): # For compatibility with existing code, parse the message # into an email.Message object if it is not one already. content = message_from_string(force_text(content)) attachment = SafeMIMEMessage(content, subtype) else: # Encode non-text attachments with base64. attachment = MIMEBase(basetype, subtype) attachment.set_payload(content) Encoders.encode_base64(attachment) return attachment def _create_attachment(self, filename, content, mimetype=None): """ Convert the filename, content, mimetype triple into a MIME attachment object. """ attachment = self._create_mime_attachment(content, mimetype) if filename: try: filename.encode('ascii') except UnicodeEncodeError: filename = ('utf-8', '', filename) attachment.add_header('Content-Disposition', 'attachment', filename=filename) return attachment def _set_list_header_if_not_empty(self, msg, header, values): """ Set msg's header, either from self.extra_headers, if present, or from the values argument. """ if values: try: value = self.extra_headers[header] except KeyError: value = ', '.join(str(v) for v in values) msg[header] = value class EmailMultiAlternatives(EmailMessage): """ A version of EmailMessage that makes it easy to send multipart/alternative messages. For example, including text and HTML versions of the text is made easier. """ alternative_subtype = 'alternative' def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None, reply_to=None): """ Initialize a single email message (which can be sent to multiple recipients). """ super().__init__( subject, body, from_email, to, bcc, connection, attachments, headers, cc, reply_to, ) self.alternatives = alternatives or [] def attach_alternative(self, content, mimetype): """Attach an alternative content representation.""" assert content is not None assert mimetype is not None self.alternatives.append((content, mimetype)) def _create_message(self, msg): return self._create_attachments(self._create_alternatives(msg)) def _create_alternatives(self, msg): encoding = self.encoding or settings.DEFAULT_CHARSET if self.alternatives: body_msg = msg msg = SafeMIMEMultipart(_subtype=self.alternative_subtype, encoding=encoding) if self.body: msg.attach(body_msg) for alternative in self.alternatives: msg.attach(self._create_mime_attachment(*alternative)) return msg
befb31284c1bdea1e09c21b447929491f529307b9931fc63a3df97fb6053a7ee
from django.conf import settings from .. import Tags, Warning, register def add_session_cookie_message(message): return message + ( " Using a secure-only session cookie makes it more difficult for " "network traffic sniffers to hijack user sessions." ) W010 = Warning( add_session_cookie_message( "You have 'django.contrib.sessions' in your INSTALLED_APPS, " "but you have not set SESSION_COOKIE_SECURE to True." ), id='security.W010', ) W011 = Warning( add_session_cookie_message( "You have 'django.contrib.sessions.middleware.SessionMiddleware' " "in your MIDDLEWARE, but you have not set " "SESSION_COOKIE_SECURE to True." ), id='security.W011', ) W012 = Warning( add_session_cookie_message("SESSION_COOKIE_SECURE is not set to True."), id='security.W012', ) def add_httponly_message(message): return message + ( " Using an HttpOnly session cookie makes it more difficult for " "cross-site scripting attacks to hijack user sessions." ) W013 = Warning( add_httponly_message( "You have 'django.contrib.sessions' in your INSTALLED_APPS, " "but you have not set SESSION_COOKIE_HTTPONLY to True.", ), id='security.W013', ) W014 = Warning( add_httponly_message( "You have 'django.contrib.sessions.middleware.SessionMiddleware' " "in your MIDDLEWARE, but you have not set " "SESSION_COOKIE_HTTPONLY to True." ), id='security.W014', ) W015 = Warning( add_httponly_message("SESSION_COOKIE_HTTPONLY is not set to True."), id='security.W015', ) @register(Tags.security, deploy=True) def check_session_cookie_secure(app_configs, **kwargs): errors = [] if not settings.SESSION_COOKIE_SECURE: if _session_app(): errors.append(W010) if _session_middleware(): errors.append(W011) if len(errors) > 1: errors = [W012] return errors @register(Tags.security, deploy=True) def check_session_cookie_httponly(app_configs, **kwargs): errors = [] if not settings.SESSION_COOKIE_HTTPONLY: if _session_app(): errors.append(W013) if _session_middleware(): errors.append(W014) if len(errors) > 1: errors = [W015] return errors def _session_middleware(): return 'django.contrib.sessions.middleware.SessionMiddleware' in settings.MIDDLEWARE def _session_app(): return "django.contrib.sessions" in settings.INSTALLED_APPS
26c17c52f24b9565c5db2b2cc16693d3c32a77a283b78c1e394af5faca4266df
from django.conf import settings from .. import Tags, Warning, register SECRET_KEY_MIN_LENGTH = 50 SECRET_KEY_MIN_UNIQUE_CHARACTERS = 5 W001 = Warning( "You do not have 'django.middleware.security.SecurityMiddleware' " "in your MIDDLEWARE so the SECURE_HSTS_SECONDS, " "SECURE_CONTENT_TYPE_NOSNIFF, " "SECURE_BROWSER_XSS_FILTER, and SECURE_SSL_REDIRECT settings " "will have no effect.", id='security.W001', ) W002 = Warning( "You do not have " "'django.middleware.clickjacking.XFrameOptionsMiddleware' in your " "MIDDLEWARE, so your pages will not be served with an " "'x-frame-options' header. Unless there is a good reason for your " "site to be served in a frame, you should consider enabling this " "header to help prevent clickjacking attacks.", id='security.W002', ) W004 = Warning( "You have not set a value for the SECURE_HSTS_SECONDS setting. " "If your entire site is served only over SSL, you may want to consider " "setting a value and enabling HTTP Strict Transport Security. " "Be sure to read the documentation first; enabling HSTS carelessly " "can cause serious, irreversible problems.", id='security.W004', ) W005 = Warning( "You have not set the SECURE_HSTS_INCLUDE_SUBDOMAINS setting to True. " "Without this, your site is potentially vulnerable to attack " "via an insecure connection to a subdomain. Only set this to True if " "you are certain that all subdomains of your domain should be served " "exclusively via SSL.", id='security.W005', ) W006 = Warning( "Your SECURE_CONTENT_TYPE_NOSNIFF setting is not set to True, " "so your pages will not be served with an " "'x-content-type-options: nosniff' header. " "You should consider enabling this header to prevent the " "browser from identifying content types incorrectly.", id='security.W006', ) W007 = Warning( "Your SECURE_BROWSER_XSS_FILTER setting is not set to True, " "so your pages will not be served with an " "'x-xss-protection: 1; mode=block' header. " "You should consider enabling this header to activate the " "browser's XSS filtering and help prevent XSS attacks.", id='security.W007', ) W008 = Warning( "Your SECURE_SSL_REDIRECT setting is not set to True. " "Unless your site should be available over both SSL and non-SSL " "connections, you may want to either set this setting True " "or configure a load balancer or reverse-proxy server " "to redirect all connections to HTTPS.", id='security.W008', ) W009 = Warning( "Your SECRET_KEY has less than %(min_length)s characters or less than " "%(min_unique_chars)s unique characters. Please generate a long and random " "SECRET_KEY, otherwise many of Django's security-critical features will be " "vulnerable to attack." % { 'min_length': SECRET_KEY_MIN_LENGTH, 'min_unique_chars': SECRET_KEY_MIN_UNIQUE_CHARACTERS, }, id='security.W009', ) W018 = Warning( "You should not have DEBUG set to True in deployment.", id='security.W018', ) W019 = Warning( "You have " "'django.middleware.clickjacking.XFrameOptionsMiddleware' in your " "MIDDLEWARE, but X_FRAME_OPTIONS is not set to 'DENY'. " "The default is 'SAMEORIGIN', but unless there is a good reason for " "your site to serve other parts of itself in a frame, you should " "change it to 'DENY'.", id='security.W019', ) W020 = Warning( "ALLOWED_HOSTS must not be empty in deployment.", id='security.W020', ) W021 = Warning( "You have not set the SECURE_HSTS_PRELOAD setting to True. Without this, " "your site cannot be submitted to the browser preload list.", id='security.W021', ) def _security_middleware(): return 'django.middleware.security.SecurityMiddleware' in settings.MIDDLEWARE def _xframe_middleware(): return 'django.middleware.clickjacking.XFrameOptionsMiddleware' in settings.MIDDLEWARE @register(Tags.security, deploy=True) def check_security_middleware(app_configs, **kwargs): passed_check = _security_middleware() return [] if passed_check else [W001] @register(Tags.security, deploy=True) def check_xframe_options_middleware(app_configs, **kwargs): passed_check = _xframe_middleware() return [] if passed_check else [W002] @register(Tags.security, deploy=True) def check_sts(app_configs, **kwargs): passed_check = not _security_middleware() or settings.SECURE_HSTS_SECONDS return [] if passed_check else [W004] @register(Tags.security, deploy=True) def check_sts_include_subdomains(app_configs, **kwargs): passed_check = ( not _security_middleware() or not settings.SECURE_HSTS_SECONDS or settings.SECURE_HSTS_INCLUDE_SUBDOMAINS is True ) return [] if passed_check else [W005] @register(Tags.security, deploy=True) def check_sts_preload(app_configs, **kwargs): passed_check = ( not _security_middleware() or not settings.SECURE_HSTS_SECONDS or settings.SECURE_HSTS_PRELOAD is True ) return [] if passed_check else [W021] @register(Tags.security, deploy=True) def check_content_type_nosniff(app_configs, **kwargs): passed_check = ( not _security_middleware() or settings.SECURE_CONTENT_TYPE_NOSNIFF is True ) return [] if passed_check else [W006] @register(Tags.security, deploy=True) def check_xss_filter(app_configs, **kwargs): passed_check = ( not _security_middleware() or settings.SECURE_BROWSER_XSS_FILTER is True ) return [] if passed_check else [W007] @register(Tags.security, deploy=True) def check_ssl_redirect(app_configs, **kwargs): passed_check = ( not _security_middleware() or settings.SECURE_SSL_REDIRECT is True ) return [] if passed_check else [W008] @register(Tags.security, deploy=True) def check_secret_key(app_configs, **kwargs): passed_check = ( getattr(settings, 'SECRET_KEY', None) and len(set(settings.SECRET_KEY)) >= SECRET_KEY_MIN_UNIQUE_CHARACTERS and len(settings.SECRET_KEY) >= SECRET_KEY_MIN_LENGTH ) return [] if passed_check else [W009] @register(Tags.security, deploy=True) def check_debug(app_configs, **kwargs): passed_check = not settings.DEBUG return [] if passed_check else [W018] @register(Tags.security, deploy=True) def check_xframe_deny(app_configs, **kwargs): passed_check = ( not _xframe_middleware() or settings.X_FRAME_OPTIONS == 'DENY' ) return [] if passed_check else [W019] @register(Tags.security, deploy=True) def check_allowed_hosts(app_configs, **kwargs): return [] if settings.ALLOWED_HOSTS else [W020]
087d3dade3875d011d08caa195e8f287422c1b00d09057874583b6e609594d81
from django.conf import settings from .. import Tags, Warning, register W003 = Warning( "You don't appear to be using Django's built-in " "cross-site request forgery protection via the middleware " "('django.middleware.csrf.CsrfViewMiddleware' is not in your " "MIDDLEWARE). Enabling the middleware is the safest approach " "to ensure you don't leave any holes.", id='security.W003', ) W016 = Warning( "You have 'django.middleware.csrf.CsrfViewMiddleware' in your " "MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. " "Using a secure-only CSRF cookie makes it more difficult for network " "traffic sniffers to steal the CSRF token.", id='security.W016', ) def _csrf_middleware(): return 'django.middleware.csrf.CsrfViewMiddleware' in settings.MIDDLEWARE @register(Tags.security, deploy=True) def check_csrf_middleware(app_configs, **kwargs): passed_check = _csrf_middleware() return [] if passed_check else [W003] @register(Tags.security, deploy=True) def check_csrf_cookie_secure(app_configs, **kwargs): passed_check = ( settings.CSRF_USE_SESSIONS or not _csrf_middleware() or settings.CSRF_COOKIE_SECURE ) return [] if passed_check else [W016]
88a9613e9385b21fc19b98d74527d05fdcd84d94dd421effd12cd90e540f37b1
import time from collections import OrderedDict from importlib import import_module from django.apps import apps from django.core.checks import Tags, run_checks from django.core.management.base import ( BaseCommand, CommandError, no_translations, ) from django.core.management.sql import ( emit_post_migrate_signal, emit_pre_migrate_signal, ) from django.db import DEFAULT_DB_ALIAS, connections, router from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.executor import MigrationExecutor from django.db.migrations.loader import AmbiguityError from django.db.migrations.state import ModelState, ProjectState from django.utils.module_loading import module_has_submodule class Command(BaseCommand): help = "Updates database schema. Manages both apps with migrations and those without." def add_arguments(self, parser): parser.add_argument( 'app_label', nargs='?', help='App label of an application to synchronize the state.', ) parser.add_argument( 'migration_name', nargs='?', help='Database state will be brought to the state after that ' 'migration. Use the name "zero" to unapply all migrations.', ) parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. Defaults to the "default" database.', ) parser.add_argument( '--fake', action='store_true', dest='fake', help='Mark migrations as run without actually running them.', ) parser.add_argument( '--fake-initial', action='store_true', dest='fake_initial', help='Detect if tables already exist and fake-apply initial migrations if so. Make sure ' 'that the current database schema matches your initial migration before using this ' 'flag. Django will only check for an existing table name.', ) parser.add_argument( '--run-syncdb', action='store_true', dest='run_syncdb', help='Creates tables for apps without migrations.', ) def _run_checks(self, **kwargs): issues = run_checks(tags=[Tags.database]) issues.extend(super()._run_checks(**kwargs)) return issues @no_translations def handle(self, *args, **options): self.verbosity = options['verbosity'] self.interactive = options['interactive'] # Import the 'management' module within each installed app, to register # dispatcher events. for app_config in apps.get_app_configs(): if module_has_submodule(app_config.module, "management"): import_module('.management', app_config.name) # Get the database we're operating from db = options['database'] connection = connections[db] # Hook for backends needing any database preparation connection.prepare_database() # Work out which apps have migrations and which do not executor = MigrationExecutor(connection, self.migration_progress_callback) # Raise an error if any migrations are applied before their dependencies. executor.loader.check_consistent_history(connection) # Before anything else, see if there's conflicting apps and drop out # hard if there are any conflicts = executor.loader.detect_conflicts() if conflicts: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str ) # If they supplied command line arguments, work out what they mean. target_app_labels_only = True if options['app_label']: # Validate app_label. app_label = options['app_label'] try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) if app_label not in executor.loader.migrated_apps: raise CommandError("App '%s' does not have migrations." % app_label) if options['app_label'] and options['migration_name']: migration_name = options['migration_name'] if migration_name == "zero": targets = [(app_label, None)] else: try: migration = executor.loader.get_migration_by_prefix(app_label, migration_name) except AmbiguityError: raise CommandError( "More than one migration matches '%s' in app '%s'. " "Please be more specific." % (migration_name, app_label) ) except KeyError: raise CommandError("Cannot find a migration matching '%s' from app '%s'." % ( migration_name, app_label)) targets = [(app_label, migration.name)] target_app_labels_only = False elif options['app_label']: targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label] else: targets = executor.loader.graph.leaf_nodes() plan = executor.migration_plan(targets) run_syncdb = options['run_syncdb'] and executor.loader.unmigrated_apps # Print some useful info if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:")) if run_syncdb: self.stdout.write( self.style.MIGRATE_LABEL(" Synchronize unmigrated apps: ") + (", ".join(sorted(executor.loader.unmigrated_apps))) ) if target_app_labels_only: self.stdout.write( self.style.MIGRATE_LABEL(" Apply all migrations: ") + (", ".join(sorted({a for a, n in targets})) or "(none)") ) else: if targets[0][1] is None: self.stdout.write(self.style.MIGRATE_LABEL( " Unapply all migrations: ") + "%s" % (targets[0][0],) ) else: self.stdout.write(self.style.MIGRATE_LABEL( " Target specific migration: ") + "%s, from %s" % (targets[0][1], targets[0][0]) ) pre_migrate_state = executor._create_project_state(with_applied_migrations=True) pre_migrate_apps = pre_migrate_state.apps emit_pre_migrate_signal( self.verbosity, self.interactive, connection.alias, apps=pre_migrate_apps, plan=plan, ) # Run the syncdb phase. if run_syncdb: if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Synchronizing apps without migrations:")) self.sync_apps(connection, executor.loader.unmigrated_apps) # Migrate! if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Running migrations:")) if not plan: if self.verbosity >= 1: self.stdout.write(" No migrations to apply.") # If there's changes that aren't in migrations yet, tell them how to fix it. autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps), ) changes = autodetector.changes(graph=executor.loader.graph) if changes: self.stdout.write(self.style.NOTICE( " Your models have changes that are not yet reflected " "in a migration, and so won't be applied." )) self.stdout.write(self.style.NOTICE( " Run 'manage.py makemigrations' to make new " "migrations, and then re-run 'manage.py migrate' to " "apply them." )) fake = False fake_initial = False else: fake = options['fake'] fake_initial = options['fake_initial'] post_migrate_state = executor.migrate( targets, plan=plan, state=pre_migrate_state.clone(), fake=fake, fake_initial=fake_initial, ) # post_migrate signals have access to all models. Ensure that all models # are reloaded in case any are delayed. post_migrate_state.clear_delayed_apps_cache() post_migrate_apps = post_migrate_state.apps # Re-render models of real apps to include relationships now that # we've got a final state. This wouldn't be necessary if real apps # models were rendered with relationships in the first place. with post_migrate_apps.bulk_update(): model_keys = [] for model_state in post_migrate_apps.real_models: model_key = model_state.app_label, model_state.name_lower model_keys.append(model_key) post_migrate_apps.unregister_model(*model_key) post_migrate_apps.render_multiple([ ModelState.from_model(apps.get_model(*model)) for model in model_keys ]) # Send the post_migrate signal, so individual apps can do whatever they need # to do at this point. emit_post_migrate_signal( self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, ) def migration_progress_callback(self, action, migration=None, fake=False): if self.verbosity >= 1: compute_time = self.verbosity > 1 if action == "apply_start": if compute_time: self.start = time.time() self.stdout.write(" Applying %s..." % migration, ending="") self.stdout.flush() elif action == "apply_success": elapsed = " (%.3fs)" % (time.time() - self.start) if compute_time else "" if fake: self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed)) else: self.stdout.write(self.style.SUCCESS(" OK" + elapsed)) elif action == "unapply_start": if compute_time: self.start = time.time() self.stdout.write(" Unapplying %s..." % migration, ending="") self.stdout.flush() elif action == "unapply_success": elapsed = " (%.3fs)" % (time.time() - self.start) if compute_time else "" if fake: self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed)) else: self.stdout.write(self.style.SUCCESS(" OK" + elapsed)) elif action == "render_start": if compute_time: self.start = time.time() self.stdout.write(" Rendering model states...", ending="") self.stdout.flush() elif action == "render_success": elapsed = " (%.3fs)" % (time.time() - self.start) if compute_time else "" self.stdout.write(self.style.SUCCESS(" DONE" + elapsed)) def sync_apps(self, connection, app_labels): """Run the old syncdb-style operation on a list of app_labels.""" with connection.cursor() as cursor: tables = connection.introspection.table_names(cursor) # Build the manifest of apps and models that are to be synchronized. all_models = [ ( app_config.label, router.get_migratable_models(app_config, connection.alias, include_auto_created=False), ) for app_config in apps.get_app_configs() if app_config.models_module is not None and app_config.label in app_labels ] def model_installed(model): opts = model._meta converter = connection.introspection.table_name_converter return not ( (converter(opts.db_table) in tables) or (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables) ) manifest = OrderedDict( (app_name, list(filter(model_installed, model_list))) for app_name, model_list in all_models ) # Create the tables for each model if self.verbosity >= 1: self.stdout.write(" Creating tables...\n") with connection.schema_editor() as editor: for app_name, model_list in manifest.items(): for model in model_list: # Never install unmanaged models, etc. if not model._meta.can_migrate(connection): continue if self.verbosity >= 3: self.stdout.write( " Processing %s.%s model\n" % (app_name, model._meta.object_name) ) if self.verbosity >= 1: self.stdout.write(" Creating table %s\n" % model._meta.db_table) editor.create_model(model) # Deferred SQL is executed when exiting the editor's context. if self.verbosity >= 1: self.stdout.write(" Running deferred SQL...\n")
9f099103dadd79abc33e62296469941bbf5f7ed8eb69d2adae880d20de026a40
from django.apps import apps from django.core import checks from django.core.checks.registry import registry from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Checks the entire Django project for potential problems." requires_system_checks = False def add_arguments(self, parser): parser.add_argument('args', metavar='app_label', nargs='*') parser.add_argument( '--tag', '-t', action='append', dest='tags', help='Run only checks labeled with given tag.', ) parser.add_argument( '--list-tags', action='store_true', dest='list_tags', help='List available tags.', ) parser.add_argument( '--deploy', action='store_true', dest='deploy', help='Check deployment settings.', ) parser.add_argument( '--fail-level', default='ERROR', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], dest='fail_level', help=( 'Message level that will cause the command to exit with a ' 'non-zero status. Default is ERROR.' ), ) def handle(self, *app_labels, **options): include_deployment_checks = options['deploy'] if options['list_tags']: self.stdout.write('\n'.join(sorted(registry.tags_available(include_deployment_checks)))) return if app_labels: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] else: app_configs = None tags = options['tags'] if tags: try: invalid_tag = next( tag for tag in tags if not checks.tag_exists(tag, include_deployment_checks) ) except StopIteration: # no invalid tags pass else: raise CommandError('There is no system check with the "%s" tag.' % invalid_tag) self.check( app_configs=app_configs, tags=tags, display_num_errors=True, include_deployment_checks=include_deployment_checks, fail_level=getattr(checks, options['fail_level']), )
842c9cea883b2b87036d57e57fce65bac828433d1f5a23b2968e89b65a2577c5
from django.core.management.base import AppCommand from django.db import DEFAULT_DB_ALIAS, connections class Command(AppCommand): help = 'Prints the SQL statements for resetting sequences for the given app name(s).' output_transaction = True def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( '--database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the SQL for. Defaults to the "default" database.', ) def handle_app_config(self, app_config, **options): if app_config.models_module is None: return connection = connections[options['database']] models = app_config.get_models(include_auto_created=True) statements = connection.ops.sequence_reset_sql(self.style, models) return '\n'.join(statements)
f65272fdc18c6a37559ab2f0745a58a8308df3d1baf7161c8f004d7cea644557
from importlib import import_module from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import emit_post_migrate_signal, sql_flush from django.db import DEFAULT_DB_ALIAS, connections class Command(BaseCommand): help = ( 'Removes ALL DATA from the database, including data added during ' 'migrations. Does not achieve a "fresh install" state.' ) stealth_options = ('reset_sequences', 'allow_cascade', 'inhibit_post_migrate') def add_arguments(self, parser): parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to flush. Defaults to the "default" database.', ) def handle(self, **options): database = options['database'] connection = connections[database] verbosity = options['verbosity'] interactive = options['interactive'] # The following are stealth options used by Django's internals. reset_sequences = options.get('reset_sequences', True) allow_cascade = options.get('allow_cascade', False) inhibit_post_migrate = options.get('inhibit_post_migrate', False) self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_config in apps.get_app_configs(): try: import_module('.management', app_config.name) except ImportError: pass sql_list = sql_flush(self.style, connection, only_django=True, reset_sequences=reset_sequences, allow_cascade=allow_cascade) if interactive: confirm = input("""You have requested a flush of the database. This will IRREVERSIBLY DESTROY all data currently in the %r database, and return each table to an empty state. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME']) else: confirm = 'yes' if confirm == 'yes': try: connection.ops.execute_sql_flush(database, sql_list) except Exception as exc: raise CommandError( "Database %s couldn't be flushed. Possible reasons:\n" " * The database isn't running or isn't configured correctly.\n" " * At least one of the expected database tables doesn't exist.\n" " * The SQL was invalid.\n" "Hint: Look at the output of 'django-admin sqlflush'. " "That's the SQL this command wasn't able to run.\n" % ( connection.settings_dict['NAME'], ) ) from exc # Empty sql_list may signify an empty database and post_migrate would then crash if sql_list and not inhibit_post_migrate: # Emit the post migrate signal. This allows individual applications to # respond as if the database had been migrated from scratch. emit_post_migrate_signal(verbosity, interactive, database) else: self.stdout.write("Flush cancelled.\n")
afc0900f28353bcd8fbbea75e7267a234d5adce3fe0728b2b8a7a3b3d02f63d1
import warnings from collections import OrderedDict from django.apps import apps from django.core import serializers from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import parse_apps_and_model_labels from django.db import DEFAULT_DB_ALIAS, router class ProxyModelWarning(Warning): pass class Command(BaseCommand): help = ( "Output the contents of the database as a fixture of the given format " "(using each model's default manager unless --all is specified)." ) def add_arguments(self, parser): parser.add_argument( 'args', metavar='app_label[.ModelName]', nargs='*', help='Restricts dumped data to the specified app_label or app_label.ModelName.', ) parser.add_argument( '--format', default='json', dest='format', help='Specifies the output serialization format for fixtures.', ) parser.add_argument( '--indent', default=None, dest='indent', type=int, help='Specifies the indent level to use when pretty-printing output.', ) parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a specific database to dump fixtures from. ' 'Defaults to the "default" database.', ) parser.add_argument( '-e', '--exclude', dest='exclude', action='append', default=[], help='An app_label or app_label.ModelName to exclude ' '(use multiple --exclude to exclude multiple apps/models).', ) parser.add_argument( '--natural-foreign', action='store_true', dest='use_natural_foreign_keys', help='Use natural foreign keys if they are available.', ) parser.add_argument( '--natural-primary', action='store_true', dest='use_natural_primary_keys', help='Use natural primary keys if they are available.', ) parser.add_argument( '-a', '--all', action='store_true', dest='use_base_manager', help="Use Django's base manager to dump all models stored in the database, " "including those that would otherwise be filtered or modified by a custom manager.", ) parser.add_argument( '--pks', dest='primary_keys', help="Only dump objects with given primary keys. Accepts a comma-separated " "list of keys. This option only works when you specify one model.", ) parser.add_argument( '-o', '--output', default=None, dest='output', help='Specifies file to which the output is written.' ) def handle(self, *app_labels, **options): format = options['format'] indent = options['indent'] using = options['database'] excludes = options['exclude'] output = options['output'] show_traceback = options['traceback'] use_natural_foreign_keys = options['use_natural_foreign_keys'] use_natural_primary_keys = options['use_natural_primary_keys'] use_base_manager = options['use_base_manager'] pks = options['primary_keys'] if pks: primary_keys = [pk.strip() for pk in pks.split(',')] else: primary_keys = [] excluded_models, excluded_apps = parse_apps_and_model_labels(excludes) if not app_labels: if primary_keys: raise CommandError("You can only use --pks option with one model") app_list = OrderedDict.fromkeys( app_config for app_config in apps.get_app_configs() if app_config.models_module is not None and app_config not in excluded_apps ) else: if len(app_labels) > 1 and primary_keys: raise CommandError("You can only use --pks option with one model") app_list = OrderedDict() for label in app_labels: try: app_label, model_label = label.split('.') try: app_config = apps.get_app_config(app_label) except LookupError as e: raise CommandError(str(e)) if app_config.models_module is None or app_config in excluded_apps: continue try: model = app_config.get_model(model_label) except LookupError: raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) app_list_value = app_list.setdefault(app_config, []) # We may have previously seen a "all-models" request for # this app (no model qualifier was given). In this case # there is no need adding specific models to the list. if app_list_value is not None: if model not in app_list_value: app_list_value.append(model) except ValueError: if primary_keys: raise CommandError("You can only use --pks option with one model") # This is just an app - no model qualifier app_label = label try: app_config = apps.get_app_config(app_label) except LookupError as e: raise CommandError(str(e)) if app_config.models_module is None or app_config in excluded_apps: continue app_list[app_config] = None # Check that the serialization format exists; this is a shortcut to # avoid collating all the objects and _then_ failing. if format not in serializers.get_public_serializer_formats(): try: serializers.get_serializer(format) except serializers.SerializerDoesNotExist: pass raise CommandError("Unknown serialization format: %s" % format) def get_objects(count_only=False): """ Collate the objects to be serialized. If count_only is True, just count the number of objects to be serialized. """ models = serializers.sort_dependencies(app_list.items()) for model in models: if model in excluded_models: continue if model._meta.proxy and model._meta.proxy_for_model not in models: warnings.warn( "%s is a proxy model and won't be serialized." % model._meta.label, category=ProxyModelWarning, ) if not model._meta.proxy and router.allow_migrate_model(using, model): if use_base_manager: objects = model._base_manager else: objects = model._default_manager queryset = objects.using(using).order_by(model._meta.pk.name) if primary_keys: queryset = queryset.filter(pk__in=primary_keys) if count_only: yield queryset.order_by().count() else: yield from queryset.iterator() try: self.stdout.ending = None progress_output = None object_count = 0 # If dumpdata is outputting to stdout, there is no way to display progress if output and self.stdout.isatty() and options['verbosity'] > 0: progress_output = self.stdout object_count = sum(get_objects(count_only=True)) stream = open(output, 'w') if output else None try: serializers.serialize( format, get_objects(), indent=indent, use_natural_foreign_keys=use_natural_foreign_keys, use_natural_primary_keys=use_natural_primary_keys, stream=stream or self.stdout, progress_output=progress_output, object_count=object_count, ) finally: if stream: stream.close() except Exception as e: if show_traceback: raise raise CommandError("Unable to serialize database: %s" % e)
945f8e18e28336d05930241b41b1c18f2b31068ffc2afddf43ecd20de1079e71
import errno import os import re import socket import sys from datetime import datetime from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.core.servers.basehttp import ( WSGIServer, get_internal_wsgi_application, run, ) from django.utils import autoreload naiveip_re = re.compile(r"""^(?: (?P<addr> (?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) | # IPv4 address (?P<ipv6>\[[a-fA-F0-9:]+\]) | # IPv6 address (?P<fqdn>[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*) # FQDN ):)?(?P<port>\d+)$""", re.X) class Command(BaseCommand): help = "Starts a lightweight Web server for development." # Validation is called explicitly each time the server is reloaded. requires_system_checks = False stealth_options = ('shutdown_message',) default_addr = '127.0.0.1' default_addr_ipv6 = '::1' default_port = '8000' protocol = 'http' server_cls = WSGIServer def add_arguments(self, parser): parser.add_argument( 'addrport', nargs='?', help='Optional port number, or ipaddr:port' ) parser.add_argument( '--ipv6', '-6', action='store_true', dest='use_ipv6', help='Tells Django to use an IPv6 address.', ) parser.add_argument( '--nothreading', action='store_false', dest='use_threading', help='Tells Django to NOT use threading.', ) parser.add_argument( '--noreload', action='store_false', dest='use_reloader', help='Tells Django to NOT use the auto-reloader.', ) def execute(self, *args, **options): if options['no_color']: # We rely on the environment because it's currently the only # way to reach WSGIRequestHandler. This seems an acceptable # compromise considering `runserver` runs indefinitely. os.environ["DJANGO_COLORS"] = "nocolor" super().execute(*args, **options) def get_handler(self, *args, **options): """Return the default WSGI handler for the runner.""" return get_internal_wsgi_application() def handle(self, *args, **options): if not settings.DEBUG and not settings.ALLOWED_HOSTS: raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.') self.use_ipv6 = options['use_ipv6'] if self.use_ipv6 and not socket.has_ipv6: raise CommandError('Your Python does not support IPv6.') self._raw_ipv6 = False if not options['addrport']: self.addr = '' self.port = self.default_port else: m = re.match(naiveip_re, options['addrport']) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % options['addrport']) self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups() if not self.port.isdigit(): raise CommandError("%r is not a valid port number." % self.port) if self.addr: if _ipv6: self.addr = self.addr[1:-1] self.use_ipv6 = True self._raw_ipv6 = True elif self.use_ipv6 and not _fqdn: raise CommandError('"%s" is not a valid IPv6 address.' % self.addr) if not self.addr: self.addr = self.default_addr_ipv6 if self.use_ipv6 else self.default_addr self._raw_ipv6 = self.use_ipv6 self.run(**options) def run(self, **options): """Run the server, using the autoreloader if needed.""" use_reloader = options['use_reloader'] if use_reloader: autoreload.main(self.inner_run, None, options) else: self.inner_run(None, **options) def inner_run(self, *args, **options): # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() threading = options['use_threading'] # 'shutdown_message' is a stealth option. shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Performing system checks...\n\n") self.check(display_num_errors=True) # Need to check migrations here, so can't use the # requires_migrations_check attribute. self.check_migrations() now = datetime.now().strftime('%B %d, %Y - %X') self.stdout.write(now) self.stdout.write(( "Django version %(version)s, using settings %(settings)r\n" "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "protocol": self.protocol, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) except socket.error as e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { errno.EACCES: "You don't have permission to access that port.", errno.EADDRINUSE: "That port is already in use.", errno.EADDRNOTAVAIL: "That IP address can't be assigned to.", } try: error_text = ERRORS[e.errno] except KeyError: error_text = e self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0) # Kept for backward compatibility BaseRunserverCommand = Command
55ea3e53af4d504c85b8cfcef6d1bb1a3459dda476bd6cdc69559a84021d4bf3
from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import connection class Command(BaseCommand): help = 'Runs a development server with data from the given fixture(s).' requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'args', metavar='fixture', nargs='*', help='Path(s) to fixtures to load before running the server.', ) parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '--addrport', default='', help='Port number or ipaddr:port to run the server on.', ) parser.add_argument( '--ipv6', '-6', action='store_true', dest='use_ipv6', help='Tells Django to use an IPv6 address.', ) def handle(self, *fixture_labels, **options): verbosity = options['verbosity'] interactive = options['interactive'] # Create a test database. db_name = connection.creation.create_test_db(verbosity=verbosity, autoclobber=not interactive, serialize=False) # Import the fixture data into the test database. call_command('loaddata', *fixture_labels, **{'verbosity': verbosity}) # Run the development server. Turn off auto-reloading because it causes # a strange error -- it causes this handle() method to be called # multiple times. shutdown_message = ( '\nServer stopped.\nNote that the test database, %r, has not been ' 'deleted. You can explore it on your own.' % db_name ) use_threading = connection.features.test_db_allows_multiple_connections call_command( 'runserver', addrport=options['addrport'], shutdown_message=shutdown_message, use_reloader=False, use_ipv6=options['use_ipv6'], use_threading=use_threading )
ddab3eaf9fe47d2f25c3ddd23bbc5436cd76a7f20654ecc6e375132dd70c5f1f
from django.core.management.base import BaseCommand def module_to_dict(module, omittable=lambda k: k.startswith('_')): """Convert a module namespace to a Python dictionary.""" return {k: repr(v) for k, v in module.__dict__.items() if not omittable(k)} class Command(BaseCommand): help = """Displays differences between the current settings.py and Django's default settings.""" requires_system_checks = False def add_arguments(self, parser): parser.add_argument( '--all', action='store_true', dest='all', help=( 'Display all settings, regardless of their value. In "hash" ' 'mode, default values are prefixed by "###".' ), ) parser.add_argument( '--default', dest='default', metavar='MODULE', default=None, help=( "The settings module to compare the current settings against. Leave empty to " "compare against Django's default settings." ), ) parser.add_argument( '--output', default='hash', choices=('hash', 'unified'), dest='output', help=( "Selects the output format. 'hash' mode displays each changed " "setting, with the settings that don't appear in the defaults " "followed by ###. 'unified' mode prefixes the default setting " "with a minus sign, followed by the changed setting prefixed " "with a plus sign." ), ) def handle(self, **options): from django.conf import settings, Settings, global_settings # Because settings are imported lazily, we need to explicitly load them. settings._setup() user_settings = module_to_dict(settings._wrapped) default = options['default'] default_settings = module_to_dict(Settings(default) if default else global_settings) output_func = { 'hash': self.output_hash, 'unified': self.output_unified, }[options['output']] return '\n'.join(output_func(user_settings, default_settings, **options)) def output_hash(self, user_settings, default_settings, **options): # Inspired by Postfix's "postconf -n". output = [] for key in sorted(user_settings): if key not in default_settings: output.append("%s = %s ###" % (key, user_settings[key])) elif user_settings[key] != default_settings[key]: output.append("%s = %s" % (key, user_settings[key])) elif options['all']: output.append("### %s = %s" % (key, user_settings[key])) return output def output_unified(self, user_settings, default_settings, **options): output = [] for key in sorted(user_settings): if key not in default_settings: output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key]))) elif user_settings[key] != default_settings[key]: output.append(self.style.ERROR("- %s = %s" % (key, default_settings[key]))) output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key]))) elif options['all']: output.append(" %s = %s" % (key, user_settings[key])) return output
385fd5663c012ab878e77a010f26cddecd0569dd7c8349536cdd599fe21998e1
from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections, migrations from django.db.migrations.loader import AmbiguityError, MigrationLoader from django.db.migrations.migration import SwappableTuple from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.writer import MigrationWriter from django.utils.version import get_docs_version class Command(BaseCommand): help = "Squashes an existing set of migrations (from first until specified) into a single new one." def add_arguments(self, parser): parser.add_argument( 'app_label', help='App label of the application to squash migrations for.', ) parser.add_argument( 'start_migration_name', default=None, nargs='?', help='Migrations will be squashed starting from and including this migration.', ) parser.add_argument( 'migration_name', help='Migrations will be squashed until and including this migration.', ) parser.add_argument( '--no-optimize', action='store_true', dest='no_optimize', help='Do not try to optimize the squashed operations.', ) parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '--squashed-name', dest='squashed_name', help='Sets the name of the new squashed migration.', ) def handle(self, **options): self.verbosity = options['verbosity'] self.interactive = options['interactive'] app_label = options['app_label'] start_migration_name = options['start_migration_name'] migration_name = options['migration_name'] no_optimize = options['no_optimize'] squashed_name = options['squashed_name'] # Validate app_label. try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) # Load the current graph state, check the app and migration they asked for exists loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) if app_label not in loader.migrated_apps: raise CommandError( "App '%s' does not have migrations (so squashmigrations on " "it makes no sense)" % app_label ) migration = self.find_migration(loader, app_label, migration_name) # Work out the list of predecessor migrations migrations_to_squash = [ loader.get_migration(al, mn) for al, mn in loader.graph.forwards_plan((migration.app_label, migration.name)) if al == migration.app_label ] if start_migration_name: start_migration = self.find_migration(loader, app_label, start_migration_name) start = loader.get_migration(start_migration.app_label, start_migration.name) try: start_index = migrations_to_squash.index(start) migrations_to_squash = migrations_to_squash[start_index:] except ValueError: raise CommandError( "The migration '%s' cannot be found. Maybe it comes after " "the migration '%s'?\n" "Have a look at:\n" " python manage.py showmigrations %s\n" "to debug this issue." % (start_migration, migration, app_label) ) # Tell them what we're doing and optionally ask if we should proceed if self.verbosity > 0 or self.interactive: self.stdout.write(self.style.MIGRATE_HEADING("Will squash the following migrations:")) for migration in migrations_to_squash: self.stdout.write(" - %s" % migration.name) if self.interactive: answer = None while not answer or answer not in "yn": answer = input("Do you wish to proceed? [yN] ") if not answer: answer = "n" break else: answer = answer[0].lower() if answer != "y": return # Load the operations from all those migrations and concat together, # along with collecting external dependencies and detecting # double-squashing operations = [] dependencies = set() # We need to take all dependencies from the first migration in the list # as it may be 0002 depending on 0001 first_migration = True for smigration in migrations_to_squash: if smigration.replaces: raise CommandError( "You cannot squash squashed migrations! Please transition " "it to a normal migration first: " "https://docs.djangoproject.com/en/%s/topics/migrations/#squashing-migrations" % get_docs_version() ) operations.extend(smigration.operations) for dependency in smigration.dependencies: if isinstance(dependency, SwappableTuple): if settings.AUTH_USER_MODEL == dependency.setting: dependencies.add(("__setting__", "AUTH_USER_MODEL")) else: dependencies.add(dependency) elif dependency[0] != smigration.app_label or first_migration: dependencies.add(dependency) first_migration = False if no_optimize: if self.verbosity > 0: self.stdout.write(self.style.MIGRATE_HEADING("(Skipping optimization.)")) new_operations = operations else: if self.verbosity > 0: self.stdout.write(self.style.MIGRATE_HEADING("Optimizing...")) optimizer = MigrationOptimizer() new_operations = optimizer.optimize(operations, migration.app_label) if self.verbosity > 0: if len(new_operations) == len(operations): self.stdout.write(" No optimizations possible.") else: self.stdout.write( " Optimized from %s operations to %s operations." % (len(operations), len(new_operations)) ) # Work out the value of replaces (any squashed ones we're re-squashing) # need to feed their replaces into ours replaces = [] for migration in migrations_to_squash: if migration.replaces: replaces.extend(migration.replaces) else: replaces.append((migration.app_label, migration.name)) # Make a new migration with those operations subclass = type("Migration", (migrations.Migration,), { "dependencies": dependencies, "operations": new_operations, "replaces": replaces, }) if start_migration_name: if squashed_name: # Use the name from --squashed-name. prefix, _ = start_migration.name.split('_', 1) name = '%s_%s' % (prefix, squashed_name) else: # Generate a name. name = '%s_squashed_%s' % (start_migration.name, migration.name) new_migration = subclass(name, app_label) else: name = '0001_%s' % (squashed_name or 'squashed_%s' % migration.name) new_migration = subclass(name, app_label) new_migration.initial = True # Write out the new migration file writer = MigrationWriter(new_migration) with open(writer.path, "w", encoding='utf-8') as fh: fh.write(writer.as_string()) if self.verbosity > 0: self.stdout.write(self.style.MIGRATE_HEADING("Created new squashed migration %s" % writer.path)) self.stdout.write(" You should commit this migration but leave the old ones in place;") self.stdout.write(" the new migration will be used for new installs. Once you are sure") self.stdout.write(" all instances of the codebase have applied the migrations you squashed,") self.stdout.write(" you can delete them.") if writer.needs_manual_porting: self.stdout.write(self.style.MIGRATE_HEADING("Manual porting required")) self.stdout.write(" Your migrations contained functions that must be manually copied over,") self.stdout.write(" as we could not safely copy their implementation.") self.stdout.write(" See the comment at the top of the squashed migration for details.") def find_migration(self, loader, app_label, name): try: return loader.get_migration_by_prefix(app_label, name) except AmbiguityError: raise CommandError( "More than one migration matches '%s' in app '%s'. Please be " "more specific." % (name, app_label) ) except KeyError: raise CommandError( "Cannot find a migration matching '%s' from app '%s'." % (name, app_label) )
b9a5ab4c204ca418d1a64018b38c00a2da769fba3a4b5374f4cb1eafa120ba5c
import codecs import concurrent.futures import glob import os from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import find_command, popen_wrapper def has_bom(fn): with open(fn, 'rb') as f: sample = f.read(4) return sample.startswith((codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)) def is_writable(path): # Known side effect: updating file access/modified time to current time if # it is writable. try: with open(path, 'a'): os.utime(path, None) except (IOError, OSError): return False return True class Command(BaseCommand): help = 'Compiles .po files to .mo files for use with builtin gettext support.' requires_system_checks = False program = 'msgfmt' program_options = ['--check-format'] def add_arguments(self, parser): parser.add_argument( '--locale', '-l', dest='locale', action='append', default=[], help='Locale(s) to process (e.g. de_AT). Default is to process all. ' 'Can be used multiple times.', ) parser.add_argument( '--exclude', '-x', dest='exclude', action='append', default=[], help='Locales to exclude. Default is none. Can be used multiple times.', ) parser.add_argument( '--use-fuzzy', '-f', dest='fuzzy', action='store_true', help='Use fuzzy translations.', ) def handle(self, **options): locale = options['locale'] exclude = options['exclude'] self.verbosity = options['verbosity'] if options['fuzzy']: self.program_options = self.program_options + ['-f'] if find_command(self.program) is None: raise CommandError("Can't find %s. Make sure you have GNU gettext " "tools 0.15 or newer installed." % self.program) basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings basedirs.extend(settings.LOCALE_PATHS) # Walk entire tree, looking for locale directories for dirpath, dirnames, filenames in os.walk('.', topdown=True): for dirname in dirnames: if dirname == 'locale': basedirs.append(os.path.join(dirpath, dirname)) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError("This script should be run from the Django Git " "checkout or your project or app tree, or with " "the settings module specified.") # Build locale list all_locales = [] for basedir in basedirs: locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % basedir)) all_locales.extend(map(os.path.basename, locale_dirs)) # Account for excluded locales locales = locale or all_locales locales = set(locales).difference(exclude) self.has_errors = False for basedir in basedirs: if locales: dirs = [os.path.join(basedir, l, 'LC_MESSAGES') for l in locales] else: dirs = [basedir] locations = [] for ldir in dirs: for dirpath, dirnames, filenames in os.walk(ldir): locations.extend((dirpath, f) for f in filenames if f.endswith('.po')) if locations: self.compile_messages(locations) if self.has_errors: raise CommandError('compilemessages generated one or more errors.') def compile_messages(self, locations): """ Locations is a list of tuples: [(directory, file), ...] """ with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for i, (dirpath, f) in enumerate(locations): if self.verbosity > 0: self.stdout.write('processing file %s in %s\n' % (f, dirpath)) po_path = os.path.join(dirpath, f) if has_bom(po_path): self.stderr.write( 'The %s file has a BOM (Byte Order Mark). Django only ' 'supports .po files encoded in UTF-8 and without any BOM.' % po_path ) self.has_errors = True continue base_path = os.path.splitext(po_path)[0] # Check writability on first location if i == 0 and not is_writable(base_path + '.mo'): self.stderr.write( 'The po files under %s are in a seemingly not writable location. ' 'mo files will not be updated/created.' % dirpath ) self.has_errors = True return args = [self.program] + self.program_options + [ '-o', base_path + '.mo', base_path + '.po' ] futures.append(executor.submit(popen_wrapper, args)) for future in concurrent.futures.as_completed(futures): output, errors, status = future.result() if status: if self.verbosity > 0: if errors: self.stderr.write("Execution of %s failed: %s" % (self.program, errors)) else: self.stderr.write("Execution of %s failed" % self.program) self.has_errors = True
98dc6a481a7e7c5dfa87724cb44b03bd8cc2cacc43039474223872898c833222
from django.core.management.base import BaseCommand from django.core.management.sql import sql_flush from django.db import DEFAULT_DB_ALIAS, connections class Command(BaseCommand): help = ( "Returns a list of the SQL statements required to return all tables in " "the database to the state they were in just after they were installed." ) output_transaction = True def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( '--database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the SQL for. Defaults to the "default" database.', ) def handle(self, **options): return '\n'.join(sql_flush(self.style, connections[options['database']], only_django=True))
aaebcdaa6d257e5defbc37cbd12d2906d5b5b5eecb19c60d52bada73894c0008
import socket from django.core.mail import mail_admins, mail_managers, send_mail from django.core.management.base import BaseCommand from django.utils import timezone class Command(BaseCommand): help = "Sends a test email to the email addresses specified as arguments." missing_args_message = "You must specify some email recipients, or pass the --managers or --admin options." def add_arguments(self, parser): parser.add_argument( 'email', nargs='*', help='One or more email addresses to send a test email to.', ) parser.add_argument( '--managers', action='store_true', dest='managers', help='Send a test email to the addresses specified in settings.MANAGERS.', ) parser.add_argument( '--admins', action='store_true', dest='admins', help='Send a test email to the addresses specified in settings.ADMINS.', ) def handle(self, *args, **kwargs): subject = 'Test email from %s on %s' % (socket.gethostname(), timezone.now()) send_mail( subject=subject, message="If you\'re reading this, it was successful.", from_email=None, recipient_list=kwargs['email'], ) if kwargs['managers']: mail_managers(subject, "This email was sent to the site managers.") if kwargs['admins']: mail_admins(subject, "This email was sent to the site admins.")
5aa91117f39c7fa5bbbae395dc2e18b11ca41a6ba90bcc51b5f35440ca94c306
import functools import glob import gzip import os import sys import warnings import zipfile from itertools import product from django.apps import apps from django.conf import settings from django.core import serializers from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.core.management.utils import parse_apps_and_model_labels from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connections, router, transaction, ) from django.utils.functional import cached_property try: import bz2 has_bz2 = True except ImportError: has_bz2 = False READ_STDIN = '-' class Command(BaseCommand): help = 'Installs the named fixture(s) in the database.' missing_args_message = ( "No database fixture specified. Please provide the path of at least " "one fixture in the command line." ) def add_arguments(self, parser): parser.add_argument('args', metavar='fixture', nargs='+', help='Fixture labels.') parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load fixtures into. Defaults to the "default" database.', ) parser.add_argument( '--app', action='store', dest='app_label', default=None, help='Only look for fixtures in the specified app.', ) parser.add_argument( '--ignorenonexistent', '-i', action='store_true', dest='ignore', help='Ignores entries in the serialized data for fields that do not ' 'currently exist on the model.', ) parser.add_argument( '-e', '--exclude', dest='exclude', action='append', default=[], help='An app_label or app_label.ModelName to exclude. Can be used multiple times.', ) parser.add_argument( '--format', action='store', dest='format', default=None, help='Format of serialized data when reading from stdin.', ) def handle(self, *fixture_labels, **options): self.ignore = options['ignore'] self.using = options['database'] self.app_label = options['app_label'] self.verbosity = options['verbosity'] self.excluded_models, self.excluded_apps = parse_apps_and_model_labels(options['exclude']) self.format = options['format'] with transaction.atomic(using=self.using): self.loaddata(fixture_labels) # Close the DB connection -- unless we're still in a transaction. This # is required as a workaround for an edge case in MySQL: if the same # connection is used to create tables, load data, and query, the query # can return incorrect results. See Django #7572, MySQL #37735. if transaction.get_autocommit(self.using): connections[self.using].close() def loaddata(self, fixture_labels): connection = connections[self.using] # Keep a count of the installed objects and fixtures self.fixture_count = 0 self.loaded_object_count = 0 self.fixture_object_count = 0 self.models = set() self.serialization_formats = serializers.get_public_serializer_formats() # Forcing binary mode may be revisited after dropping Python 2 support (see #22399) self.compression_formats = { None: (open, 'rb'), 'gz': (gzip.GzipFile, 'rb'), 'zip': (SingleZipReader, 'r'), 'stdin': (lambda *args: sys.stdin, None), } if has_bz2: self.compression_formats['bz2'] = (bz2.BZ2File, 'r') # Django's test suite repeatedly tries to load initial_data fixtures # from apps that don't have any fixtures. Because disabling constraint # checks can be expensive on some database (especially MSSQL), bail # out early if no fixtures are found. for fixture_label in fixture_labels: if self.find_fixtures(fixture_label): break else: return with connection.constraint_checks_disabled(): for fixture_label in fixture_labels: self.load_label(fixture_label) # Since we disabled constraint checks, we must manually check for # any invalid keys that might have been added table_names = [model._meta.db_table for model in self.models] try: connection.check_constraints(table_names=table_names) except Exception as e: e.args = ("Problem installing fixtures: %s" % e,) raise # If we found even one object in a fixture, we need to reset the # database sequences. if self.loaded_object_count > 0: sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models) if sequence_sql: if self.verbosity >= 2: self.stdout.write("Resetting sequences\n") with connection.cursor() as cursor: for line in sequence_sql: cursor.execute(line) if self.verbosity >= 1: if self.fixture_object_count == self.loaded_object_count: self.stdout.write( "Installed %d object(s) from %d fixture(s)" % (self.loaded_object_count, self.fixture_count) ) else: self.stdout.write( "Installed %d object(s) (of %d) from %d fixture(s)" % (self.loaded_object_count, self.fixture_object_count, self.fixture_count) ) def load_label(self, fixture_label): """Load fixtures files for a given label.""" show_progress = self.verbosity >= 3 for fixture_file, fixture_dir, fixture_name in self.find_fixtures(fixture_label): _, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file)) open_method, mode = self.compression_formats[cmp_fmt] fixture = open_method(fixture_file, mode) try: self.fixture_count += 1 objects_in_fixture = 0 loaded_objects_in_fixture = 0 if self.verbosity >= 2: self.stdout.write( "Installing %s fixture '%s' from %s." % (ser_fmt, fixture_name, humanize(fixture_dir)) ) objects = serializers.deserialize( ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore, ) for obj in objects: objects_in_fixture += 1 if (obj.object._meta.app_config in self.excluded_apps or type(obj.object) in self.excluded_models): continue if router.allow_migrate_model(self.using, obj.object.__class__): loaded_objects_in_fixture += 1 self.models.add(obj.object.__class__) try: obj.save(using=self.using) if show_progress: self.stdout.write( '\rProcessed %i object(s).' % loaded_objects_in_fixture, ending='' ) # psycopg2 raises ValueError if data contains NUL chars. except (DatabaseError, IntegrityError, ValueError) as e: e.args = ("Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % { 'app_label': obj.object._meta.app_label, 'object_name': obj.object._meta.object_name, 'pk': obj.object.pk, 'error_msg': e, },) raise if objects and show_progress: self.stdout.write('') # add a newline after progress indicator self.loaded_object_count += loaded_objects_in_fixture self.fixture_object_count += objects_in_fixture except Exception as e: if not isinstance(e, CommandError): e.args = ("Problem installing fixture '%s': %s" % (fixture_file, e),) raise finally: fixture.close() # Warn if the fixture we loaded contains 0 objects. if objects_in_fixture == 0: warnings.warn( "No fixture data found for '%s'. (File format may be " "invalid.)" % fixture_name, RuntimeWarning ) @functools.lru_cache(maxsize=None) def find_fixtures(self, fixture_label): """Find fixture files for a given label.""" if fixture_label == READ_STDIN: return [(READ_STDIN, None, READ_STDIN)] fixture_name, ser_fmt, cmp_fmt = self.parse_name(fixture_label) databases = [self.using, None] cmp_fmts = list(self.compression_formats) if cmp_fmt is None else [cmp_fmt] ser_fmts = serializers.get_public_serializer_formats() if ser_fmt is None else [ser_fmt] if self.verbosity >= 2: self.stdout.write("Loading '%s' fixtures..." % fixture_name) if os.path.isabs(fixture_name): fixture_dirs = [os.path.dirname(fixture_name)] fixture_name = os.path.basename(fixture_name) else: fixture_dirs = self.fixture_dirs if os.path.sep in os.path.normpath(fixture_name): fixture_dirs = [os.path.join(dir_, os.path.dirname(fixture_name)) for dir_ in fixture_dirs] fixture_name = os.path.basename(fixture_name) suffixes = ( '.'.join(ext for ext in combo if ext) for combo in product(databases, ser_fmts, cmp_fmts) ) targets = {'.'.join((fixture_name, suffix)) for suffix in suffixes} fixture_files = [] for fixture_dir in fixture_dirs: if self.verbosity >= 2: self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir)) fixture_files_in_dir = [] path = os.path.join(fixture_dir, fixture_name) for candidate in glob.iglob(glob.escape(path) + '*'): if os.path.basename(candidate) in targets: # Save the fixture_dir and fixture_name for future error messages. fixture_files_in_dir.append((candidate, fixture_dir, fixture_name)) if self.verbosity >= 2 and not fixture_files_in_dir: self.stdout.write("No fixture '%s' in %s." % (fixture_name, humanize(fixture_dir))) # Check kept for backwards-compatibility; it isn't clear why # duplicates are only allowed in different directories. if len(fixture_files_in_dir) > 1: raise CommandError( "Multiple fixtures named '%s' in %s. Aborting." % (fixture_name, humanize(fixture_dir))) fixture_files.extend(fixture_files_in_dir) if not fixture_files: raise CommandError("No fixture named '%s' found." % fixture_name) return fixture_files @cached_property def fixture_dirs(self): """ Return a list of fixture directories. The list contains the 'fixtures' subdirectory of each installed application, if it exists, the directories in FIXTURE_DIRS, and the current directory. """ dirs = [] fixture_dirs = settings.FIXTURE_DIRS if len(fixture_dirs) != len(set(fixture_dirs)): raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.") for app_config in apps.get_app_configs(): app_label = app_config.label app_dir = os.path.join(app_config.path, 'fixtures') if app_dir in fixture_dirs: raise ImproperlyConfigured( "'%s' is a default fixture directory for the '%s' app " "and cannot be listed in settings.FIXTURE_DIRS." % (app_dir, app_label) ) if self.app_label and app_label != self.app_label: continue if os.path.isdir(app_dir): dirs.append(app_dir) dirs.extend(list(fixture_dirs)) dirs.append('') dirs = [os.path.abspath(os.path.realpath(d)) for d in dirs] return dirs def parse_name(self, fixture_name): """ Split fixture name in name, serialization format, compression format. """ if fixture_name == READ_STDIN: if not self.format: raise CommandError('--format must be specified when reading from stdin.') return READ_STDIN, self.format, 'stdin' parts = fixture_name.rsplit('.', 2) if len(parts) > 1 and parts[-1] in self.compression_formats: cmp_fmt = parts[-1] parts = parts[:-1] else: cmp_fmt = None if len(parts) > 1: if parts[-1] in self.serialization_formats: ser_fmt = parts[-1] parts = parts[:-1] else: raise CommandError( "Problem installing fixture '%s': %s is not a known " "serialization format." % (''.join(parts[:-1]), parts[-1])) else: ser_fmt = None name = '.'.join(parts) return name, ser_fmt, cmp_fmt class SingleZipReader(zipfile.ZipFile): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if len(self.namelist()) != 1: raise ValueError("Zip-compressed fixtures must contain one file.") def read(self): return zipfile.ZipFile.read(self, self.namelist()[0]) def humanize(dirname): return "'%s'" % dirname if dirname else 'absolute path'
aef5c0a662dd3f78018a729a38c26d4f583762b8154e51ed7aa36a162a0dbbc6
from django.core.management.templates import TemplateCommand class Command(TemplateCommand): help = ( "Creates a Django app directory structure for the given app name in " "the current directory or optionally in the given directory." ) missing_args_message = "You must provide an application name." def handle(self, **options): app_name = options.pop('name') target = options.pop('directory') super().handle('app', app_name, target, **options)
ca03fde59125768b601159b10d804f53201e74d4134f026e94a2e29c653166d8
from django.core.management.templates import TemplateCommand from ..utils import get_random_secret_key class Command(TemplateCommand): help = ( "Creates a Django project directory structure for the given project " "name in the current directory or optionally in the given directory." ) missing_args_message = "You must provide a project name." def handle(self, **options): project_name = options.pop('name') target = options.pop('directory') # Create a random SECRET_KEY to put it in the main settings. options['secret_key'] = get_random_secret_key() super().handle('project', project_name, target, **options)
1530939b4112c68cd056977ea8c806c6f2188c9bb59bdeaeab923028542d7e17
import sys from django.conf import settings from django.core.management.base import BaseCommand from django.test.utils import get_runner class Command(BaseCommand): help = 'Discover and run tests in the specified modules or the current directory.' # DiscoverRunner runs the checks after databases are set up. requires_system_checks = False test_runner = None def run_from_argv(self, argv): """ Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments. """ option = '--testrunner=' for arg in argv[2:]: if arg.startswith(option): self.test_runner = arg[len(option):] break super().run_from_argv(argv) def add_arguments(self, parser): parser.add_argument( 'args', metavar='test_label', nargs='*', help='Module paths to test; can be modulename, modulename.TestCase or modulename.TestCase.test_method' ) parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '--failfast', action='store_true', dest='failfast', help='Tells Django to stop running the test suite after first failed test.', ) parser.add_argument( '--testrunner', action='store', dest='testrunner', help='Tells Django to use specified test runner class instead of ' 'the one specified by the TEST_RUNNER setting.', ) test_runner_class = get_runner(settings, self.test_runner) if hasattr(test_runner_class, 'add_arguments'): test_runner_class.add_arguments(parser) def handle(self, *test_labels, **options): TestRunner = get_runner(settings, options['testrunner']) test_runner = TestRunner(**options) failures = test_runner.run_tests(test_labels) if failures: sys.exit(1)
086fa22b8fdf60646e5dcbdd854ed1de2bdcbd6eae36660d204c7e09095cf89a
from django.conf import settings from django.core.cache import caches from django.core.cache.backends.db import BaseDatabaseCache from django.core.management.base import BaseCommand, CommandError from django.db import ( DEFAULT_DB_ALIAS, connections, models, router, transaction, ) from django.db.utils import DatabaseError class Command(BaseCommand): help = "Creates the tables needed to use the SQL cache backend." requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'args', metavar='table_name', nargs='*', help='Optional table names. Otherwise, settings.CACHES is used to find cache tables.', ) parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database onto which the cache tables will be ' 'installed. Defaults to the "default" database.', ) parser.add_argument( '--dry-run', action='store_true', dest='dry_run', help='Does not create the table, just prints the SQL that would be run.', ) def handle(self, *tablenames, **options): db = options['database'] self.verbosity = options['verbosity'] dry_run = options['dry_run'] if tablenames: # Legacy behavior, tablename specified as argument for tablename in tablenames: self.create_table(db, tablename, dry_run) else: for cache_alias in settings.CACHES: cache = caches[cache_alias] if isinstance(cache, BaseDatabaseCache): self.create_table(db, cache._table, dry_run) def create_table(self, database, tablename, dry_run): cache = BaseDatabaseCache(tablename, {}) if not router.allow_migrate_model(database, cache.cache_model_class): return connection = connections[database] if tablename in connection.introspection.table_names(): if self.verbosity > 0: self.stdout.write("Cache table '%s' already exists." % tablename) return fields = ( # "key" is a reserved word in MySQL, so use "cache_key" instead. models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True), models.TextField(name='value'), models.DateTimeField(name='expires', db_index=True), ) table_output = [] index_output = [] qn = connection.ops.quote_name for f in fields: field_output = [ qn(f.name), f.db_type(connection=connection), '%sNULL' % ('NOT ' if not f.null else ''), ] if f.primary_key: field_output.append("PRIMARY KEY") elif f.unique: field_output.append("UNIQUE") if f.db_index: unique = "UNIQUE " if f.unique else "" index_output.append( "CREATE %sINDEX %s ON %s (%s);" % (unique, qn('%s_%s' % (tablename, f.name)), qn(tablename), qn(f.name)) ) table_output.append(" ".join(field_output)) full_statement = ["CREATE TABLE %s (" % qn(tablename)] for i, line in enumerate(table_output): full_statement.append(' %s%s' % (line, ',' if i < len(table_output) - 1 else '')) full_statement.append(');') full_statement = "\n".join(full_statement) if dry_run: self.stdout.write(full_statement) for statement in index_output: self.stdout.write(statement) return with transaction.atomic(using=database, savepoint=connection.features.can_rollback_ddl): with connection.cursor() as curs: try: curs.execute(full_statement) except DatabaseError as e: raise CommandError( "Cache table '%s' could not be created.\nThe error was: %s." % (tablename, e)) for statement in index_output: curs.execute(statement) if self.verbosity > 1: self.stdout.write("Cache table '%s' created." % tablename)
39e7b105025711402b38a5862a9052b1a034e375f552893335673f1036c98b93
from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections class Command(BaseCommand): help = ( "Runs the command-line client for specified database, or the " "default database if none is provided." ) requires_system_checks = False def add_arguments(self, parser): parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database onto which to open a shell. Defaults to the "default" database.', ) def handle(self, **options): connection = connections[options['database']] try: connection.client.runshell() except OSError: # Note that we're assuming OSError means that the client program # isn't installed. There's a possibility OSError would be raised # for some other reason, in which case this error message would be # inaccurate. Still, this message catches the common case. raise CommandError( 'You appear not to have the %r program installed or on your path.' % connection.client.executable_name )
1b8a45beb626434ba520253f4cbfe5f06c9da99b57b70069b8d88ee7d1a25e53
import fnmatch import glob import os import re import sys from functools import total_ordering from itertools import dropwhile import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.temp import NamedTemporaryFile from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import ( find_command, handle_extensions, popen_wrapper, ) from django.utils.encoding import DEFAULT_LOCALE_ENCODING from django.utils.functional import cached_property from django.utils.jslex import prepare_js_for_gettext from django.utils.text import get_text_list from django.utils.translation import templatize plural_forms_re = re.compile(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL) STATUS_OK = 0 NO_LOCALE_DIR = object() def check_programs(*programs): for program in programs: if find_command(program) is None: raise CommandError( "Can't find %s. Make sure you have GNU gettext tools 0.15 or " "newer installed." % program ) @total_ordering class TranslatableFile: def __init__(self, dirpath, file_name, locale_dir): self.file = file_name self.dirpath = dirpath self.locale_dir = locale_dir def __repr__(self): return "<%s: %s>" % ( self.__class__.__name__, os.sep.join([self.dirpath, self.file]), ) def __eq__(self, other): return self.path == other.path def __lt__(self, other): return self.path < other.path @property def path(self): return os.path.join(self.dirpath, self.file) class BuildFile: """ Represent the state of a translatable file during the build process. """ def __init__(self, command, domain, translatable): self.command = command self.domain = domain self.translatable = translatable @cached_property def is_templatized(self): if self.domain == 'djangojs': return self.command.gettext_version < (0, 18, 3) elif self.domain == 'django': file_ext = os.path.splitext(self.translatable.file)[1] return file_ext != '.py' return False @cached_property def path(self): return self.translatable.path @cached_property def work_path(self): """ Path to a file which is being fed into GNU gettext pipeline. This may be either a translatable or its preprocessed version. """ if not self.is_templatized: return self.path extension = { 'djangojs': 'c', 'django': 'py', }.get(self.domain) filename = '%s.%s' % (self.translatable.file, extension) return os.path.join(self.translatable.dirpath, filename) def preprocess(self): """ Preprocess (if necessary) a translatable file before passing it to xgettext GNU gettext utility. """ if not self.is_templatized: return encoding = settings.FILE_CHARSET if self.command.settings_available else 'utf-8' with open(self.path, 'r', encoding=encoding) as fp: src_data = fp.read() if self.domain == 'djangojs': content = prepare_js_for_gettext(src_data) elif self.domain == 'django': content = templatize(src_data, origin=self.path[2:]) with open(self.work_path, 'w', encoding='utf-8') as fp: fp.write(content) def postprocess_messages(self, msgs): """ Postprocess messages generated by xgettext GNU gettext utility. Transform paths as if these messages were generated from original translatable files rather than from preprocessed versions. """ if not self.is_templatized: return msgs # Remove '.py' suffix if os.name == 'nt': # Preserve '.\' prefix on Windows to respect gettext behavior old_path = self.work_path new_path = self.path else: old_path = self.work_path[2:] new_path = self.path[2:] return re.sub( r'^(#: .*)(' + re.escape(old_path) + r')', lambda match: match.group().replace(old_path, new_path), msgs, flags=re.MULTILINE ) def cleanup(self): """ Remove a preprocessed copy of a translatable file (if any). """ if self.is_templatized: # This check is needed for the case of a symlinked file and its # source being processed inside a single group (locale dir); # removing either of those two removes both. if os.path.exists(self.work_path): os.unlink(self.work_path) def normalize_eols(raw_contents): """ Take a block of raw text that will be passed through str.splitlines() to get universal newlines treatment. Return the resulting block of text with normalized `\n` EOL sequences ready to be written to disk using current platform's native EOLs. """ lines_list = raw_contents.splitlines() # Ensure last line has its EOL if lines_list and lines_list[-1]: lines_list.append('') return '\n'.join(lines_list) def write_pot_file(potfile, msgs): """ Write the `potfile` with the `msgs` contents, making sure its format is valid. """ pot_lines = msgs.splitlines() if os.path.exists(potfile): # Strip the header lines = dropwhile(len, pot_lines) else: lines = [] found, header_read = False, False for line in pot_lines: if not found and not header_read: if 'charset=CHARSET' in line: found = True line = line.replace('charset=CHARSET', 'charset=UTF-8') if not line and not found: header_read = True lines.append(line) msgs = '\n'.join(lines) # Force newlines of POT files to '\n' to work around # https://savannah.gnu.org/bugs/index.php?52395 with open(potfile, 'a', encoding='utf-8', newline='\n') as fp: fp.write(msgs) class Command(BaseCommand): help = ( "Runs over the entire source tree of the current directory and " "pulls out all strings marked for translation. It creates (or updates) a message " "file in the conf/locale (in the django tree) or locale (for projects and " "applications) directory.\n\nYou must run this command with one of either the " "--locale, --exclude, or --all options." ) translatable_file_class = TranslatableFile build_file_class = BuildFile requires_system_checks = False msgmerge_options = ['-q', '--previous'] msguniq_options = ['--to-code=utf-8'] msgattrib_options = ['--no-obsolete'] xgettext_options = ['--from-code=UTF-8', '--add-comments=Translators'] def add_arguments(self, parser): parser.add_argument( '--locale', '-l', default=[], dest='locale', action='append', help='Creates or updates the message files for the given locale(s) (e.g. pt_BR). ' 'Can be used multiple times.', ) parser.add_argument( '--exclude', '-x', default=[], dest='exclude', action='append', help='Locales to exclude. Default is none. Can be used multiple times.', ) parser.add_argument( '--domain', '-d', default='django', dest='domain', help='The domain of the message files (default: "django").', ) parser.add_argument( '--all', '-a', action='store_true', dest='all', help='Updates the message files for all existing locales.', ) parser.add_argument( '--extension', '-e', dest='extensions', action='append', help='The file extension(s) to examine (default: "html,txt,py", or "js" ' 'if the domain is "djangojs"). Separate multiple extensions with ' 'commas, or use -e multiple times.', ) parser.add_argument( '--symlinks', '-s', action='store_true', dest='symlinks', help='Follows symlinks to directories when examining source code ' 'and templates for translation strings.', ) parser.add_argument( '--ignore', '-i', action='append', dest='ignore_patterns', default=[], metavar='PATTERN', help='Ignore files or directories matching this glob-style pattern. ' 'Use multiple times to ignore more.', ) parser.add_argument( '--no-default-ignore', action='store_false', dest='use_default_ignore_patterns', help="Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and '*.pyc'.", ) parser.add_argument( '--no-wrap', action='store_true', dest='no_wrap', help="Don't break long message lines into several lines.", ) parser.add_argument( '--no-location', action='store_true', dest='no_location', help="Don't write '#: filename:line' lines.", ) parser.add_argument( '--add-location', dest='add_location', choices=('full', 'file', 'never'), const='full', nargs='?', help=( "Controls '#: filename:line' lines. If the option is 'full' " "(the default if not given), the lines include both file name " "and line number. If it's 'file', the line number is omitted. If " "it's 'never', the lines are suppressed (same as --no-location). " "--add-location requires gettext 0.19 or newer." ), ) parser.add_argument( '--no-obsolete', action='store_true', dest='no_obsolete', help="Remove obsolete message strings.", ) parser.add_argument( '--keep-pot', action='store_true', dest='keep_pot', help="Keep .pot file after making messages. Useful when debugging.", ) def handle(self, *args, **options): locale = options['locale'] exclude = options['exclude'] self.domain = options['domain'] self.verbosity = options['verbosity'] process_all = options['all'] extensions = options['extensions'] self.symlinks = options['symlinks'] ignore_patterns = options['ignore_patterns'] if options['use_default_ignore_patterns']: ignore_patterns += ['CVS', '.*', '*~', '*.pyc'] self.ignore_patterns = list(set(ignore_patterns)) # Avoid messing with mutable class variables if options['no_wrap']: self.msgmerge_options = self.msgmerge_options[:] + ['--no-wrap'] self.msguniq_options = self.msguniq_options[:] + ['--no-wrap'] self.msgattrib_options = self.msgattrib_options[:] + ['--no-wrap'] self.xgettext_options = self.xgettext_options[:] + ['--no-wrap'] if options['no_location']: self.msgmerge_options = self.msgmerge_options[:] + ['--no-location'] self.msguniq_options = self.msguniq_options[:] + ['--no-location'] self.msgattrib_options = self.msgattrib_options[:] + ['--no-location'] self.xgettext_options = self.xgettext_options[:] + ['--no-location'] if options['add_location']: if self.gettext_version < (0, 19): raise CommandError( "The --add-location option requires gettext 0.19 or later. " "You have %s." % '.'.join(str(x) for x in self.gettext_version) ) arg_add_location = "--add-location=%s" % options['add_location'] self.msgmerge_options = self.msgmerge_options[:] + [arg_add_location] self.msguniq_options = self.msguniq_options[:] + [arg_add_location] self.msgattrib_options = self.msgattrib_options[:] + [arg_add_location] self.xgettext_options = self.xgettext_options[:] + [arg_add_location] self.no_obsolete = options['no_obsolete'] self.keep_pot = options['keep_pot'] if self.domain not in ('django', 'djangojs'): raise CommandError("currently makemessages only supports domains " "'django' and 'djangojs'") if self.domain == 'djangojs': exts = extensions or ['js'] else: exts = extensions or ['html', 'txt', 'py'] self.extensions = handle_extensions(exts) if (locale is None and not exclude and not process_all) or self.domain is None: raise CommandError( "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1]) ) if self.verbosity > 1: self.stdout.write( 'examining files with the extensions: %s\n' % get_text_list(list(self.extensions), 'and') ) self.invoked_for_django = False self.locale_paths = [] self.default_locale_path = None if os.path.isdir(os.path.join('conf', 'locale')): self.locale_paths = [os.path.abspath(os.path.join('conf', 'locale'))] self.default_locale_path = self.locale_paths[0] self.invoked_for_django = True else: if self.settings_available: self.locale_paths.extend(settings.LOCALE_PATHS) # Allow to run makemessages inside an app dir if os.path.isdir('locale'): self.locale_paths.append(os.path.abspath('locale')) if self.locale_paths: self.default_locale_path = self.locale_paths[0] if not os.path.exists(self.default_locale_path): os.makedirs(self.default_locale_path) # Build locale list looks_like_locale = re.compile(r'[a-z]{2}') locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % self.default_locale_path)) all_locales = [ lang_code for lang_code in map(os.path.basename, locale_dirs) if looks_like_locale.match(lang_code) ] # Account for excluded locales if process_all: locales = all_locales else: locales = locale or all_locales locales = set(locales).difference(exclude) if locales: check_programs('msguniq', 'msgmerge', 'msgattrib') check_programs('xgettext') try: potfiles = self.build_potfiles() # Build po files for each selected locale for locale in locales: if self.verbosity > 0: self.stdout.write("processing locale %s\n" % locale) for potfile in potfiles: self.write_po_file(potfile, locale) finally: if not self.keep_pot: self.remove_potfiles() @cached_property def gettext_version(self): # Gettext tools will output system-encoded bytestrings instead of UTF-8, # when looking up the version. It's especially a problem on Windows. out, err, status = popen_wrapper( ['xgettext', '--version'], stdout_encoding=DEFAULT_LOCALE_ENCODING, ) m = re.search(r'(\d+)\.(\d+)\.?(\d+)?', out) if m: return tuple(int(d) for d in m.groups() if d is not None) else: raise CommandError("Unable to get gettext version. Is it installed?") @cached_property def settings_available(self): try: settings.LOCALE_PATHS except ImproperlyConfigured: if self.verbosity > 1: self.stderr.write("Running without configured settings.") return False return True def build_potfiles(self): """ Build pot files and apply msguniq to them. """ file_list = self.find_files(".") self.remove_potfiles() self.process_files(file_list) potfiles = [] for path in self.locale_paths: potfile = os.path.join(path, '%s.pot' % self.domain) if not os.path.exists(potfile): continue args = ['msguniq'] + self.msguniq_options + [potfile] msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msguniq\n%s" % errors) elif self.verbosity > 0: self.stdout.write(errors) msgs = normalize_eols(msgs) with open(potfile, 'w', encoding='utf-8') as fp: fp.write(msgs) potfiles.append(potfile) return potfiles def remove_potfiles(self): for path in self.locale_paths: pot_path = os.path.join(path, '%s.pot' % self.domain) if os.path.exists(pot_path): os.unlink(pot_path) def find_files(self, root): """ Get all files in the given root. Also check that there is a matching locale dir for each file. """ def is_ignored(path, ignore_patterns): """ Check if the given path should be ignored or not. """ filename = os.path.basename(path) def ignore(pattern): return fnmatch.fnmatchcase(filename, pattern) or fnmatch.fnmatchcase(path, pattern) return any(ignore(pattern) for pattern in ignore_patterns) ignore_patterns = [os.path.normcase(p) for p in self.ignore_patterns] dir_suffixes = {'%s*' % path_sep for path_sep in {'/', os.sep}} norm_patterns = [] for p in ignore_patterns: for dir_suffix in dir_suffixes: if p.endswith(dir_suffix): norm_patterns.append(p[:-len(dir_suffix)]) break else: norm_patterns.append(p) all_files = [] ignored_roots = [] if self.settings_available: ignored_roots = [os.path.normpath(p) for p in (settings.MEDIA_ROOT, settings.STATIC_ROOT) if p] for dirpath, dirnames, filenames in os.walk(root, topdown=True, followlinks=self.symlinks): for dirname in dirnames[:]: if (is_ignored(os.path.normpath(os.path.join(dirpath, dirname)), norm_patterns) or os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots): dirnames.remove(dirname) if self.verbosity > 1: self.stdout.write('ignoring directory %s\n' % dirname) elif dirname == 'locale': dirnames.remove(dirname) self.locale_paths.insert(0, os.path.join(os.path.abspath(dirpath), dirname)) for filename in filenames: file_path = os.path.normpath(os.path.join(dirpath, filename)) file_ext = os.path.splitext(filename)[1] if file_ext not in self.extensions or is_ignored(file_path, self.ignore_patterns): if self.verbosity > 1: self.stdout.write('ignoring file %s in %s\n' % (filename, dirpath)) else: locale_dir = None for path in self.locale_paths: if os.path.abspath(dirpath).startswith(os.path.dirname(path)): locale_dir = path break locale_dir = locale_dir or self.default_locale_path or NO_LOCALE_DIR all_files.append(self.translatable_file_class(dirpath, filename, locale_dir)) return sorted(all_files) def process_files(self, file_list): """ Group translatable files by locale directory and run pot file build process for each group. """ file_groups = {} for translatable in file_list: file_group = file_groups.setdefault(translatable.locale_dir, []) file_group.append(translatable) for locale_dir, files in file_groups.items(): self.process_locale_dir(locale_dir, files) def process_locale_dir(self, locale_dir, files): """ Extract translatable literals from the specified files, creating or updating the POT file for a given locale directory. Use the xgettext GNU gettext utility. """ build_files = [] for translatable in files: if self.verbosity > 1: self.stdout.write('processing file %s in %s\n' % ( translatable.file, translatable.dirpath )) if self.domain not in ('djangojs', 'django'): continue build_file = self.build_file_class(self, self.domain, translatable) try: build_file.preprocess() except UnicodeDecodeError as e: self.stdout.write( 'UnicodeDecodeError: skipped file %s in %s (reason: %s)' % ( translatable.file, translatable.dirpath, e, ) ) continue build_files.append(build_file) if self.domain == 'djangojs': is_templatized = build_file.is_templatized args = [ 'xgettext', '-d', self.domain, '--language=%s' % ('C' if is_templatized else 'JavaScript',), '--keyword=gettext_noop', '--keyword=gettext_lazy', '--keyword=ngettext_lazy:1,2', '--keyword=pgettext:1c,2', '--keyword=npgettext:1c,2,3', '--output=-', ] elif self.domain == 'django': args = [ 'xgettext', '-d', self.domain, '--language=Python', '--keyword=gettext_noop', '--keyword=gettext_lazy', '--keyword=ngettext_lazy:1,2', '--keyword=ugettext_noop', '--keyword=ugettext_lazy', '--keyword=ungettext_lazy:1,2', '--keyword=pgettext:1c,2', '--keyword=npgettext:1c,2,3', '--keyword=pgettext_lazy:1c,2', '--keyword=npgettext_lazy:1c,2,3', '--output=-', ] else: return input_files = [bf.work_path for bf in build_files] with NamedTemporaryFile(mode='w+') as input_files_list: input_files_list.write(('\n'.join(input_files))) input_files_list.flush() args.extend(['--files-from', input_files_list.name]) args.extend(self.xgettext_options) msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: for build_file in build_files: build_file.cleanup() raise CommandError( 'errors happened while running xgettext on %s\n%s' % ('\n'.join(input_files), errors) ) elif self.verbosity > 0: # Print warnings self.stdout.write(errors) if msgs: if locale_dir is NO_LOCALE_DIR: file_path = os.path.normpath(build_files[0].path) raise CommandError( 'Unable to find a locale path to store translations for ' 'file %s' % file_path ) for build_file in build_files: msgs = build_file.postprocess_messages(msgs) potfile = os.path.join(locale_dir, '%s.pot' % self.domain) write_pot_file(potfile, msgs) for build_file in build_files: build_file.cleanup() def write_po_file(self, potfile, locale): """ Create or update the PO file for self.domain and `locale`. Use contents of the existing `potfile`. Use msgmerge and msgattrib GNU gettext utilities. """ basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES') if not os.path.isdir(basedir): os.makedirs(basedir) pofile = os.path.join(basedir, '%s.po' % self.domain) if os.path.exists(pofile): args = ['msgmerge'] + self.msgmerge_options + [pofile, potfile] msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msgmerge\n%s" % errors) elif self.verbosity > 0: self.stdout.write(errors) else: with open(potfile, 'r', encoding='utf-8') as fp: msgs = fp.read() if not self.invoked_for_django: msgs = self.copy_plural_forms(msgs, locale) msgs = normalize_eols(msgs) msgs = msgs.replace( "#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % self.domain, "") with open(pofile, 'w', encoding='utf-8') as fp: fp.write(msgs) if self.no_obsolete: args = ['msgattrib'] + self.msgattrib_options + ['-o', pofile, pofile] msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msgattrib\n%s" % errors) elif self.verbosity > 0: self.stdout.write(errors) def copy_plural_forms(self, msgs, locale): """ Copy plural forms header contents from a Django catalog of locale to the msgs string, inserting it at the right place. msgs should be the contents of a newly created .po file. """ django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__))) if self.domain == 'djangojs': domains = ('djangojs', 'django') else: domains = ('django',) for domain in domains: django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain) if os.path.exists(django_po): with open(django_po, 'r', encoding='utf-8') as fp: m = plural_forms_re.search(fp.read()) if m: plural_form_line = m.group('value') if self.verbosity > 1: self.stdout.write("copying plural forms: %s\n" % plural_form_line) lines = [] found = False for line in msgs.splitlines(): if not found and (not line or plural_forms_re.search(line)): line = plural_form_line found = True lines.append(line) msgs = '\n'.join(lines) break return msgs
828f733168967eb52a6d735af729d82c842ef1f2cd4355ebe35d69af7713145f
from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections from django.db.migrations.executor import MigrationExecutor from django.db.migrations.loader import AmbiguityError class Command(BaseCommand): help = "Prints the SQL statements for the named migration." output_transaction = True def add_arguments(self, parser): parser.add_argument('app_label', help='App label of the application containing the migration.') parser.add_argument('migration_name', help='Migration name to print the SQL for.') parser.add_argument( '--database', default=DEFAULT_DB_ALIAS, help='Nominates a database to create SQL for. Defaults to the "default" database.', ) parser.add_argument( '--backwards', action='store_true', dest='backwards', help='Creates SQL to unapply the migration, rather than to apply it', ) def execute(self, *args, **options): # sqlmigrate doesn't support coloring its output but we need to force # no_color=True so that the BEGIN/COMMIT statements added by # output_transaction don't get colored either. options['no_color'] = True return super().execute(*args, **options) def handle(self, *args, **options): # Get the database we're operating from connection = connections[options['database']] # Load up an executor to get all the migration data executor = MigrationExecutor(connection) # Resolve command-line arguments into a migration app_label, migration_name = options['app_label'], options['migration_name'] # Validate app_label try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) if app_label not in executor.loader.migrated_apps: raise CommandError("App '%s' does not have migrations" % app_label) try: migration = executor.loader.get_migration_by_prefix(app_label, migration_name) except AmbiguityError: raise CommandError("More than one migration matches '%s' in app '%s'. Please be more specific." % ( migration_name, app_label)) except KeyError: raise CommandError("Cannot find a migration matching '%s' from app '%s'. Is it in INSTALLED_APPS?" % ( migration_name, app_label)) targets = [(app_label, migration.name)] # Show begin/end around output only for atomic migrations self.output_transaction = migration.atomic # Make a plan that represents just the requested migrations and show SQL # for it plan = [(executor.loader.graph.nodes[targets[0]], options['backwards'])] sql_statements = executor.collect_sql(plan) return '\n'.join(sql_statements)
390da8bd18e0cb803f2d152d15eeaedac8949f4c6a5010fe423de8eca7b946ab
from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections from django.db.migrations.loader import MigrationLoader class Command(BaseCommand): help = "Shows all available migrations for the current project" def add_arguments(self, parser): parser.add_argument( 'app_label', nargs='*', help='App labels of applications to limit the output to.', ) parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. Defaults to the "default" database.', ) formats = parser.add_mutually_exclusive_group() formats.add_argument( '--list', '-l', action='store_const', dest='format', const='list', help='Shows a list of all migrations and which are applied.', ) formats.add_argument( '--plan', '-p', action='store_const', dest='format', const='plan', help=( 'Shows all migrations in the order they will be applied. ' 'With a verbosity level of 2 or above all direct migration dependencies ' 'and reverse dependencies (run_before) will be included.' ) ) parser.set_defaults(format='list') def handle(self, *args, **options): self.verbosity = options['verbosity'] # Get the database we're operating from db = options['database'] connection = connections[db] if options['format'] == "plan": return self.show_plan(connection, options['app_label']) else: return self.show_list(connection, options['app_label']) def _validate_app_names(self, loader, app_names): invalid_apps = [] for app_name in app_names: if app_name not in loader.migrated_apps: invalid_apps.append(app_name) if invalid_apps: raise CommandError('No migrations present for: %s' % (', '.join(sorted(invalid_apps)))) def show_list(self, connection, app_names=None): """ Show a list of all migrations on the system, or only those of some named apps. """ # Load migrations from disk/DB loader = MigrationLoader(connection, ignore_no_migrations=True) graph = loader.graph # If we were passed a list of apps, validate it if app_names: self._validate_app_names(loader, app_names) # Otherwise, show all apps in alphabetic order else: app_names = sorted(loader.migrated_apps) # For each app, print its migrations in order from oldest (roots) to # newest (leaves). for app_name in app_names: self.stdout.write(app_name, self.style.MIGRATE_LABEL) shown = set() for node in graph.leaf_nodes(app_name): for plan_node in graph.forwards_plan(node): if plan_node not in shown and plan_node[0] == app_name: # Give it a nice title if it's a squashed one title = plan_node[1] if graph.nodes[plan_node].replaces: title += " (%s squashed migrations)" % len(graph.nodes[plan_node].replaces) # Mark it as applied/unapplied if plan_node in loader.applied_migrations: self.stdout.write(" [X] %s" % title) else: self.stdout.write(" [ ] %s" % title) shown.add(plan_node) # If we didn't print anything, then a small message if not shown: self.stdout.write(" (no migrations)", self.style.ERROR) def show_plan(self, connection, app_names=None): """ Show all known migrations (or only those of the specified app_names) in the order they will be applied. """ # Load migrations from disk/DB loader = MigrationLoader(connection) graph = loader.graph if app_names: self._validate_app_names(loader, app_names) targets = [key for key in graph.leaf_nodes() if key[0] in app_names] else: targets = graph.leaf_nodes() plan = [] seen = set() # Generate the plan for target in targets: for migration in graph.forwards_plan(target): if migration not in seen: node = graph.node_map[migration] plan.append(node) seen.add(migration) # Output def print_deps(node): out = [] for parent in sorted(node.parents): out.append("%s.%s" % parent.key) if out: return " ... (%s)" % ", ".join(out) return "" for node in plan: deps = "" if self.verbosity >= 2: deps = print_deps(node) if node.key in loader.applied_migrations: self.stdout.write("[X] %s.%s%s" % (node.key[0], node.key[1], deps)) else: self.stdout.write("[ ] %s.%s%s" % (node.key[0], node.key[1], deps))
55e8f253abce581dda78016178c085c59968c84bd36f7845314f4d10310ba875
import keyword import re from collections import OrderedDict from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections from django.db.models.constants import LOOKUP_SEP class Command(BaseCommand): help = "Introspects the database tables in the given database and outputs a Django model module." requires_system_checks = False stealth_options = ('table_name_filter',) db_module = 'django.db' def add_arguments(self, parser): parser.add_argument( 'table', action='store', nargs='*', type=str, help='Selects what tables or views should be introspected.', ) parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to introspect. Defaults to using the "default" database.', ) parser.add_argument( '--include-views', action='store_true', help='Also output models for database views.', ) def handle(self, **options): try: for line in self.handle_inspection(options): self.stdout.write("%s\n" % line) except NotImplementedError: raise CommandError("Database inspection isn't supported for the currently selected database backend.") def handle_inspection(self, options): connection = connections[options['database']] # 'table_name_filter' is a stealth option table_name_filter = options.get('table_name_filter') def table2model(table_name): return re.sub(r'[^a-zA-Z0-9]', '', table_name.title()) def strip_prefix(s): return s[1:] if s.startswith("u'") else s with connection.cursor() as cursor: yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield "# * Make sure each ForeignKey has `on_delete` set to the desired behavior." yield ( "# * Remove `managed = False` lines if you wish to allow " "Django to create, modify, and delete the table" ) yield "# Feel free to rename the models, but don't rename db_table values or field names." yield 'from %s import models' % self.db_module known_models = [] table_info = connection.introspection.get_table_list(cursor) tables_to_introspect = ( options['table'] or sorted(info.name for info in table_info if options['include_views'] or info.type == 't') ) for table_name in tables_to_introspect: if table_name_filter is not None and callable(table_name_filter): if not table_name_filter(table_name): continue try: try: relations = connection.introspection.get_relations(cursor, table_name) except NotImplementedError: relations = {} try: constraints = connection.introspection.get_constraints(cursor, table_name) except NotImplementedError: constraints = {} primary_key_column = connection.introspection.get_primary_key_column(cursor, table_name) unique_columns = [ c['columns'][0] for c in constraints.values() if c['unique'] and len(c['columns']) == 1 ] table_description = connection.introspection.get_table_description(cursor, table_name) except Exception as e: yield "# Unable to inspect table '%s'" % table_name yield "# The error was: %s" % e continue yield '' yield '' yield 'class %s(models.Model):' % table2model(table_name) known_models.append(table2model(table_name)) used_column_names = [] # Holds column names used in the table so far column_to_field_name = {} # Maps column names to names of model fields for row in table_description: comment_notes = [] # Holds Field notes, to be displayed in a Python comment. extra_params = OrderedDict() # Holds Field parameters such as 'db_column'. column_name = row[0] is_relation = column_name in relations att_name, params, notes = self.normalize_col_name( column_name, used_column_names, is_relation) extra_params.update(params) comment_notes.extend(notes) used_column_names.append(att_name) column_to_field_name[column_name] = att_name # Add primary_key and unique, if necessary. if column_name == primary_key_column: extra_params['primary_key'] = True elif column_name in unique_columns: extra_params['unique'] = True if is_relation: rel_to = ( "self" if relations[column_name][1] == table_name else table2model(relations[column_name][1]) ) if rel_to in known_models: field_type = 'ForeignKey(%s' % rel_to else: field_type = "ForeignKey('%s'" % rel_to else: # Calling `get_field_type` to get the field type string and any # additional parameters and notes. field_type, field_params, field_notes = self.get_field_type(connection, table_name, row) extra_params.update(field_params) comment_notes.extend(field_notes) field_type += '(' # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. if att_name == 'id' and extra_params == {'primary_key': True}: if field_type == 'AutoField(': continue elif field_type == 'IntegerField(' and not connection.features.can_introspect_autofield: comment_notes.append('AutoField?') # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. if row[6]: # If it's NULL... extra_params['blank'] = True extra_params['null'] = True field_desc = '%s = %s%s' % ( att_name, # Custom fields will have a dotted path '' if '.' in field_type else 'models.', field_type, ) if field_type.startswith('ForeignKey('): field_desc += ', models.DO_NOTHING' if extra_params: if not field_desc.endswith('('): field_desc += ', ' field_desc += ', '.join( '%s=%s' % (k, strip_prefix(repr(v))) for k, v in extra_params.items()) field_desc += ')' if comment_notes: field_desc += ' # ' + ' '.join(comment_notes) yield ' %s' % field_desc is_view = any(info.name == table_name and info.type == 'v' for info in table_info) for meta_line in self.get_meta(table_name, constraints, column_to_field_name, is_view): yield meta_line def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.append('Field name made lowercase.') if is_relation: if new_name.endswith('_id'): new_name = new_name[:-3] else: field_params['db_column'] = col_name new_name, num_repl = re.subn(r'\W', '_', new_name) if num_repl > 0: field_notes.append('Field renamed to remove unsuitable characters.') if new_name.find(LOOKUP_SEP) >= 0: while new_name.find(LOOKUP_SEP) >= 0: new_name = new_name.replace(LOOKUP_SEP, '_') if col_name.lower().find(LOOKUP_SEP) >= 0: # Only add the comment if the double underscore was in the original name field_notes.append("Field renamed because it contained more than one '_' in a row.") if new_name.startswith('_'): new_name = 'field%s' % new_name field_notes.append("Field renamed because it started with '_'.") if new_name.endswith('_'): new_name = '%sfield' % new_name field_notes.append("Field renamed because it ended with '_'.") if keyword.iskeyword(new_name): new_name += '_field' field_notes.append('Field renamed because it was a Python reserved word.') if new_name[0].isdigit(): new_name = 'number_%s' % new_name field_notes.append("Field renamed because it wasn't a valid Python identifier.") if new_name in used_column_names: num = 0 while '%s_%d' % (new_name, num) in used_column_names: num += 1 new_name = '%s_%d' % (new_name, num) field_notes.append('Field renamed because of name conflict.') if col_name != new_name and field_notes: field_params['db_column'] = col_name return new_name, field_params, field_notes def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = OrderedDict() field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') # This is a hook for data_types_reverse to return a tuple of # (field_type, field_params_dict). if type(field_type) is tuple: field_type, new_params = field_type field_params.update(new_params) # Add max_length for all CharFields. if field_type == 'CharField' and row[3]: field_params['max_length'] = int(row[3]) if field_type == 'DecimalField': if row[4] is None or row[5] is None: field_notes.append( 'max_digits and decimal_places have been guessed, as this ' 'database handles decimal fields as float') field_params['max_digits'] = row[4] if row[4] is not None else 10 field_params['decimal_places'] = row[5] if row[5] is not None else 5 else: field_params['max_digits'] = row[4] field_params['decimal_places'] = row[5] return field_type, field_params, field_notes def get_meta(self, table_name, constraints, column_to_field_name, is_view): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ unique_together = [] has_unsupported_constraint = False for params in constraints.values(): if params['unique']: columns = params['columns'] if None in columns: has_unsupported_constraint = True columns = [x for x in columns if x is not None] if len(columns) > 1: unique_together.append(str(tuple(column_to_field_name[c] for c in columns))) managed_comment = " # Created from a view. Don't remove." if is_view else "" meta = [''] if has_unsupported_constraint: meta.append(' # A unique constraint could not be introspected.') meta += [ ' class Meta:', ' managed = False%s' % managed_comment, ' db_table = %r' % table_name ] if unique_together: tup = '(' + ', '.join(unique_together) + ',)' meta += [" unique_together = %s" % tup] return meta
c9f86f7bfd554b4c59d38bdbc4054eb7168ed3033f483c6650d9e3469f7fd50b
import os import sys from itertools import takewhile from django.apps import apps from django.conf import settings from django.core.management.base import ( BaseCommand, CommandError, no_translations, ) from django.db import DEFAULT_DB_ALIAS, connections, router from django.db.migrations import Migration from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import ( InteractiveMigrationQuestioner, MigrationQuestioner, NonInteractiveMigrationQuestioner, ) from django.db.migrations.state import ProjectState from django.db.migrations.utils import get_migration_name_timestamp from django.db.migrations.writer import MigrationWriter class Command(BaseCommand): help = "Creates new migration(s) for apps." def add_arguments(self, parser): parser.add_argument( 'args', metavar='app_label', nargs='*', help='Specify the app label(s) to create migrations for.', ) parser.add_argument( '--dry-run', action='store_true', dest='dry_run', help="Just show what migrations would be made; don't actually write them.", ) parser.add_argument( '--merge', action='store_true', dest='merge', help="Enable fixing of migration conflicts.", ) parser.add_argument( '--empty', action='store_true', dest='empty', help="Create an empty migration.", ) parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '-n', '--name', action='store', dest='name', default=None, help="Use this name for migration file(s).", ) parser.add_argument( '--check', action='store_true', dest='check_changes', help='Exit with a non-zero status if model changes are missing migrations.', ) @no_translations def handle(self, *app_labels, **options): self.verbosity = options['verbosity'] self.interactive = options['interactive'] self.dry_run = options['dry_run'] self.merge = options['merge'] self.empty = options['empty'] self.migration_name = options['name'] check_changes = options['check_changes'] # Make sure the app they asked for exists app_labels = set(app_labels) has_bad_labels = False for app_label in app_labels: try: apps.get_app_config(app_label) except LookupError as err: self.stderr.write(str(err)) has_bad_labels = True if has_bad_labels: sys.exit(2) # Load the current graph state. Pass in None for the connection so # the loader doesn't try to resolve replaced migrations from DB. loader = MigrationLoader(None, ignore_no_migrations=True) # Raise an error if any migrations are applied before their dependencies. consistency_check_labels = {config.label for config in apps.get_app_configs()} # Non-default databases are only checked if database routers used. aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS] for alias in sorted(aliases_to_check): connection = connections[alias] if (connection.settings_dict['ENGINE'] != 'django.db.backends.dummy' and any( # At least one model must be migrated to the database. router.allow_migrate(connection.alias, app_label, model_name=model._meta.object_name) for app_label in consistency_check_labels for model in apps.get_app_config(app_label).get_models() )): loader.check_consistent_history(connection) # Before anything else, see if there's conflicting apps and drop out # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() # If app_labels is specified, filter out conflicting migrations for unspecified apps if app_labels: conflicts = { app_label: conflict for app_label, conflict in conflicts.items() if app_label in app_labels } if conflicts and not self.merge: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str ) # If they want to merge and there's nothing to merge, then politely exit if self.merge and not conflicts: self.stdout.write("No conflicts detected to merge.") return # If they want to merge and there is something to merge, then # divert into the merge code if self.merge and conflicts: return self.handle_merge(loader, conflicts) if self.interactive: questioner = InteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run) else: questioner = NonInteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run) # Set up autodetector autodetector = MigrationAutodetector( loader.project_state(), ProjectState.from_apps(apps), questioner, ) # If they want to make an empty migration, make one for each app if self.empty: if not app_labels: raise CommandError("You must supply at least one app label when using --empty.") # Make a fake changes() result we can pass to arrange_for_graph changes = { app: [Migration("custom", app)] for app in app_labels } changes = autodetector.arrange_for_graph( changes=changes, graph=loader.graph, migration_name=self.migration_name, ) self.write_migration_files(changes) return # Detect changes changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name=self.migration_name, ) if not changes: # No changes? Tell them. if self.verbosity >= 1: if app_labels: if len(app_labels) == 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) else: self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else: self.stdout.write("No changes detected") else: self.write_migration_files(changes) if check_changes: sys.exit(1) def write_migration_files(self, changes): """ Take a changes dict and write them out as migration files. """ directory_created = {} for app_label, app_migrations in changes.items(): if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n") for migration in app_migrations: # Describe the migration writer = MigrationWriter(migration) if self.verbosity >= 1: # Display a relative path if it's below the current working # directory, or an absolute path otherwise. try: migration_string = os.path.relpath(writer.path) except ValueError: migration_string = writer.path if migration_string.startswith('..'): migration_string = writer.path self.stdout.write(" %s\n" % (self.style.MIGRATE_LABEL(migration_string),)) for operation in migration.operations: self.stdout.write(" - %s\n" % operation.describe()) if not self.dry_run: # Write the migrations file to the disk. migrations_directory = os.path.dirname(writer.path) if not directory_created.get(app_label): if not os.path.isdir(migrations_directory): os.mkdir(migrations_directory) init_path = os.path.join(migrations_directory, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() # We just do this once per app directory_created[app_label] = True migration_string = writer.as_string() with open(writer.path, "w", encoding='utf-8') as fh: fh.write(migration_string) elif self.verbosity == 3: # Alternatively, makemigrations --dry-run --verbosity 3 # will output the migrations to stdout rather than saving # the file to the disk. self.stdout.write(self.style.MIGRATE_HEADING( "Full migrations file '%s':" % writer.filename) + "\n" ) self.stdout.write("%s\n" % writer.as_string()) def handle_merge(self, loader, conflicts): """ Handles merging together conflicted migrations interactively, if it's safe; otherwise, advises on how to fix it. """ if self.interactive: questioner = InteractiveMigrationQuestioner() else: questioner = MigrationQuestioner(defaults={'ask_merge': True}) for app_label, migration_names in conflicts.items(): # Grab out the migrations in question, and work out their # common ancestor. merge_migrations = [] for migration_name in migration_names: migration = loader.get_migration(app_label, migration_name) migration.ancestry = [ mig for mig in loader.graph.forwards_plan((app_label, migration_name)) if mig[0] == migration.app_label ] merge_migrations.append(migration) def all_items_equal(seq): return all(item == seq[0] for item in seq[1:]) merge_migrations_generations = zip(*(m.ancestry for m in merge_migrations)) common_ancestor_count = sum(1 for common_ancestor_generation in takewhile(all_items_equal, merge_migrations_generations)) if not common_ancestor_count: raise ValueError("Could not find common ancestor of %s" % migration_names) # Now work out the operations along each divergent branch for migration in merge_migrations: migration.branch = migration.ancestry[common_ancestor_count:] migrations_ops = (loader.get_migration(node_app, node_name).operations for node_app, node_name in migration.branch) migration.merged_operations = sum(migrations_ops, []) # In future, this could use some of the Optimizer code # (can_optimize_through) to automatically see if they're # mergeable. For now, we always just prompt the user. if self.verbosity > 0: self.stdout.write(self.style.MIGRATE_HEADING("Merging %s" % app_label)) for migration in merge_migrations: self.stdout.write(self.style.MIGRATE_LABEL(" Branch %s" % migration.name)) for operation in migration.merged_operations: self.stdout.write(" - %s\n" % operation.describe()) if questioner.ask_merge(app_label): # If they still want to merge it, then write out an empty # file depending on the migrations needing merging. numbers = [ MigrationAutodetector.parse_number(migration.name) for migration in merge_migrations ] try: biggest_number = max(x for x in numbers if x is not None) except ValueError: biggest_number = 1 subclass = type("Migration", (Migration,), { "dependencies": [(app_label, migration.name) for migration in merge_migrations], }) migration_name = "%04i_%s" % ( biggest_number + 1, self.migration_name or ("merge_%s" % get_migration_name_timestamp()) ) new_migration = subclass(migration_name, app_label) writer = MigrationWriter(new_migration) if not self.dry_run: # Write the merge migrations file to the disk with open(writer.path, "w", encoding='utf-8') as fh: fh.write(writer.as_string()) if self.verbosity > 0: self.stdout.write("\nCreated new merge migration %s" % writer.path) elif self.verbosity == 3: # Alternatively, makemigrations --merge --dry-run --verbosity 3 # will output the merge migrations to stdout rather than saving # the file to the disk. self.stdout.write(self.style.MIGRATE_HEADING( "Full merge migrations file '%s':" % writer.filename) + "\n" ) self.stdout.write("%s\n" % writer.as_string())
0513a3aef3cd0a9d640ba8c0aeb3848337728f47fa30d878a7beb4c3635d0b21
import os import select import sys import traceback from django.core.management import BaseCommand, CommandError from django.utils.datastructures import OrderedSet class Command(BaseCommand): help = ( "Runs a Python interactive interpreter. Tries to use IPython or " "bpython, if one of them is available. Any standard input is executed " "as code." ) requires_system_checks = False shells = ['ipython', 'bpython', 'python'] def add_arguments(self, parser): parser.add_argument( '--no-startup', action='store_true', dest='no_startup', help='When using plain Python, ignore the PYTHONSTARTUP environment variable and ~/.pythonrc.py script.', ) parser.add_argument( '-i', '--interface', choices=self.shells, dest='interface', help='Specify an interactive interpreter interface. Available options: "ipython", "bpython", and "python"', ) parser.add_argument( '-c', '--command', dest='command', help='Instead of opening an interactive shell, run a command as Django and exit.', ) def ipython(self, options): from IPython import start_ipython start_ipython(argv=[]) def bpython(self, options): import bpython bpython.embed() def python(self, options): import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. imported_objects = {} try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) # Enable tab completion on systems using libedit (e.g. macOS). # These lines are copied from Python's Lib/site.py. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in OrderedSet([os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')]): if not pythonrc: continue if not os.path.isfile(pythonrc): continue with open(pythonrc) as handle: pythonrc_code = handle.read() # Match the behavior of the cpython shell where an error in # PYTHONSTARTUP prints an exception and continues. try: exec(compile(pythonrc_code, pythonrc, 'exec'), imported_objects) except Exception: traceback.print_exc() code.interact(local=imported_objects) def handle(self, **options): # Execute the command and exit. if options['command']: exec(options['command']) return # Execute stdin if it has anything to read and exit. # Not supported on Windows due to select.select() limitations. if sys.platform != 'win32' and select.select([sys.stdin], [], [], 0)[0]: exec(sys.stdin.read()) return available_shells = [options['interface']] if options['interface'] else self.shells for shell in available_shells: try: return getattr(self, shell)(options) except ImportError: pass raise CommandError("Couldn't import {} interface.".format(shell))
bafe9ceacafda0dfa8e4f36a06a0d25631e3fa98425a6b6c6a678b38ad9ec508
"File-based cache backend" import glob import hashlib import os import pickle import random import tempfile import time import zlib from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.core.files import locks from django.core.files.move import file_move_safe def _write_content(f, expiry, value): f.write(pickle.dumps(expiry, pickle.HIGHEST_PROTOCOL)) f.write(zlib.compress(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))) class FileBasedCache(BaseCache): cache_suffix = '.djcache' def __init__(self, dir, params): super().__init__(params) self._dir = os.path.abspath(dir) self._createdir() def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): if self.has_key(key, version): return False self.set(key, value, timeout, version) return True def get(self, key, default=None, version=None): fname = self._key_to_file(key, version) try: with open(fname, 'rb') as f: if not self._is_expired(f): return pickle.loads(zlib.decompress(f.read())) except FileNotFoundError: pass return default def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): self._createdir() # Cache dir can be deleted at any time. fname = self._key_to_file(key, version) self._cull() # make some room if necessary fd, tmp_path = tempfile.mkstemp(dir=self._dir) renamed = False try: with open(fd, 'wb') as f: expiry = self.get_backend_timeout(timeout) _write_content(f, expiry, value) file_move_safe(tmp_path, fname, allow_overwrite=True) renamed = True finally: if not renamed: os.remove(tmp_path) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): try: with open(self._key_to_file(key, version), 'r+b') as f: try: locks.lock(f, locks.LOCK_EX) if self._is_expired(f): return False else: previous_value = pickle.loads(zlib.decompress(f.read())) f.seek(0) _write_content(f, self.get_backend_timeout(timeout), previous_value) return True finally: locks.unlock(f) except FileNotFoundError: return False def delete(self, key, version=None): self._delete(self._key_to_file(key, version)) def _delete(self, fname): if not fname.startswith(self._dir) or not os.path.exists(fname): return try: os.remove(fname) except FileNotFoundError: # The file may have been removed by another process. pass def has_key(self, key, version=None): fname = self._key_to_file(key, version) if os.path.exists(fname): with open(fname, 'rb') as f: return not self._is_expired(f) return False def _cull(self): """ Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged. """ filelist = self._list_cache_files() num_entries = len(filelist) if num_entries < self._max_entries: return # return early if no culling is required if self._cull_frequency == 0: return self.clear() # Clear the cache when CULL_FREQUENCY = 0 # Delete a random selection of entries filelist = random.sample(filelist, int(num_entries / self._cull_frequency)) for fname in filelist: self._delete(fname) def _createdir(self): if not os.path.exists(self._dir): try: os.makedirs(self._dir, 0o700) except FileExistsError: pass def _key_to_file(self, key, version=None): """ Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix. """ key = self.make_key(key, version=version) self.validate_key(key) return os.path.join(self._dir, ''.join( [hashlib.md5(key.encode()).hexdigest(), self.cache_suffix])) def clear(self): """ Remove all the cache files. """ if not os.path.exists(self._dir): return for fname in self._list_cache_files(): self._delete(fname) def _is_expired(self, f): """ Take an open cache file `f` and delete it if it's expired. """ try: exp = pickle.load(f) except EOFError: exp = 0 # An empty file is considered expired. if exp is not None and exp < time.time(): f.close() # On Windows a file has to be closed before deleting self._delete(f.name) return True return False def _list_cache_files(self): """ Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix. """ if not os.path.exists(self._dir): return [] filelist = [os.path.join(self._dir, fname) for fname in glob.glob1(self._dir, '*%s' % self.cache_suffix)] return filelist
808d4f76ac6ccc62ffeef23a02c7e819caa2772a582dfea43e251bebf0adfb65
"Memcached cache backend" import pickle import re import time from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.utils.functional import cached_property class BaseMemcachedCache(BaseCache): def __init__(self, server, params, library, value_not_found_exception): super().__init__(params) if isinstance(server, str): self._servers = re.split('[;,]', server) else: self._servers = server # The exception type to catch from the underlying library for a key # that was not found. This is a ValueError for python-memcache, # pylibmc.NotFound for pylibmc, and cmemcache will return None without # raising an exception. self.LibraryValueNotFoundException = value_not_found_exception self._lib = library self._options = params.get('OPTIONS') or {} @property def _cache(self): """ Implement transparent thread-safe access to a memcached client. """ if getattr(self, '_client', None) is None: self._client = self._lib.Client(self._servers, **self._options) return self._client def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout if timeout is None: # Using 0 in memcache sets a non-expiring timeout. return 0 elif int(timeout) == 0: # Other cache backends treat 0 as set-and-expire. To achieve this # in memcache backends, a negative timeout must be passed. timeout = -1 if timeout > 2592000: # 60*60*24*30, 30 days # See https://github.com/memcached/memcached/wiki/Programming#expiration # "Expiration times can be set from 0, meaning "never expire", to # 30 days. Any time higher than 30 days is interpreted as a Unix # timestamp date. If you want to expire an object on January 1st of # next year, this is how you do that." # # This means that we have to switch to absolute timestamps. timeout += int(time.time()) return int(timeout) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_key(key, version=version) val = self._cache.get(key) if val is None: return default return val def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) if not self._cache.set(key, value, self.get_backend_timeout(timeout)): # make sure the key doesn't keep its old value in case of failure to set (memcached's 1MB limit) self._cache.delete(key) def delete(self, key, version=None): key = self.make_key(key, version=version) self._cache.delete(key) def get_many(self, keys, version=None): new_keys = [self.make_key(x, version=version) for x in keys] ret = self._cache.get_multi(new_keys) if ret: m = dict(zip(new_keys, keys)) return {m[k]: v for k, v in ret.items()} return ret def close(self, **kwargs): # Many clients don't clean up connections properly. self._cache.disconnect_all() def incr(self, key, delta=1, version=None): key = self.make_key(key, version=version) # memcached doesn't support a negative delta if delta < 0: return self._cache.decr(key, -delta) try: val = self._cache.incr(key, delta) # python-memcache responds to incr on nonexistent keys by # raising a ValueError, pylibmc by raising a pylibmc.NotFound # and Cmemcache returns None. In all cases, # we should raise a ValueError though. except self.LibraryValueNotFoundException: val = None if val is None: raise ValueError("Key '%s' not found" % key) return val def decr(self, key, delta=1, version=None): key = self.make_key(key, version=version) # memcached doesn't support a negative delta if delta < 0: return self._cache.incr(key, -delta) try: val = self._cache.decr(key, delta) # python-memcache responds to incr on nonexistent keys by # raising a ValueError, pylibmc by raising a pylibmc.NotFound # and Cmemcache returns None. In all cases, # we should raise a ValueError though. except self.LibraryValueNotFoundException: val = None if val is None: raise ValueError("Key '%s' not found" % key) return val def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): safe_data = {} original_keys = {} for key, value in data.items(): safe_key = self.make_key(key, version=version) safe_data[safe_key] = value original_keys[safe_key] = key failed_keys = self._cache.set_multi(safe_data, self.get_backend_timeout(timeout)) return [original_keys[k] for k in failed_keys] def delete_many(self, keys, version=None): self._cache.delete_multi(self.make_key(key, version=version) for key in keys) def clear(self): self._cache.flush_all() class MemcachedCache(BaseMemcachedCache): "An implementation of a cache binding using python-memcached" def __init__(self, server, params): import memcache super().__init__(server, params, library=memcache, value_not_found_exception=ValueError) @property def _cache(self): if getattr(self, '_client', None) is None: client_kwargs = {'pickleProtocol': pickle.HIGHEST_PROTOCOL} client_kwargs.update(self._options) self._client = self._lib.Client(self._servers, **client_kwargs) return self._client def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) return self._cache.touch(key, self.get_backend_timeout(timeout)) != 0 class PyLibMCCache(BaseMemcachedCache): "An implementation of a cache binding using pylibmc" def __init__(self, server, params): import pylibmc super().__init__(server, params, library=pylibmc, value_not_found_exception=pylibmc.NotFound) @cached_property def _cache(self): return self._lib.Client(self._servers, **self._options) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) if timeout == 0: return self._cache.delete(key) return self._cache.touch(key, self.get_backend_timeout(timeout)) def close(self, **kwargs): # libmemcached manages its own connections. Don't call disconnect_all() # as it resets the failover state and creates unnecessary reconnects. pass
d4d4c391eae4a3bb8e881d70ca9d1ccf1f3818c1e0caa5cffda232d83830dd20
"Database cache backend." import base64 import pickle from datetime import datetime from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.db import DatabaseError, connections, models, router, transaction from django.utils import timezone from django.utils.inspect import func_supports_parameter class Options: """A class that will quack like a Django model _meta class. This allows cache operations to be controlled by the router """ def __init__(self, table): self.db_table = table self.app_label = 'django_cache' self.model_name = 'cacheentry' self.verbose_name = 'cache entry' self.verbose_name_plural = 'cache entries' self.object_name = 'CacheEntry' self.abstract = False self.managed = True self.proxy = False self.swapped = False class BaseDatabaseCache(BaseCache): def __init__(self, table, params): super().__init__(params) self._table = table class CacheEntry: _meta = Options(table) self.cache_model_class = CacheEntry class DatabaseCache(BaseDatabaseCache): # This class uses cursors provided by the database connection. This means # it reads expiration values as aware or naive datetimes, depending on the # value of USE_TZ and whether the database supports time zones. The ORM's # conversion and adaptation infrastructure is then used to avoid comparing # aware and naive datetimes accidentally. def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) connection = connections[db] quote_name = connection.ops.quote_name table = quote_name(self._table) with connection.cursor() as cursor: cursor.execute( 'SELECT %s, %s, %s FROM %s WHERE %s = %%s' % ( quote_name('cache_key'), quote_name('value'), quote_name('expires'), table, quote_name('cache_key'), ), [key] ) row = cursor.fetchone() if row is None: return default expires = row[2] expression = models.Expression(output_field=models.DateTimeField()) for converter in (connection.ops.get_db_converters(expression) + expression.get_db_converters(connection)): if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning expires = converter(expires, expression, connection, {}) else: expires = converter(expires, expression, connection) if expires < timezone.now(): db = router.db_for_write(self.cache_model_class) connection = connections[db] with connection.cursor() as cursor: cursor.execute( 'DELETE FROM %s WHERE %s = %%s' % ( table, quote_name('cache_key'), ), [key] ) return default value = connection.ops.process_clob(row[1]) return pickle.loads(base64.b64decode(value.encode())) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._base_set('set', key, value, timeout) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) return self._base_set('add', key, value, timeout) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) return self._base_set('touch', key, None, timeout) def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT): timeout = self.get_backend_timeout(timeout) db = router.db_for_write(self.cache_model_class) connection = connections[db] quote_name = connection.ops.quote_name table = quote_name(self._table) with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] now = timezone.now() now = now.replace(microsecond=0) if timeout is None: exp = datetime.max elif settings.USE_TZ: exp = datetime.utcfromtimestamp(timeout) else: exp = datetime.fromtimestamp(timeout) exp = exp.replace(microsecond=0) if num > self._max_entries: self._cull(db, cursor, now) pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) # The DB column is expecting a string, so make sure the value is a # string, not bytes. Refs #19274. b64encoded = base64.b64encode(pickled).decode('latin1') try: # Note: typecasting for datetimes is needed by some 3rd party # database backends. All core backends work without typecasting, # so be careful about changes here - test suite will NOT pick # regressions. with transaction.atomic(using=db): cursor.execute( 'SELECT %s, %s FROM %s WHERE %s = %%s' % ( quote_name('cache_key'), quote_name('expires'), table, quote_name('cache_key'), ), [key] ) result = cursor.fetchone() if result: current_expires = result[1] expression = models.Expression(output_field=models.DateTimeField()) for converter in (connection.ops.get_db_converters(expression) + expression.get_db_converters(connection)): if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning current_expires = converter(current_expires, expression, connection, {}) else: current_expires = converter(current_expires, expression, connection) exp = connection.ops.adapt_datetimefield_value(exp) if result and mode == 'touch': cursor.execute( 'UPDATE %s SET %s = %%s WHERE %s = %%s' % ( table, quote_name('expires'), quote_name('cache_key') ), [exp, key] ) elif result and (mode == 'set' or (mode == 'add' and current_expires < now)): cursor.execute( 'UPDATE %s SET %s = %%s, %s = %%s WHERE %s = %%s' % ( table, quote_name('value'), quote_name('expires'), quote_name('cache_key'), ), [b64encoded, exp, key] ) elif mode != 'touch': cursor.execute( 'INSERT INTO %s (%s, %s, %s) VALUES (%%s, %%s, %%s)' % ( table, quote_name('cache_key'), quote_name('value'), quote_name('expires'), ), [key, b64encoded, exp] ) else: return False # touch failed. except DatabaseError: # To be threadsafe, updates/inserts are allowed to fail silently return False else: return True def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_write(self.cache_model_class) connection = connections[db] table = connection.ops.quote_name(self._table) with connection.cursor() as cursor: cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key]) def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) connection = connections[db] quote_name = connection.ops.quote_name if settings.USE_TZ: now = datetime.utcnow() else: now = datetime.now() now = now.replace(microsecond=0) with connection.cursor() as cursor: cursor.execute( 'SELECT %s FROM %s WHERE %s = %%s and expires > %%s' % ( quote_name('cache_key'), quote_name(self._table), quote_name('cache_key'), ), [key, connection.ops.adapt_datetimefield_value(now)] ) return cursor.fetchone() is not None def _cull(self, db, cursor, now): if self._cull_frequency == 0: self.clear() else: connection = connections[db] table = connection.ops.quote_name(self._table) cursor.execute("DELETE FROM %s WHERE expires < %%s" % table, [connection.ops.adapt_datetimefield_value(now)]) cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] if num > self._max_entries: cull_num = num // self._cull_frequency cursor.execute( connection.ops.cache_key_culling_sql() % table, [cull_num]) cursor.execute("DELETE FROM %s " "WHERE cache_key < %%s" % table, [cursor.fetchone()[0]]) def clear(self): db = router.db_for_write(self.cache_model_class) connection = connections[db] table = connection.ops.quote_name(self._table) with connection.cursor() as cursor: cursor.execute('DELETE FROM %s' % table)
beb3212ab000a34bdb48339fb1054c5fc3857d1389645a1e6e87e7b651693cc8
"Base Cache class." import time import warnings from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import import_string class InvalidCacheBackendError(ImproperlyConfigured): pass class CacheKeyWarning(RuntimeWarning): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object() # Memcached does not accept keys longer than this. MEMCACHE_MAX_KEY_LENGTH = 250 def default_key_func(key, key_prefix, version): """ Default function to generate keys. Construct the key used by all other methods. By default, prepend the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return '%s:%s:%s' % (key_prefix, version, key) def get_key_func(key_func): """ Function to decide which key function to use. Default to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func class BaseCache: def __init__(self, params): timeout = params.get('timeout', params.get('TIMEOUT', 300)) if timeout is not None: try: timeout = int(timeout) except (ValueError, TypeError): timeout = 300 self.default_timeout = timeout options = params.get('OPTIONS', {}) max_entries = params.get('max_entries', options.get('MAX_ENTRIES', 300)) try: self._max_entries = int(max_entries) except (ValueError, TypeError): self._max_entries = 300 cull_frequency = params.get('cull_frequency', options.get('CULL_FREQUENCY', 3)) try: self._cull_frequency = int(cull_frequency) except (ValueError, TypeError): self._cull_frequency = 3 self.key_prefix = params.get('KEY_PREFIX', '') self.version = params.get('VERSION', 1) self.key_func = get_key_func(params.get('KEY_FUNCTION')) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Return the timeout value usable by this backend based upon the provided timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout elif timeout == 0: # ticket 21147 - avoid time.time() related precision issues timeout = -1 return None if timeout is None else time.time() + timeout def make_key(self, key, version=None): """ Construct the key used by all other methods. By default, use the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). A different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to provide custom key making behavior. """ if version is None: version = self.version new_key = self.key_func(key, self.key_prefix, version) return new_key def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache if the key does not already exist. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. Return True if the value was stored, False otherwise. """ raise NotImplementedError('subclasses of BaseCache must provide an add() method') def get(self, key, default=None, version=None): """ Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError('subclasses of BaseCache must provide a get() method') def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. """ raise NotImplementedError('subclasses of BaseCache must provide a set() method') def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): """ Update the key's expiry time using timeout. Return True if successful or False if the key does not exist. """ raise NotImplementedError('subclasses of BaseCache must provide a touch() method') def delete(self, key, version=None): """ Delete a key from the cache, failing silently. """ raise NotImplementedError('subclasses of BaseCache must provide a delete() method') def get_many(self, keys, version=None): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Return a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. """ d = {} for k in keys: val = self.get(k, version=version) if val is not None: d[k] = val return d def get_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None): """ Fetch a given key from the cache. If the key does not exist, add the key and set it to the default value. The default value can also be any callable. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. Return the value of the key stored or retrieved. """ val = self.get(key, version=version) if val is None: if callable(default): default = default() if default is not None: self.add(key, default, timeout=timeout, version=version) # Fetch the value again to avoid a race condition if another # caller added a value between the first get() and the add() # above. return self.get(key, default, version=version) return val def has_key(self, key, version=None): """ Return True if the key is in the cache and has not expired. """ return self.get(key, version=version) is not None def incr(self, key, delta=1, version=None): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta self.set(key, new_value, version=version) return new_value def decr(self, key, delta=1, version=None): """ Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception. """ return self.incr(key, -delta, version=version) def __contains__(self, key): """ Return True if the key is in the cache and has not expired. """ # This is a separate method, rather than just a copy of has_key(), # so that it always has the same functionality as has_key(), even # if a subclass overrides it. return self.has_key(key) def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. On backends that support it, return a list of keys that failed insertion, or an empty list if all keys were inserted successfully. """ for key, value in data.items(): self.set(key, value, timeout=timeout, version=version) return [] def delete_many(self, keys, version=None): """ Delete a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times. """ for key in keys: self.delete(key, version=version) def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError('subclasses of BaseCache must provide a clear() method') def validate_key(self, key): """ Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn( 'Cache key will cause errors if used with memcached: %r ' '(longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH), CacheKeyWarning ) for char in key: if ord(char) < 33 or ord(char) == 127: warnings.warn( 'Cache key contains characters that will cause errors if ' 'used with memcached: %r' % key, CacheKeyWarning ) break def incr_version(self, key, delta=1, version=None): """ Add delta to the cache version for the supplied key. Return the new version. """ if version is None: version = self.version value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) self.set(key, value, version=version + delta) self.delete(key, version=version) return version + delta def decr_version(self, key, delta=1, version=None): """ Subtract delta from the cache version for the supplied key. Return the new version. """ return self.incr_version(key, -delta, version) def close(self, **kwargs): """Close the cache connection""" pass
cc98885cb549f53b9c6fffd1a18405b9925e4af869086ecdbe92c980ea7c6df9
"Dummy cache backend" from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache class DummyCache(BaseCache): def __init__(self, host, *args, **kwargs): super().__init__(*args, **kwargs) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) return True def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) return default def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): self.validate_key(key) return False def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) return False def clear(self): pass
2344699bdd161b679288637ca55000641476a50cf9a2adfce3811507da6ae39b
"Thread-safe in-memory cache backend." import pickle import time from collections import OrderedDict from threading import Lock from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache # Global in-memory store of cache data. Keyed by name, to provide # multiple named local memory caches. _caches = {} _expire_info = {} _locks = {} class LocMemCache(BaseCache): def __init__(self, name, params): super().__init__(params) self._cache = _caches.setdefault(name, OrderedDict()) self._expire_info = _expire_info.setdefault(name, {}) self._lock = _locks.setdefault(name, Lock()) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) with self._lock: if self._has_expired(key): self._set(key, pickled, timeout) return True return False def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) with self._lock: if self._has_expired(key): self._delete(key) return default pickled = self._cache[key] self._cache.move_to_end(key, last=False) return pickle.loads(pickled) def _set(self, key, value, timeout=DEFAULT_TIMEOUT): if len(self._cache) >= self._max_entries: self._cull() self._cache[key] = value self._cache.move_to_end(key, last=False) self._expire_info[key] = self.get_backend_timeout(timeout) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) with self._lock: self._set(key, pickled, timeout) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) with self._lock: if self._has_expired(key): return False self._expire_info[key] = self.get_backend_timeout(timeout) return True def incr(self, key, delta=1, version=None): key = self.make_key(key, version=version) self.validate_key(key) with self._lock: if self._has_expired(key): self._delete(key) raise ValueError("Key '%s' not found" % key) pickled = self._cache[key] value = pickle.loads(pickled) new_value = value + delta pickled = pickle.dumps(new_value, pickle.HIGHEST_PROTOCOL) self._cache[key] = pickled self._cache.move_to_end(key, last=False) return new_value def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) with self._lock: if self._has_expired(key): self._delete(key) return False return True def _has_expired(self, key): exp = self._expire_info.get(key, -1) return exp is not None and exp <= time.time() def _cull(self): if self._cull_frequency == 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self._cull_frequency for i in range(count): key, _ = self._cache.popitem() del self._expire_info[key] def _delete(self, key): try: del self._cache[key] del self._expire_info[key] except KeyError: pass def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) with self._lock: self._delete(key) def clear(self): with self._lock: self._cache.clear() self._expire_info.clear()
9755c511205b93535ecb96d482309854fa120f38e86f320adc6310cb1417d509
""" Email backend that writes messages to console instead of sending them. """ import sys import threading from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, *args, **kwargs): self.stream = kwargs.pop('stream', sys.stdout) self._lock = threading.RLock() super().__init__(*args, **kwargs) def write_message(self, message): msg = message.message() msg_data = msg.as_bytes() charset = msg.get_charset().get_output_charset() if msg.get_charset() else 'utf-8' msg_data = msg_data.decode(charset) self.stream.write('%s\n' % msg_data) self.stream.write('-' * 79) self.stream.write('\n') def send_messages(self, email_messages): """Write all messages to the stream in a thread-safe way.""" if not email_messages: return msg_count = 0 with self._lock: try: stream_created = self.open() for message in email_messages: self.write_message(message) self.stream.flush() # flush after each message msg_count += 1 if stream_created: self.close() except Exception: if not self.fail_silently: raise return msg_count
549ffd74158a038f0c5c1657554693cbd36181f4689daa40e9402354510f283f
# Mail backends shipped with Django.
38f45ce650ec07d19b95edb9d5fc17a74a2ad6a29e64cf53d894dc6702ffe63b
"""Email backend that writes messages to a file.""" import datetime import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail.backends.console import ( EmailBackend as ConsoleEmailBackend, ) class EmailBackend(ConsoleEmailBackend): def __init__(self, *args, file_path=None, **kwargs): self._fname = None if file_path is not None: self.file_path = file_path else: self.file_path = getattr(settings, 'EMAIL_FILE_PATH', None) # Make sure self.file_path is a string. if not isinstance(self.file_path, str): raise ImproperlyConfigured('Path for saving emails is invalid: %r' % self.file_path) self.file_path = os.path.abspath(self.file_path) # Make sure that self.file_path is a directory if it exists. if os.path.exists(self.file_path) and not os.path.isdir(self.file_path): raise ImproperlyConfigured( 'Path for saving email messages exists, but is not a directory: %s' % self.file_path ) # Try to create it, if it not exists. elif not os.path.exists(self.file_path): try: os.makedirs(self.file_path) except OSError as err: raise ImproperlyConfigured( 'Could not create directory for saving email messages: %s (%s)' % (self.file_path, err) ) # Make sure that self.file_path is writable. if not os.access(self.file_path, os.W_OK): raise ImproperlyConfigured('Could not write to directory: %s' % self.file_path) # Finally, call super(). # Since we're using the console-based backend as a base, # force the stream to be None, so we don't default to stdout kwargs['stream'] = None super().__init__(*args, **kwargs) def write_message(self, message): self.stream.write(message.message().as_bytes() + b'\n') self.stream.write(b'-' * 79) self.stream.write(b'\n') def _get_filename(self): """Return a unique file name.""" if self._fname is None: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") fname = "%s-%s.log" % (timestamp, abs(id(self))) self._fname = os.path.join(self.file_path, fname) return self._fname def open(self): if self.stream is None: self.stream = open(self._get_filename(), 'ab') return True return False def close(self): try: if self.stream is not None: self.stream.close() finally: self.stream = None
7fd39e6b0d510223c79ac4dd41a91e63311a6df3ad50bcf452f95d3f80b27699
"""Base email backend class.""" class BaseEmailBackend: """ Base class for email backend implementations. Subclasses must at least overwrite send_messages(). open() and close() can be called indirectly by using a backend object as a context manager: with backend as connection: # do something with connection pass """ def __init__(self, fail_silently=False, **kwargs): self.fail_silently = fail_silently def open(self): """ Open a network connection. This method can be overwritten by backend implementations to open a network connection. It's up to the backend implementation to track the status of a network connection if it's needed by the backend. This method can be called by applications to force a single network connection to be used when sending mails. See the send_messages() method of the SMTP backend for a reference implementation. The default implementation does nothing. """ pass def close(self): """Close a network connection.""" pass def __enter__(self): try: self.open() except Exception: self.close() raise return self def __exit__(self, exc_type, exc_value, traceback): self.close() def send_messages(self, email_messages): """ Send one or more EmailMessage objects and return the number of email messages sent. """ raise NotImplementedError('subclasses of BaseEmailBackend must override send_messages() method')
4c4daffbdeab4a037b9d9ff709facd73bfb452d93800b077a1b470f935dfcfdd
"""SMTP email backend class.""" import smtplib import socket import ssl import threading from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.message import sanitize_address from django.core.mail.utils import DNS_NAME class EmailBackend(BaseEmailBackend): """ A wrapper that manages the SMTP network connection. """ def __init__(self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs): super().__init__(fail_silently=fail_silently) self.host = host or settings.EMAIL_HOST self.port = port or settings.EMAIL_PORT self.username = settings.EMAIL_HOST_USER if username is None else username self.password = settings.EMAIL_HOST_PASSWORD if password is None else password self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout self.ssl_keyfile = settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile self.ssl_certfile = settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile if self.use_ssl and self.use_tls: raise ValueError( "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set " "one of those settings to True.") self.connection = None self._lock = threading.RLock() @property def connection_class(self): return smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP def open(self): """ Ensure an open connection to the email server. Return whether or not a new connection was required (True or False) or None if an exception passed silently. """ if self.connection: # Nothing to do if the connection is already open. return False # If local_hostname is not specified, socket.getfqdn() gets used. # For performance, we use the cached FQDN for local_hostname. connection_params = {'local_hostname': DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params['timeout'] = self.timeout if self.use_ssl: connection_params.update({ 'keyfile': self.ssl_keyfile, 'certfile': self.ssl_certfile, }) try: self.connection = self.connection_class(self.host, self.port, **connection_params) # TLS/SSL are mutually exclusive, so only attempt TLS over # non-secure connections. if not self.use_ssl and self.use_tls: self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) if self.username and self.password: self.connection.login(self.username, self.password) return True except (smtplib.SMTPException, socket.error): if not self.fail_silently: raise def close(self): """Close the connection to the email server.""" if self.connection is None: return try: try: self.connection.quit() except (ssl.SSLError, smtplib.SMTPServerDisconnected): # This happens when calling quit() on a TLS connection # sometimes, or when the connection was already disconnected # by the server. self.connection.close() except smtplib.SMTPException: if self.fail_silently: return raise finally: self.connection = None def send_messages(self, email_messages): """ Send one or more EmailMessage objects and return the number of email messages sent. """ if not email_messages: return with self._lock: new_conn_created = self.open() if not self.connection or new_conn_created is None: # We failed silently on open(). # Trying to send would be pointless. return num_sent = 0 for message in email_messages: sent = self._send(message) if sent: num_sent += 1 if new_conn_created: self.close() return num_sent def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False encoding = email_message.encoding or settings.DEFAULT_CHARSET from_email = sanitize_address(email_message.from_email, encoding) recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()] message = email_message.message() try: self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) except smtplib.SMTPException: if not self.fail_silently: raise return False return True
b08eed01adcc7c6e3750701176eb6d06f1006187e22dab20177f63cda64fbbd1
""" Dummy email backend that does nothing. """ from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def send_messages(self, email_messages): return len(list(email_messages))
3a04caff840686c05daad0ca63a6f060d2b0d8c5ee75cd0f485e46355a92ee09
""" Backend for test environment. """ from django.core import mail from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): """ An email backend for use during test sessions. The test connection stores email messages in a dummy outbox, rather than sending them out on the wire. The dummy outbox is accessible through the outbox instance attribute. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not hasattr(mail, 'outbox'): mail.outbox = [] def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() mail.outbox.append(message) msg_count += 1 return msg_count
e292fec59de734f6dccebb8566a9cbf314c7e4aac62ff0b502075f04c7d67f06
from urllib.parse import urlencode from urllib.request import urlopen from django.apps import apps as django_apps from django.conf import settings from django.core import paginator from django.core.exceptions import ImproperlyConfigured from django.urls import NoReverseMatch, reverse from django.utils import translation PING_URL = "https://www.google.com/webmasters/tools/ping" class SitemapNotFound(Exception): pass def ping_google(sitemap_url=None, ping_url=PING_URL): """ Alert Google that the sitemap for the current site has been updated. If sitemap_url is provided, it should be an absolute path to the sitemap for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this function will attempt to deduce it by using urls.reverse(). """ sitemap_full_url = _get_sitemap_full_url(sitemap_url) params = urlencode({'sitemap': sitemap_full_url}) urlopen('%s?%s' % (ping_url, params)) def _get_sitemap_full_url(sitemap_url): if not django_apps.is_installed('django.contrib.sites'): raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.") if sitemap_url is None: try: # First, try to get the "index" sitemap URL. sitemap_url = reverse('django.contrib.sitemaps.views.index') except NoReverseMatch: try: # Next, try for the "global" sitemap URL. sitemap_url = reverse('django.contrib.sitemaps.views.sitemap') except NoReverseMatch: pass if sitemap_url is None: raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.") Site = django_apps.get_model('sites.Site') current_site = Site.objects.get_current() return 'http://%s%s' % (current_site.domain, sitemap_url) class Sitemap: # This limit is defined by Google. See the index documentation at # http://www.sitemaps.org/protocol.html#index. limit = 50000 # If protocol is None, the URLs in the sitemap will use the protocol # with which the sitemap was requested. protocol = None def __get(self, name, obj, default=None): try: attr = getattr(self, name) except AttributeError: return default if callable(attr): return attr(obj) return attr def items(self): return [] def location(self, obj): return obj.get_absolute_url() @property def paginator(self): return paginator.Paginator(self.items(), self.limit) def get_urls(self, page=1, site=None, protocol=None): # Determine protocol if self.protocol is not None: protocol = self.protocol if protocol is None: protocol = 'http' # Determine domain if site is None: if django_apps.is_installed('django.contrib.sites'): Site = django_apps.get_model('sites.Site') try: site = Site.objects.get_current() except Site.DoesNotExist: pass if site is None: raise ImproperlyConfigured( "To use sitemaps, either enable the sites framework or pass " "a Site/RequestSite object in your view." ) domain = site.domain if getattr(self, 'i18n', False): urls = [] current_lang_code = translation.get_language() for lang_code, lang_name in settings.LANGUAGES: translation.activate(lang_code) urls += self._urls(page, protocol, domain) translation.activate(current_lang_code) else: urls = self._urls(page, protocol, domain) return urls def _urls(self, page, protocol, domain): urls = [] latest_lastmod = None all_items_lastmod = True # track if all items have a lastmod for item in self.paginator.page(page).object_list: loc = "%s://%s%s" % (protocol, domain, self.__get('location', item)) priority = self.__get('priority', item) lastmod = self.__get('lastmod', item) if all_items_lastmod: all_items_lastmod = lastmod is not None if (all_items_lastmod and (latest_lastmod is None or lastmod > latest_lastmod)): latest_lastmod = lastmod url_info = { 'item': item, 'location': loc, 'lastmod': lastmod, 'changefreq': self.__get('changefreq', item), 'priority': str(priority if priority is not None else ''), } urls.append(url_info) if all_items_lastmod and latest_lastmod: self.latest_lastmod = latest_lastmod return urls class GenericSitemap(Sitemap): priority = None changefreq = None def __init__(self, info_dict, priority=None, changefreq=None, protocol=None): self.queryset = info_dict['queryset'] self.date_field = info_dict.get('date_field') self.priority = priority self.changefreq = changefreq self.protocol = protocol def items(self): # Make sure to return a clone; we don't want premature evaluation. return self.queryset.filter() def lastmod(self, item): if self.date_field is not None: return getattr(item, self.date_field) return None default_app_config = 'django.contrib.sitemaps.apps.SiteMapsConfig'
92d63d3dc5ac9afe533a5bc4746e882fc6416c632d651a4edb88f983b0c68a55
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class SiteMapsConfig(AppConfig): name = 'django.contrib.sitemaps' verbose_name = _("Site Maps")
28ff9c0a40f854615b77865abd62bbf6002465af3700f791813c7e7a8ba7cb83
import datetime from calendar import timegm from functools import wraps from django.contrib.sites.shortcuts import get_current_site from django.core.paginator import EmptyPage, PageNotAnInteger from django.http import Http404 from django.template.response import TemplateResponse from django.urls import reverse from django.utils.http import http_date def x_robots_tag(func): @wraps(func) def inner(request, *args, **kwargs): response = func(request, *args, **kwargs) response['X-Robots-Tag'] = 'noindex, noodp, noarchive' return response return inner @x_robots_tag def index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap'): req_protocol = request.scheme req_site = get_current_site(request) sites = [] # all sections' sitemap URLs for section, site in sitemaps.items(): # For each section label, add links of all pages of its sitemap # (usually generated by the `sitemap` view). if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = reverse(sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) # Add links to all pages of the sitemap. for page in range(2, site.paginator.num_pages + 1): sites.append('%s?p=%s' % (absolute_url, page)) return TemplateResponse(request, template_name, {'sitemaps': sites}, content_type=content_type) @x_robots_tag def sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml'): req_protocol = request.scheme req_site = get_current_site(request) if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps = [sitemaps[section]] else: maps = sitemaps.values() page = request.GET.get("p", 1) lastmod = None all_sites_lastmod = True urls = [] for site in maps: try: if callable(site): site = site() urls.extend(site.get_urls(page=page, site=req_site, protocol=req_protocol)) if all_sites_lastmod: site_lastmod = getattr(site, 'latest_lastmod', None) if site_lastmod is not None: site_lastmod = ( site_lastmod.utctimetuple() if isinstance(site_lastmod, datetime.datetime) else site_lastmod.timetuple() ) lastmod = site_lastmod if lastmod is None else max(lastmod, site_lastmod) else: all_sites_lastmod = False except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) response = TemplateResponse(request, template_name, {'urlset': urls}, content_type=content_type) if all_sites_lastmod and lastmod is not None: # if lastmod is defined for all sites, set header so as # ConditionalGetMiddleware is able to send 304 NOT MODIFIED response['Last-Modified'] = http_date(timegm(lastmod)) return response
4a3b769a089af2fa92a484abb3aecddbbac05e0bea47e30fab7ed507e9e64af1
from django.contrib.messages.api import * # NOQA from django.contrib.messages.constants import * # NOQA default_app_config = 'django.contrib.messages.apps.MessagesConfig'
c865c129f579585fc495c3db5f8c098d7aba8f3a77f6db673bbb29f0dfc8cce4
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class MessagesConfig(AppConfig): name = 'django.contrib.messages' verbose_name = _("Messages")
b163f60cffa7f1958e4ccf812c50c6ac7fe5fafa06c2b4b10b43a013226dd45e
from django.contrib.messages import constants from django.contrib.messages.storage import default_storage __all__ = ( 'add_message', 'get_messages', 'get_level', 'set_level', 'debug', 'info', 'success', 'warning', 'error', 'MessageFailure', ) class MessageFailure(Exception): pass def add_message(request, level, message, extra_tags='', fail_silently=False): """ Attempt to add a message to the request using the 'messages' app. """ try: messages = request._messages except AttributeError: if not hasattr(request, 'META'): raise TypeError( "add_message() argument must be an HttpRequest object, not " "'%s'." % request.__class__.__name__ ) if not fail_silently: raise MessageFailure( 'You cannot add messages without installing ' 'django.contrib.messages.middleware.MessageMiddleware' ) else: return messages.add(level, message, extra_tags) def get_messages(request): """ Return the message storage on the request if it exists, otherwise return an empty list. """ return getattr(request, '_messages', []) def get_level(request): """ Return the minimum level of messages to be recorded. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, use the ``INFO`` level. """ storage = getattr(request, '_messages', default_storage(request)) return storage.level def set_level(request, level): """ Set the minimum level of messages to be recorded, and return ``True`` if the level was recorded successfully. If set to ``None``, use the default level (see the get_level() function). """ if not hasattr(request, '_messages'): return False request._messages.level = level return True def debug(request, message, extra_tags='', fail_silently=False): """Add a message with the ``DEBUG`` level.""" add_message(request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently) def info(request, message, extra_tags='', fail_silently=False): """Add a message with the ``INFO`` level.""" add_message(request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently) def success(request, message, extra_tags='', fail_silently=False): """Add a message with the ``SUCCESS`` level.""" add_message(request, constants.SUCCESS, message, extra_tags=extra_tags, fail_silently=fail_silently) def warning(request, message, extra_tags='', fail_silently=False): """Add a message with the ``WARNING`` level.""" add_message(request, constants.WARNING, message, extra_tags=extra_tags, fail_silently=fail_silently) def error(request, message, extra_tags='', fail_silently=False): """Add a message with the ``ERROR`` level.""" add_message(request, constants.ERROR, message, extra_tags=extra_tags, fail_silently=fail_silently)
e8fcc0af22747baa0ec2d48032b8c022c606bbf9d622980c1b4a7c7ffaf33ab8
from django.conf import settings from django.contrib.messages import constants def get_level_tags(): """ Return the message level tags. """ return { **constants.DEFAULT_TAGS, **getattr(settings, 'MESSAGE_TAGS', {}), }
d0b9e2663c59ec5c7607161d274b5caee846e2490110486c73b52b71fdf53671
from django.contrib.messages.api import get_messages from django.contrib.messages.constants import DEFAULT_LEVELS def messages(request): """ Return a lazy 'messages' context variable as well as 'DEFAULT_MESSAGE_LEVELS'. """ return { 'messages': get_messages(request), 'DEFAULT_MESSAGE_LEVELS': DEFAULT_LEVELS, }
599c63cef128288ee6802852169fe0f5efb3507f2be892e1bbdb05b1fb5318d0
DEBUG = 10 INFO = 20 SUCCESS = 25 WARNING = 30 ERROR = 40 DEFAULT_TAGS = { DEBUG: 'debug', INFO: 'info', SUCCESS: 'success', WARNING: 'warning', ERROR: 'error', } DEFAULT_LEVELS = { 'DEBUG': DEBUG, 'INFO': INFO, 'SUCCESS': SUCCESS, 'WARNING': WARNING, 'ERROR': ERROR, }
e0bf9bce04a34f0f8a821f1683c30eaa424fca295ac725e2fe31f55293f587e5
from django.conf import settings from django.contrib.messages.storage import default_storage from django.utils.deprecation import MiddlewareMixin class MessageMiddleware(MiddlewareMixin): """ Middleware that handles temporary messages. """ def process_request(self, request): request._messages = default_storage(request) def process_response(self, request, response): """ Update the storage backend (i.e., save the messages). Raise ValueError if not all messages could be stored and DEBUG is True. """ # A higher middleware layer may return a request which does not contain # messages storage, so make no assumption that it will be there. if hasattr(request, '_messages'): unstored_messages = request._messages.update(response) if unstored_messages and settings.DEBUG: raise ValueError('Not all temporary messages could be stored.') return response
479c43d832e600ed31e841a913c4d7e5b92ee338a83a262442702d7faafe5401
from django.contrib import messages class SuccessMessageMixin: """ Add a success message on successful form submission. """ success_message = '' def form_valid(self, form): response = super().form_valid(form) success_message = self.get_success_message(form.cleaned_data) if success_message: messages.success(self.request, success_message) return response def get_success_message(self, cleaned_data): return self.success_message % cleaned_data
a18f9e07300ec297f9836db6faf947e41587a43ce9923fc35bbfd71838fbce02
default_app_config = 'django.contrib.admindocs.apps.AdminDocsConfig'
ad5dda5957af808ea8f3ff56634c90eb63b9092311459ad5c1916dd60a5f2a4d
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class AdminDocsConfig(AppConfig): name = 'django.contrib.admindocs' verbose_name = _("Administrative Documentation")
d473190ea771dcea2bdc3db67238ec019dce9071570168d56b77923d85301797
"Misc. utility functions/classes for admin documentation generator." import re from email.errors import HeaderParseError from email.parser import HeaderParser from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.safestring import mark_safe try: import docutils.core import docutils.nodes import docutils.parsers.rst.roles except ImportError: docutils_is_available = False else: docutils_is_available = True def get_view_name(view_func): mod_name = view_func.__module__ view_name = getattr(view_func, '__qualname__', view_func.__class__.__name__) return mod_name + '.' + view_name def trim_docstring(docstring): """ Uniformly trim leading/trailing whitespace from docstrings. Based on https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation """ if not docstring or not docstring.strip(): return '' # Convert tabs to spaces and split into lines lines = docstring.expandtabs().splitlines() indent = min(len(line) - len(line.lstrip()) for line in lines if line.lstrip()) trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]] return "\n".join(trimmed).strip() def parse_docstring(docstring): """ Parse out the parts of a docstring. Return (title, body, metadata). """ docstring = trim_docstring(docstring) parts = re.split(r'\n{2,}', docstring) title = parts[0] if len(parts) == 1: body = '' metadata = {} else: parser = HeaderParser() try: metadata = parser.parsestr(parts[-1]) except HeaderParseError: metadata = {} body = "\n\n".join(parts[1:]) else: metadata = dict(metadata.items()) if metadata: body = "\n\n".join(parts[1:-1]) else: body = "\n\n".join(parts[1:]) return title, body, metadata def parse_rst(text, default_reference_context, thing_being_parsed=None): """ Convert the string from reST to an XHTML fragment. """ overrides = { 'doctitle_xform': True, 'initial_header_level': 3, "default_reference_context": default_reference_context, "link_base": reverse('django-admindocs-docroot').rstrip('/'), 'raw_enabled': False, 'file_insertion_enabled': False, } thing_being_parsed = thing_being_parsed and force_bytes('<%s>' % thing_being_parsed) # Wrap ``text`` in some reST that sets the default role to ``cmsreference``, # then restores it. source = """ .. default-role:: cmsreference %s .. default-role:: """ parts = docutils.core.publish_parts( source % text, source_path=thing_being_parsed, destination_path=None, writer_name='html', settings_overrides=overrides, ) return mark_safe(parts['fragment']) # # reST roles # ROLES = { 'model': '%s/models/%s/', 'view': '%s/views/%s/', 'template': '%s/templates/%s/', 'filter': '%s/filters/#%s', 'tag': '%s/tags/#%s', } def create_reference_role(rolename, urlbase): def _role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] node = docutils.nodes.reference( rawtext, text, refuri=(urlbase % ( inliner.document.settings.link_base, text.lower(), )), **options ) return [node], [] docutils.parsers.rst.roles.register_canonical_role(rolename, _role) def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] context = inliner.document.settings.default_reference_context node = docutils.nodes.reference( rawtext, text, refuri=(ROLES[context] % ( inliner.document.settings.link_base, text.lower(), )), **options ) return [node], [] if docutils_is_available: docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role) for name, urlbase in ROLES.items(): create_reference_role(name, urlbase) # Match the beginning of a named or unnamed group. named_group_matcher = re.compile(r'\(\?P(<\w+>)') unnamed_group_matcher = re.compile(r'\(') def replace_named_groups(pattern): r""" Find named groups in `pattern` and replace them with the group name. E.g., 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^<a>/b/(\w+)$ 2. ^(?P<a>\w+)/b/(?P<c>\w+)/$ ==> ^<a>/b/<c>/$ """ named_group_indices = [ (m.start(0), m.end(0), m.group(1)) for m in named_group_matcher.finditer(pattern) ] # Tuples of (named capture group pattern, group name). group_pattern_and_name = [] # Loop over the groups and their start and end indices. for start, end, group_name in named_group_indices: # Handle nested parentheses, e.g. '^(?P<a>(x|y))/b'. unmatched_open_brackets, prev_char = 1, None for idx, val in enumerate(list(pattern[end:])): # If brackets are balanced, the end of the string for the current # named capture group pattern has been reached. if unmatched_open_brackets == 0: group_pattern_and_name.append((pattern[start:end + idx], group_name)) break # Check for unescaped `(` and `)`. They mark the start and end of a # nested group. if val == '(' and prev_char != '\\': unmatched_open_brackets += 1 elif val == ')' and prev_char != '\\': unmatched_open_brackets -= 1 prev_char = val # Replace the string for named capture groups with their group names. for group_pattern, group_name in group_pattern_and_name: pattern = pattern.replace(group_pattern, group_name) return pattern def replace_unnamed_groups(pattern): r""" Find unnamed groups in `pattern` and replace them with '<var>'. E.g., 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^(?P<a>\w+)/b/<var>$ 2. ^(?P<a>\w+)/b/((x|y)\w+)$ ==> ^(?P<a>\w+)/b/<var>$ """ unnamed_group_indices = [m.start(0) for m in unnamed_group_matcher.finditer(pattern)] # Indices of the start of unnamed capture groups. group_indices = [] # Loop over the start indices of the groups. for start in unnamed_group_indices: # Handle nested parentheses, e.g. '^b/((x|y)\w+)$'. unmatched_open_brackets, prev_char = 1, None for idx, val in enumerate(list(pattern[start + 1:])): if unmatched_open_brackets == 0: group_indices.append((start, start + 1 + idx)) break # Check for unescaped `(` and `)`. They mark the start and end of # a nested group. if val == '(' and prev_char != '\\': unmatched_open_brackets += 1 elif val == ')' and prev_char != '\\': unmatched_open_brackets -= 1 prev_char = val # Remove unnamed group matches inside other unnamed capture groups. group_start_end_indices = [] prev_end = None for start, end in group_indices: if prev_end and start > prev_end or not prev_end: group_start_end_indices.append((start, end)) prev_end = end if group_start_end_indices: # Replace unnamed groups with <var>. Handle the fact that replacing the # string between indices will change string length and thus indices # will point to the wrong substring if not corrected. final_pattern, prev_end = [], None for start, end in group_start_end_indices: if prev_end: final_pattern.append(pattern[prev_end:start]) final_pattern.append(pattern[:start] + '<var>') prev_end = end final_pattern.append(pattern[prev_end:]) return ''.join(final_pattern) else: return pattern
cdd1da57ad3224c8ee2ea3bdc54d07fa3ee1cf53e64ac7a9116640d861fe788d
from django.contrib.admindocs import views from django.urls import path, re_path urlpatterns = [ path( '', views.BaseAdminDocsView.as_view(template_name='admin_doc/index.html'), name='django-admindocs-docroot', ), path( 'bookmarklets/', views.BookmarkletsView.as_view(), name='django-admindocs-bookmarklets', ), path( 'tags/', views.TemplateTagIndexView.as_view(), name='django-admindocs-tags', ), path( 'filters/', views.TemplateFilterIndexView.as_view(), name='django-admindocs-filters', ), path( 'views/', views.ViewIndexView.as_view(), name='django-admindocs-views-index', ), path( 'views/<view>/', views.ViewDetailView.as_view(), name='django-admindocs-views-detail', ), path( 'models/', views.ModelIndexView.as_view(), name='django-admindocs-models-index', ), re_path( r'^models/(?P<app_label>[^\.]+)\.(?P<model_name>[^/]+)/$', views.ModelDetailView.as_view(), name='django-admindocs-models-detail', ), path( 'templates/<path:template>/', views.TemplateDetailView.as_view(), name='django-admindocs-templates', ), ]
019a52dc36ea5fb8e11a5dd56b5ca51a5ec85eb452fb9c5a0620c0f022c4c93d
from django.conf import settings from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin from .utils import get_view_name class XViewMiddleware(MiddlewareMixin): """ Add an X-View header to internal HEAD requests. """ def process_view(self, request, view_func, view_args, view_kwargs): """ If the request method is HEAD and either the IP is internal or the user is a logged-in staff member, return a responsewith an x-view header indicating the view function. This is used to lookup the view function for an arbitrary page. """ assert hasattr(request, 'user'), ( "The XView middleware requires authentication middleware to be " "installed. Edit your MIDDLEWARE%s setting to insert " "'django.contrib.auth.middleware.AuthenticationMiddleware'." % ( "_CLASSES" if settings.MIDDLEWARE is None else "" ) ) if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or (request.user.is_active and request.user.is_staff)): response = HttpResponse() response['X-View'] = get_view_name(view_func) return response
3792269479c3929c38b1d7b08169214675b4bfc2c3c4d118e8d756e6fed9b9a7
import inspect from importlib import import_module from pathlib import Path from django.apps import apps from django.conf import settings from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admindocs import utils from django.contrib.admindocs.utils import ( replace_named_groups, replace_unnamed_groups, ) from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf, reverse from django.utils.decorators import method_decorator from django.utils.inspect import ( func_accepts_kwargs, func_accepts_var_args, func_has_no_args, get_func_full_args, ) from django.utils.translation import gettext as _ from django.views.generic import TemplateView from .utils import get_view_name # Exclude methods starting with these strings from documentation MODEL_METHODS_EXCLUDE = ('_', 'add_', 'delete', 'save', 'set_') class BaseAdminDocsView(TemplateView): """ Base view for admindocs views. """ @method_decorator(staff_member_required) def dispatch(self, request, *args, **kwargs): if not utils.docutils_is_available: # Display an error message for people without docutils self.template_name = 'admin_doc/missing_docutils.html' return self.render_to_response(admin.site.each_context(request)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): return super().get_context_data(**{ **kwargs, 'root_path': reverse('admin:index'), **admin.site.each_context(self.request), }) class BookmarkletsView(BaseAdminDocsView): template_name = 'admin_doc/bookmarklets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'admin_url': "%s://%s%s" % ( self.request.scheme, self.request.get_host(), context['root_path']) }) return context class TemplateTagIndexView(BaseAdminDocsView): template_name = 'admin_doc/template_tag_index.html' def get_context_data(self, **kwargs): tags = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for tag_name, tag_func in library.tags.items(): title, body, metadata = utils.parse_docstring(tag_func.__doc__) title = title and utils.parse_rst(title, 'tag', _('tag:') + tag_name) body = body and utils.parse_rst(body, 'tag', _('tag:') + tag_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'tag', _('tag:') + tag_name) tag_library = module_name.split('.')[-1] tags.append({ 'name': tag_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return super().get_context_data(**{**kwargs, 'tags': tags}) class TemplateFilterIndexView(BaseAdminDocsView): template_name = 'admin_doc/template_filter_index.html' def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) title = title and utils.parse_rst(title, 'filter', _('filter:') + filter_name) body = body and utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name) tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return super().get_context_data(**{**kwargs, 'filters': filters}) class ViewIndexView(BaseAdminDocsView): template_name = 'admin_doc/view_index.html' def get_context_data(self, **kwargs): views = [] urlconf = import_module(settings.ROOT_URLCONF) view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) for (func, regex, namespace, name) in view_functions: views.append({ 'full_name': get_view_name(func), 'url': simplify_regex(regex), 'url_name': ':'.join((namespace or []) + (name and [name] or [])), 'namespace': ':'.join((namespace or [])), 'name': name, }) return super().get_context_data(**{**kwargs, 'views': views}) class ViewDetailView(BaseAdminDocsView): template_name = 'admin_doc/view_detail.html' @staticmethod def _get_view_func(view): urlconf = get_urlconf() if get_resolver(urlconf)._is_callback(view): mod, func = get_mod_func(view) try: # Separate the module and function, e.g. # 'mymodule.views.myview' -> 'mymodule.views', 'myview'). return getattr(import_module(mod), func) except ImportError: # Import may fail because view contains a class name, e.g. # 'mymodule.views.ViewContainer.my_view', so mod takes the form # 'mymodule.views.ViewContainer'. Parse it again to separate # the module and class. mod, klass = get_mod_func(mod) return getattr(getattr(import_module(mod), klass), func) def get_context_data(self, **kwargs): view = self.kwargs['view'] view_func = self._get_view_func(view) if view_func is None: raise Http404 title, body, metadata = utils.parse_docstring(view_func.__doc__) title = title and utils.parse_rst(title, 'view', _('view:') + view) body = body and utils.parse_rst(body, 'view', _('view:') + view) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view) return super().get_context_data(**{ **kwargs, 'name': view, 'summary': title, 'body': body, 'meta': metadata, }) class ModelIndexView(BaseAdminDocsView): template_name = 'admin_doc/model_index.html' def get_context_data(self, **kwargs): m_list = [m._meta for m in apps.get_models()] return super().get_context_data(**{**kwargs, 'models': m_list}) class ModelDetailView(BaseAdminDocsView): template_name = 'admin_doc/model_detail.html' def get_context_data(self, **kwargs): model_name = self.kwargs['model_name'] # Get the model class. try: app_config = apps.get_app_config(self.kwargs['app_label']) except LookupError: raise Http404(_("App %(app_label)r not found") % self.kwargs) try: model = app_config.get_model(model_name) except LookupError: raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % self.kwargs) opts = model._meta title, body, metadata = utils.parse_docstring(model.__doc__) title = title and utils.parse_rst(title, 'model', _('model:') + model_name) body = body and utils.parse_rst(body, 'model', _('model:') + model_name) # Gather fields/field descriptions. fields = [] for field in opts.fields: # ForeignKey is a special case since the field will actually be a # descriptor that returns the other object if isinstance(field, models.ForeignKey): data_type = field.remote_field.model.__name__ app_label = field.remote_field.model._meta.app_label verbose = utils.parse_rst( (_("the related `%(app_label)s.%(data_type)s` object") % { 'app_label': app_label, 'data_type': data_type, }), 'model', _('model:') + data_type, ) else: data_type = get_readable_field_data_type(field) verbose = field.verbose_name fields.append({ 'name': field.name, 'data_type': data_type, 'verbose': verbose or '', 'help_text': field.help_text, }) # Gather many-to-many fields. for field in opts.many_to_many: data_type = field.remote_field.model.__name__ app_label = field.remote_field.model._meta.app_label verbose = _("related `%(app_label)s.%(object_name)s` objects") % { 'app_label': app_label, 'object_name': data_type, } fields.append({ 'name': "%s.all" % field.name, "data_type": 'List', 'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name), }) fields.append({ 'name': "%s.count" % field.name, 'data_type': 'Integer', 'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name), }) methods = [] # Gather model methods. for func_name, func in model.__dict__.items(): if inspect.isfunction(func) or isinstance(func, property): try: for exclude in MODEL_METHODS_EXCLUDE: if func_name.startswith(exclude): raise StopIteration except StopIteration: continue verbose = func.__doc__ verbose = verbose and ( utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.model_name) ) # Show properties and methods without arguments as fields. # Otherwise, show as a 'method with arguments'. if isinstance(func, property): fields.append({ 'name': func_name, 'data_type': get_return_data_type(func_name), 'verbose': verbose or '' }) elif func_has_no_args(func) and not func_accepts_kwargs(func) and not func_accepts_var_args(func): fields.append({ 'name': func_name, 'data_type': get_return_data_type(func_name), 'verbose': verbose or '', }) else: arguments = get_func_full_args(func) # Join arguments with ', ' and in case of default value, # join it with '='. Use repr() so that strings will be # correctly displayed. print_arguments = ', '.join([ '='.join(list(arg_el[:1]) + [repr(el) for el in arg_el[1:]]) for arg_el in arguments ]) methods.append({ 'name': func_name, 'arguments': print_arguments, 'verbose': verbose or '', }) # Gather related objects for rel in opts.related_objects: verbose = _("related `%(app_label)s.%(object_name)s` objects") % { 'app_label': rel.related_model._meta.app_label, 'object_name': rel.related_model._meta.object_name, } accessor = rel.get_accessor_name() fields.append({ 'name': "%s.all" % accessor, 'data_type': 'List', 'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name), }) fields.append({ 'name': "%s.count" % accessor, 'data_type': 'Integer', 'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name), }) return super().get_context_data(**{ **kwargs, 'name': '%s.%s' % (opts.app_label, opts.object_name), 'summary': title, 'description': body, 'fields': fields, 'methods': methods, }) class TemplateDetailView(BaseAdminDocsView): template_name = 'admin_doc/template_detail.html' def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(directory) / template if template_file.exists(): with template_file.open() as f: template_contents = f.read() else: template_contents = '' templates.append({ 'file': template_file, 'exists': template_file.exists(), 'contents': template_contents, 'order': index, }) return super().get_context_data(**{ **kwargs, 'name': template, 'templates': templates, }) #################### # Helper functions # #################### def get_return_data_type(func_name): """Return a somewhat-helpful data type given a function name""" if func_name.startswith('get_'): if func_name.endswith('_list'): return 'List' elif func_name.endswith('_count'): return 'Integer' return '' def get_readable_field_data_type(field): """ Return the description for a given field type, if it exists. Fields' descriptions can contain format strings, which will be interpolated with the values of field.__dict__ before being output. """ return field.description % field.__dict__ def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a two-tuple: (view_func, regex) """ views = [] for p in urlpatterns: if hasattr(p, 'url_patterns'): try: patterns = p.url_patterns except ImportError: continue views.extend(extract_views_from_urlpatterns( patterns, base + str(p.pattern), (namespace or []) + (p.namespace and [p.namespace] or []) )) elif hasattr(p, 'callback'): try: views.append((p.callback, base + str(p.pattern), namespace, p.name)) except ViewDoesNotExist: continue else: raise TypeError(_("%s does not appear to be a urlpattern object") % p) return views def simplify_regex(pattern): r""" Clean up urlpattern regexes into something more readable by humans. For example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" into "/<sport_slug>/athletes/<athlete_slug>/". """ pattern = replace_named_groups(pattern) pattern = replace_unnamed_groups(pattern) # clean up any outstanding regex-y characters. pattern = pattern.replace('^', '').replace('$', '').replace('?', '') if not pattern.startswith('/'): pattern = '/' + pattern return pattern
aac59f9beb846585aededbf9fc79fbd219576e7da0c3bbdc680ad2d384604bce
from django.db.models import Index from django.utils.functional import cached_property __all__ = ['BrinIndex', 'GinIndex', 'GistIndex'] class PostgresIndex(Index): @cached_property def max_name_length(self): # Allow an index name longer than 30 characters when the suffix is # longer than the usual 3 character limit. The 30 character limit for # cross-database compatibility isn't applicable to PostgreSQL-specific # indexes. return Index.max_name_length - len(Index.suffix) + len(self.suffix) def create_sql(self, model, schema_editor, using=''): statement = super().create_sql(model, schema_editor, using=' USING %s' % self.suffix) with_params = self.get_with_params() if with_params: statement.parts['extra'] = 'WITH (%s) %s' % ( ', '.join(with_params), statement.parts['extra'], ) return statement def get_with_params(self): return [] class BrinIndex(PostgresIndex): suffix = 'brin' def __init__(self, *, pages_per_range=None, **kwargs): if pages_per_range is not None and pages_per_range <= 0: raise ValueError('pages_per_range must be None or a positive integer') self.pages_per_range = pages_per_range super().__init__(**kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.pages_per_range is not None: kwargs['pages_per_range'] = self.pages_per_range return path, args, kwargs def get_with_params(self): with_params = [] if self.pages_per_range is not None: with_params.append('pages_per_range = %d' % self.pages_per_range) return with_params class GinIndex(PostgresIndex): suffix = 'gin' def __init__(self, *, fastupdate=None, gin_pending_list_limit=None, **kwargs): self.fastupdate = fastupdate self.gin_pending_list_limit = gin_pending_list_limit super().__init__(**kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.fastupdate is not None: kwargs['fastupdate'] = self.fastupdate if self.gin_pending_list_limit is not None: kwargs['gin_pending_list_limit'] = self.gin_pending_list_limit return path, args, kwargs def get_with_params(self): with_params = [] if self.gin_pending_list_limit is not None: with_params.append('gin_pending_list_limit = %d' % self.gin_pending_list_limit) if self.fastupdate is not None: with_params.append('fastupdate = %s' % ('on' if self.fastupdate else 'off')) return with_params class GistIndex(PostgresIndex): suffix = 'gist' def __init__(self, *, buffering=None, fillfactor=None, **kwargs): self.buffering = buffering self.fillfactor = fillfactor super().__init__(**kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.buffering is not None: kwargs['buffering'] = self.buffering if self.fillfactor is not None: kwargs['fillfactor'] = self.fillfactor return path, args, kwargs def get_with_params(self): with_params = [] if self.buffering is not None: with_params.append('buffering = %s' % ('on' if self.buffering else 'off')) if self.fillfactor is not None: with_params.append('fillfactor = %d' % self.fillfactor) return with_params
8ed9fdfa6c0e2127390ff614a10e73ff7b0de1b10f37104e083cdb18d6a0fe67
default_app_config = 'django.contrib.postgres.apps.PostgresConfig'
879462e57d1a85adbd60c31f2ccd4e2aaeebaca59e49389d1f35c585121857e4
from django.db.models import Field, FloatField from django.db.models.expressions import CombinedExpression, Func, Value from django.db.models.functions import Coalesce from django.db.models.lookups import Lookup class SearchVectorExact(Lookup): lookup_name = 'exact' def process_rhs(self, qn, connection): if not hasattr(self.rhs, 'resolve_expression'): config = getattr(self.lhs, 'config', None) self.rhs = SearchQuery(self.rhs, config=config) rhs, rhs_params = super().process_rhs(qn, connection) return rhs, rhs_params def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return '%s @@ %s = true' % (lhs, rhs), params class SearchVectorField(Field): def db_type(self, connection): return 'tsvector' class SearchQueryField(Field): def db_type(self, connection): return 'tsquery' class SearchVectorCombinable: ADD = '||' def _combine(self, other, connector, reversed): if not isinstance(other, SearchVectorCombinable) or not self.config == other.config: raise TypeError('SearchVector can only be combined with other SearchVectors') if reversed: return CombinedSearchVector(other, connector, self, self.config) return CombinedSearchVector(self, connector, other, self.config) class SearchVector(SearchVectorCombinable, Func): function = 'to_tsvector' arg_joiner = " || ' ' || " output_field = SearchVectorField() config = None def __init__(self, *expressions, **extra): super().__init__(*expressions, **extra) self.source_expressions = [ Coalesce(expression, Value('')) for expression in self.source_expressions ] self.config = self.extra.get('config', self.config) weight = self.extra.get('weight') if weight is not None and not hasattr(weight, 'resolve_expression'): weight = Value(weight) self.weight = weight def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): resolved = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) if self.config: if not hasattr(self.config, 'resolve_expression'): resolved.config = Value(self.config).resolve_expression(query, allow_joins, reuse, summarize, for_save) else: resolved.config = self.config.resolve_expression(query, allow_joins, reuse, summarize, for_save) return resolved def as_sql(self, compiler, connection, function=None, template=None): config_params = [] if template is None: if self.config: config_sql, config_params = compiler.compile(self.config) template = "%(function)s({}::regconfig, %(expressions)s)".format(config_sql.replace('%', '%%')) else: template = self.template sql, params = super().as_sql(compiler, connection, function=function, template=template) extra_params = [] if self.weight: weight_sql, extra_params = compiler.compile(self.weight) sql = 'setweight({}, {})'.format(sql, weight_sql) return sql, config_params + params + extra_params class CombinedSearchVector(SearchVectorCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config super().__init__(lhs, connector, rhs, output_field) class SearchQueryCombinable: BITAND = '&&' BITOR = '||' def _combine(self, other, connector, reversed): if not isinstance(other, SearchQueryCombinable): raise TypeError( 'SearchQuery can only be combined with other SearchQuerys, ' 'got {}.'.format(type(other)) ) if not self.config == other.config: raise TypeError("SearchQuery configs don't match.") if reversed: return CombinedSearchQuery(other, connector, self, self.config) return CombinedSearchQuery(self, connector, other, self.config) # On Combinable, these are not implemented to reduce confusion with Q. In # this case we are actually (ab)using them to do logical combination so # it's consistent with other usage in Django. def __or__(self, other): return self._combine(other, self.BITOR, False) def __ror__(self, other): return self._combine(other, self.BITOR, True) def __and__(self, other): return self._combine(other, self.BITAND, False) def __rand__(self, other): return self._combine(other, self.BITAND, True) class SearchQuery(SearchQueryCombinable, Value): output_field = SearchQueryField() def __init__(self, value, output_field=None, *, config=None, invert=False): self.config = config self.invert = invert super().__init__(value, output_field=output_field) def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): resolved = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) if self.config: if not hasattr(self.config, 'resolve_expression'): resolved.config = Value(self.config).resolve_expression(query, allow_joins, reuse, summarize, for_save) else: resolved.config = self.config.resolve_expression(query, allow_joins, reuse, summarize, for_save) return resolved def as_sql(self, compiler, connection): params = [self.value] if self.config: config_sql, config_params = compiler.compile(self.config) template = 'plainto_tsquery({}::regconfig, %s)'.format(config_sql) params = config_params + [self.value] else: template = 'plainto_tsquery(%s)' if self.invert: template = '!!({})'.format(template) return template, params def _combine(self, other, connector, reversed): combined = super()._combine(other, connector, reversed) combined.output_field = SearchQueryField() return combined def __invert__(self): return type(self)(self.value, config=self.config, invert=not self.invert) class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config super().__init__(lhs, connector, rhs, output_field) class SearchRank(Func): function = 'ts_rank' output_field = FloatField() def __init__(self, vector, query, **extra): if not hasattr(vector, 'resolve_expression'): vector = SearchVector(vector) if not hasattr(query, 'resolve_expression'): query = SearchQuery(query) weights = extra.get('weights') if weights is not None and not hasattr(weights, 'resolve_expression'): weights = Value(weights) self.weights = weights super().__init__(vector, query, **extra) def as_sql(self, compiler, connection, function=None, template=None): extra_params = [] extra_context = {} if template is None and self.extra.get('weights'): if self.weights: template = '%(function)s(%(weights)s, %(expressions)s)' weight_sql, extra_params = compiler.compile(self.weights) extra_context['weights'] = weight_sql sql, params = super().as_sql( compiler, connection, function=function, template=template, **extra_context ) return sql, extra_params + params SearchVectorField.register_lookup(SearchVectorExact) class TrigramBase(Func): output_field = FloatField() def __init__(self, expression, string, **extra): if not hasattr(string, 'resolve_expression'): string = Value(string) super().__init__(expression, string, **extra) class TrigramSimilarity(TrigramBase): function = 'SIMILARITY' class TrigramDistance(TrigramBase): function = '' arg_joiner = ' <-> '
e2b4d3c1f1a64ac2e888c0604fb3cb9b1ed139269ab35f2d919a749f6adc8f09
from django.apps import AppConfig from django.db import connections from django.db.backends.signals import connection_created from django.db.models import CharField, TextField from django.utils.translation import gettext_lazy as _ from .lookups import SearchLookup, TrigramSimilar, Unaccent from .signals import register_type_handlers class PostgresConfig(AppConfig): name = 'django.contrib.postgres' verbose_name = _('PostgreSQL extensions') def ready(self): # Connections may already exist before we are called. for conn in connections.all(): if conn.vendor == 'postgresql': conn.introspection.data_types_reverse.update({ 3802: 'django.contrib.postgres.fields.JSONField', 3904: 'django.contrib.postgres.fields.IntegerRangeField', 3906: 'django.contrib.postgres.fields.FloatRangeField', 3910: 'django.contrib.postgres.fields.DateTimeRangeField', 3912: 'django.contrib.postgres.fields.DateRangeField', 3926: 'django.contrib.postgres.fields.BigIntegerRangeField', }) if conn.connection is not None: register_type_handlers(conn) connection_created.connect(register_type_handlers) CharField.register_lookup(Unaccent) TextField.register_lookup(Unaccent) CharField.register_lookup(SearchLookup) TextField.register_lookup(SearchLookup) CharField.register_lookup(TrigramSimilar) TextField.register_lookup(TrigramSimilar)
47c8e6eeef4ae5d3ef75b9ac4af08ef79c7ca08ecb49ab74d42797b4f5332f97
from django.contrib.postgres.signals import ( get_citext_oids, get_hstore_oids, register_type_handlers, ) from django.db.migrations.operations.base import Operation class CreateExtension(Operation): reversible = True def __init__(self, name): self.name = name def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor != 'postgresql': return schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % schema_editor.quote_name(self.name)) # Clear cached, stale oids. get_hstore_oids.cache_clear() get_citext_oids.cache_clear() # Registering new type handlers cannot be done before the extension is # installed, otherwise a subsequent data migration would use the same # connection. register_type_handlers(schema_editor.connection) def database_backwards(self, app_label, schema_editor, from_state, to_state): schema_editor.execute("DROP EXTENSION %s" % schema_editor.quote_name(self.name)) # Clear cached, stale oids. get_hstore_oids.cache_clear() get_citext_oids.cache_clear() def describe(self): return "Creates extension %s" % self.name class BtreeGinExtension(CreateExtension): def __init__(self): self.name = 'btree_gin' class BtreeGistExtension(CreateExtension): def __init__(self): self.name = 'btree_gist' class CITextExtension(CreateExtension): def __init__(self): self.name = 'citext' class CryptoExtension(CreateExtension): def __init__(self): self.name = 'pgcrypto' class HStoreExtension(CreateExtension): def __init__(self): self.name = 'hstore' class TrigramExtension(CreateExtension): def __init__(self): self.name = 'pg_trgm' class UnaccentExtension(CreateExtension): def __init__(self): self.name = 'unaccent'
cc7780c8a4793219ec206239a9bb6645dc4f9bc3adc9c1011393a608dcb29c3f
from django.db.models import DateTimeField, Func, UUIDField class RandomUUID(Func): template = 'GEN_RANDOM_UUID()' output_field = UUIDField() class TransactionNow(Func): template = 'CURRENT_TIMESTAMP' output_field = DateTimeField()
80118198060c28b901ea7c9a460c79633ff4d1b5da380e810caf64a2213efdca
from django.core.exceptions import ValidationError from django.utils.functional import SimpleLazyObject from django.utils.text import format_lazy def prefix_validation_error(error, prefix, code, params): """ Prefix a validation error message while maintaining the existing validation data structure. """ if error.error_list == [error]: error_params = error.params or {} return ValidationError( # We can't simply concatenate messages since they might require # their associated parameters to be expressed correctly which # is not something `format_lazy` does. For example, proxied # ngettext calls require a count parameter and are converted # to an empty string if they are missing it. message=format_lazy( '{} {}', SimpleLazyObject(lambda: prefix % params), SimpleLazyObject(lambda: error.message % error_params), ), code=code, params={**error_params, **params}, ) return ValidationError([ prefix_validation_error(e, prefix, code, params) for e in error.error_list ])
3265249606935b5f9404c1904f134eff57ec3bb999ba01acf52728bee088c89a
import functools import psycopg2 from psycopg2 import ProgrammingError from psycopg2.extras import register_hstore from django.db import connections from django.db.backends.base.base import NO_DB_ALIAS @functools.lru_cache() def get_hstore_oids(connection_alias): """Return hstore and hstore array OIDs.""" with connections[connection_alias].cursor() as cursor: cursor.execute( "SELECT t.oid, typarray " "FROM pg_type t " "JOIN pg_namespace ns ON typnamespace = ns.oid " "WHERE typname = 'hstore'" ) oids = [] array_oids = [] for row in cursor: oids.append(row[0]) array_oids.append(row[1]) return tuple(oids), tuple(array_oids) @functools.lru_cache() def get_citext_oids(connection_alias): """Return citext array OIDs.""" with connections[connection_alias].cursor() as cursor: cursor.execute("SELECT typarray FROM pg_type WHERE typname = 'citext'") return tuple(row[0] for row in cursor) def register_type_handlers(connection, **kwargs): if connection.vendor != 'postgresql' or connection.alias == NO_DB_ALIAS: return try: oids, array_oids = get_hstore_oids(connection.alias) register_hstore(connection.connection, globally=True, oid=oids, array_oid=array_oids) except ProgrammingError: # Hstore is not available on the database. # # If someone tries to create an hstore field it will error there. # This is necessary as someone may be using PSQL without extensions # installed but be using other features of contrib.postgres. # # This is also needed in order to create the connection in order to # install the hstore extension. pass try: citext_oids = get_citext_oids(connection.alias) array_type = psycopg2.extensions.new_array_type(citext_oids, 'citext[]', psycopg2.STRING) psycopg2.extensions.register_type(array_type, None) except ProgrammingError: # citext is not available on the database. # # The same comments in the except block of the above call to # register_hstore() also apply here. pass
088cceb5085a6d6239fc611153de51118540e70ce18a6773f61a465ed2a95b4f
from django.db.models import Lookup, Transform from django.db.models.lookups import Exact from .search import SearchVector, SearchVectorExact, SearchVectorField class PostgresSimpleLookup(Lookup): def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return '%s %s %s' % (lhs, self.operator, rhs), params class DataContains(PostgresSimpleLookup): lookup_name = 'contains' operator = '@>' class ContainedBy(PostgresSimpleLookup): lookup_name = 'contained_by' operator = '<@' class Overlap(PostgresSimpleLookup): lookup_name = 'overlap' operator = '&&' class HasKey(PostgresSimpleLookup): lookup_name = 'has_key' operator = '?' prepare_rhs = False class HasKeys(PostgresSimpleLookup): lookup_name = 'has_keys' operator = '?&' def get_prep_lookup(self): return [str(item) for item in self.rhs] class HasAnyKeys(HasKeys): lookup_name = 'has_any_keys' operator = '?|' class Unaccent(Transform): bilateral = True lookup_name = 'unaccent' function = 'UNACCENT' class SearchLookup(SearchVectorExact): lookup_name = 'search' def process_lhs(self, qn, connection): if not isinstance(self.lhs.output_field, SearchVectorField): self.lhs = SearchVector(self.lhs) lhs, lhs_params = super().process_lhs(qn, connection) return lhs, lhs_params class TrigramSimilar(PostgresSimpleLookup): lookup_name = 'trigram_similar' operator = '%%' class JSONExact(Exact): can_use_none_as_rhs = True def process_rhs(self, compiler, connection): result = super().process_rhs(compiler, connection) # Treat None lookup values as null. return ("'null'", []) if result == ('%s', [None]) else result
080fe2ca0136ab7a3cb57950f497cc631a0ee870c99370f43c87261ab6a1c1d2
from django.core.exceptions import ValidationError from django.core.validators import ( MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, ) from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _, ngettext_lazy class ArrayMaxLengthValidator(MaxLengthValidator): message = ngettext_lazy( 'List contains %(show_value)d item, it should contain no more than %(limit_value)d.', 'List contains %(show_value)d items, it should contain no more than %(limit_value)d.', 'limit_value') class ArrayMinLengthValidator(MinLengthValidator): message = ngettext_lazy( 'List contains %(show_value)d item, it should contain no fewer than %(limit_value)d.', 'List contains %(show_value)d items, it should contain no fewer than %(limit_value)d.', 'limit_value') @deconstructible class KeysValidator: """A validator designed for HStore to require/restrict keys.""" messages = { 'missing_keys': _('Some keys were missing: %(keys)s'), 'extra_keys': _('Some unknown keys were provided: %(keys)s'), } strict = False def __init__(self, keys, strict=False, messages=None): self.keys = set(keys) self.strict = strict if messages is not None: self.messages = {**self.messages, **messages} def __call__(self, value): keys = set(value) missing_keys = self.keys - keys if missing_keys: raise ValidationError( self.messages['missing_keys'], code='missing_keys', params={'keys': ', '.join(missing_keys)}, ) if self.strict: extra_keys = keys - self.keys if extra_keys: raise ValidationError( self.messages['extra_keys'], code='extra_keys', params={'keys': ', '.join(extra_keys)}, ) def __eq__(self, other): return ( isinstance(other, self.__class__) and self.keys == other.keys and self.messages == other.messages and self.strict == other.strict ) class RangeMaxValueValidator(MaxValueValidator): def compare(self, a, b): return a.upper is None or a.upper > b message = _('Ensure that this range is completely less than or equal to %(limit_value)s.') class RangeMinValueValidator(MinValueValidator): def compare(self, a, b): return a.lower is None or a.lower < b message = _('Ensure that this range is completely greater than or equal to %(limit_value)s.')
6f90ba88875b20e1dfe70bdc9b540962cb2912b1f74f25899c20d84bd363158e
default_app_config = 'django.contrib.syndication.apps.SyndicationConfig'
857aae147ff704be8d351d9cc4b53ebc7941259dce0a36dc97c8e4cc236f13ae
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class SyndicationConfig(AppConfig): name = 'django.contrib.syndication' verbose_name = _("Syndication")
917053e241a3581aa6615534045accc4ccaa91d3de523808afe4c6a791ef092d
from calendar import timegm from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import Http404, HttpResponse from django.template import TemplateDoesNotExist, loader from django.utils import feedgenerator from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.http import http_date from django.utils.timezone import get_default_timezone, is_naive, make_aware def add_domain(domain, url, secure=False): protocol = 'https' if secure else 'http' if url.startswith('//'): # Support network-path reference (see #16753) - RSS requires a protocol url = '%s:%s' % (protocol, url) elif not url.startswith(('http://', 'https://', 'mailto:')): url = iri_to_uri('%s://%s%s' % (protocol, domain, url)) return url class FeedDoesNotExist(ObjectDoesNotExist): pass class Feed: feed_type = feedgenerator.DefaultFeed title_template = None description_template = None def __call__(self, request, *args, **kwargs): try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404('Feed object does not exist.') feedgen = self.get_feed(obj, request) response = HttpResponse(content_type=feedgen.content_type) if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'): # if item_pubdate or item_updateddate is defined for the feed, set # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED response['Last-Modified'] = http_date( timegm(feedgen.latest_post_date().utctimetuple())) feedgen.write(response, 'utf-8') return response def item_title(self, item): # Titles should be double escaped by default (see #6533) return escape(str(item)) def item_description(self, item): return str(item) def item_link(self, item): try: return item.get_absolute_url() except AttributeError: raise ImproperlyConfigured( 'Give your %s class a get_absolute_url() method, or define an ' 'item_link() method in your Feed class.' % item.__class__.__name__ ) def item_enclosures(self, item): enc_url = self._get_dynamic_attr('item_enclosure_url', item) if enc_url: enc = feedgenerator.Enclosure( url=str(enc_url), length=str(self._get_dynamic_attr('item_enclosure_length', item)), mime_type=str(self._get_dynamic_attr('item_enclosure_mime_type', item)), ) return [enc] return [] def _get_dynamic_attr(self, attname, obj, default=None): try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check co_argcount rather than try/excepting the function and # catching the TypeError, because something inside the function # may raise the TypeError. This technique is more accurate. try: code = attr.__code__ except AttributeError: code = attr.__call__.__code__ if code.co_argcount == 2: # one argument is 'self' return attr(obj) else: return attr() return attr def feed_extra_kwargs(self, obj): """ Return an extra keyword arguments dictionary that is used when initializing the feed generator. """ return {} def item_extra_kwargs(self, item): """ Return an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator. """ return {} def get_object(self, request, *args, **kwargs): return None def get_context_data(self, **kwargs): """ Return a dictionary to use as extra context if either ``self.description_template`` or ``self.item_template`` are used. Default implementation preserves the old behavior of using {'obj': item, 'site': current_site} as the context. """ return {'obj': kwargs.get('item'), 'site': kwargs.get('site')} def get_feed(self, obj, request): """ Return a feedgenerator.DefaultFeed object, fully populated, for this feed. Raise FeedDoesNotExist for invalid parameters. """ current_site = get_current_site(request) link = self._get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link, request.is_secure()) feed = self.feed_type( title=self._get_dynamic_attr('title', obj), subtitle=self._get_dynamic_attr('subtitle', obj), link=link, description=self._get_dynamic_attr('description', obj), language=settings.LANGUAGE_CODE, feed_url=add_domain( current_site.domain, self._get_dynamic_attr('feed_url', obj) or request.path, request.is_secure(), ), author_name=self._get_dynamic_attr('author_name', obj), author_link=self._get_dynamic_attr('author_link', obj), author_email=self._get_dynamic_attr('author_email', obj), categories=self._get_dynamic_attr('categories', obj), feed_copyright=self._get_dynamic_attr('feed_copyright', obj), feed_guid=self._get_dynamic_attr('feed_guid', obj), ttl=self._get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj) ) title_tmp = None if self.title_template is not None: try: title_tmp = loader.get_template(self.title_template) except TemplateDoesNotExist: pass description_tmp = None if self.description_template is not None: try: description_tmp = loader.get_template(self.description_template) except TemplateDoesNotExist: pass for item in self._get_dynamic_attr('items', obj): context = self.get_context_data(item=item, site=current_site, obj=obj, request=request) if title_tmp is not None: title = title_tmp.render(context, request) else: title = self._get_dynamic_attr('item_title', item) if description_tmp is not None: description = description_tmp.render(context, request) else: description = self._get_dynamic_attr('item_description', item) link = add_domain( current_site.domain, self._get_dynamic_attr('item_link', item), request.is_secure(), ) enclosures = self._get_dynamic_attr('item_enclosures', item) author_name = self._get_dynamic_attr('item_author_name', item) if author_name is not None: author_email = self._get_dynamic_attr('item_author_email', item) author_link = self._get_dynamic_attr('item_author_link', item) else: author_email = author_link = None tz = get_default_timezone() pubdate = self._get_dynamic_attr('item_pubdate', item) if pubdate and is_naive(pubdate): pubdate = make_aware(pubdate, tz) updateddate = self._get_dynamic_attr('item_updateddate', item) if updateddate and is_naive(updateddate): updateddate = make_aware(updateddate, tz) feed.add_item( title=title, link=link, description=description, unique_id=self._get_dynamic_attr('item_guid', item, link), unique_id_is_permalink=self._get_dynamic_attr( 'item_guid_is_permalink', item), enclosures=enclosures, pubdate=pubdate, updateddate=updateddate, author_name=author_name, author_email=author_email, author_link=author_link, categories=self._get_dynamic_attr('item_categories', item), item_copyright=self._get_dynamic_attr('item_copyright', item), **self.item_extra_kwargs(item) ) return feed
f6f753903bc7d38e37ca7d2a5f1e7d8f87573e7dcff8f7fd941f005ab4a9fc19
default_app_config = 'django.contrib.redirects.apps.RedirectsConfig'
c7d7fda0619b503b27d487faccbc03a64c16dccd809e5f998fce39580d76d5f8
from django.contrib.sites.models import Site from django.db import models from django.utils.translation import gettext_lazy as _ class Redirect(models.Model): site = models.ForeignKey(Site, models.CASCADE, verbose_name=_('site')) old_path = models.CharField( _('redirect from'), max_length=200, db_index=True, help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'."), ) new_path = models.CharField( _('redirect to'), max_length=200, blank=True, help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'."), ) class Meta: verbose_name = _('redirect') verbose_name_plural = _('redirects') db_table = 'django_redirect' unique_together = (('site', 'old_path'),) ordering = ('old_path',) def __str__(self): return "%s ---> %s" % (self.old_path, self.new_path)
3fdc29f3222f0e32527c85e95983367ed0e55612afb5eff400cf4acbf8f5248b
from django.contrib import admin from django.contrib.redirects.models import Redirect @admin.register(Redirect) class RedirectAdmin(admin.ModelAdmin): list_display = ('old_path', 'new_path') list_filter = ('site',) search_fields = ('old_path', 'new_path') radio_fields = {'site': admin.VERTICAL}
06f4ef3772170afef210aaa1c70083892099dfaf7961736db44be638d1cdc42e
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class RedirectsConfig(AppConfig): name = 'django.contrib.redirects' verbose_name = _("Redirects")
9097d3223f06da5a1182210992a89812b79dcede3184d01f0da4d9924f42a32a
from django.apps import apps from django.conf import settings from django.contrib.redirects.models import Redirect from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponseGone, HttpResponsePermanentRedirect from django.utils.deprecation import MiddlewareMixin class RedirectFallbackMiddleware(MiddlewareMixin): # Defined as class-level attributes to be subclassing-friendly. response_gone_class = HttpResponseGone response_redirect_class = HttpResponsePermanentRedirect def __init__(self, get_response=None): if not apps.is_installed('django.contrib.sites'): raise ImproperlyConfigured( "You cannot use RedirectFallbackMiddleware when " "django.contrib.sites is not installed." ) super().__init__(get_response) def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response full_path = request.get_full_path() current_site = get_current_site(request) r = None try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if r is None and settings.APPEND_SLASH and not request.path.endswith('/'): try: r = Redirect.objects.get( site=current_site, old_path=request.get_full_path(force_append_slash=True), ) except Redirect.DoesNotExist: pass if r is not None: if r.new_path == '': return self.response_gone_class() return self.response_redirect_class(r.new_path) # No redirect was found. Return the response. return response
da2a305001ab919073697fd67f452451b774a68d34502c6d7454315e3d47232a
from functools import wraps from urllib.parse import urlparse from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import PermissionDenied from django.shortcuts import resolve_url def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ def check_perms(user): if isinstance(perm, str): perms = (perm,) else: perms = perm # First check if the user has the permission (even anon users) if user.has_perms(perms): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url)
bd75027c54860f355f8f1fe4879f77759dbb5b8de82356f4a53936381759e3fe
from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission UserModel = get_user_model() class ModelBackend: """ Authenticates against settings.AUTH_USER_MODEL. """ def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def user_can_authenticate(self, user): """ Reject users with is_active=False. Custom user models that don't have that attribute are allowed. """ is_active = getattr(user, 'is_active', None) return is_active or is_active is None def _get_user_permissions(self, user_obj): return user_obj.user_permissions.all() def _get_group_permissions(self, user_obj): user_groups_field = get_user_model()._meta.get_field('groups') user_groups_query = 'group__%s' % user_groups_field.related_query_name() return Permission.objects.filter(**{user_groups_query: user_obj}) def _get_permissions(self, user_obj, obj, from_name): """ Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively. """ if not user_obj.is_active or user_obj.is_anonymous or obj is not None: return set() perm_cache_name = '_%s_perm_cache' % from_name if not hasattr(user_obj, perm_cache_name): if user_obj.is_superuser: perms = Permission.objects.all() else: perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj) perms = perms.values_list('content_type__app_label', 'codename').order_by() setattr(user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms}) return getattr(user_obj, perm_cache_name) def get_user_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from their `user_permissions`. """ return self._get_permissions(user_obj, obj, 'user') def get_group_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from the groups they belong. """ return self._get_permissions(user_obj, obj, 'group') def get_all_permissions(self, user_obj, obj=None): if not user_obj.is_active or user_obj.is_anonymous or obj is not None: return set() if not hasattr(user_obj, '_perm_cache'): user_obj._perm_cache = { *self.get_user_permissions(user_obj), *self.get_group_permissions(user_obj), } return user_obj._perm_cache def has_perm(self, user_obj, perm, obj=None): return user_obj.is_active and perm in self.get_all_permissions(user_obj, obj) def has_module_perms(self, user_obj, app_label): """ Return True if user_obj has any permissions in the given app_label. """ return user_obj.is_active and any( perm[:perm.index('.')] == app_label for perm in self.get_all_permissions(user_obj) ) def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None class AllowAllUsersModelBackend(ModelBackend): def user_can_authenticate(self, user): return True class RemoteUserBackend(ModelBackend): """ This backend is to be used in conjunction with the ``RemoteUserMiddleware`` found in the middleware module of this package, and is used when the server is handling authentication outside of Django. By default, the ``authenticate`` method creates ``User`` objects for usernames that don't already exist in the database. Subclasses can disable this behavior by setting the ``create_unknown_user`` attribute to ``False``. """ # Create a User object if not already in the database? create_unknown_user = True def authenticate(self, request, remote_user): """ The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``. Return None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found in the database. """ if not remote_user: return user = None username = self.clean_username(remote_user) # Note that this could be accomplished in one try-except clause, but # instead we use get_or_create when creating unknown users since it has # built-in safeguards for multiple threads. if self.create_unknown_user: user, created = UserModel._default_manager.get_or_create(**{ UserModel.USERNAME_FIELD: username }) if created: user = self.configure_user(user) else: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: pass return user if self.user_can_authenticate(user) else None def clean_username(self, username): """ Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username. By default, return the username unchanged. """ return username def configure_user(self, user): """ Configure a user after creation and return the updated user. By default, return the user unmodified. """ return user class AllowAllUsersRemoteUserBackend(RemoteUserBackend): def user_can_authenticate(self, user): return True
051ebd8f3d310ba6b5afbab232eaf8606e5ea01f7ee2c9caf93490bc95b1601d
import inspect import re from django.apps import apps as django_apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.middleware.csrf import rotate_token from django.utils.crypto import constant_time_compare from django.utils.module_loading import import_string from django.utils.translation import LANGUAGE_SESSION_KEY from .signals import user_logged_in, user_logged_out, user_login_failed SESSION_KEY = '_auth_user_id' BACKEND_SESSION_KEY = '_auth_user_backend' HASH_SESSION_KEY = '_auth_user_hash' REDIRECT_FIELD_NAME = 'next' def load_backend(path): return import_string(path)() def _get_backends(return_tuples=False): backends = [] for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) backends.append((backend, backend_path) if return_tuples else backend) if not backends: raise ImproperlyConfigured( 'No authentication backends have been defined. Does ' 'AUTHENTICATION_BACKENDS contain anything?' ) return backends def get_backends(): return _get_backends(return_tuples=False) def _clean_credentials(credentials): """ Clean a dictionary of credentials of potentially sensitive info before sending to less secure functions. Not comprehensive - intended for user_login_failed signal """ SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I) CLEANSED_SUBSTITUTE = '********************' for key in credentials: if SENSITIVE_CREDENTIALS.search(key): credentials[key] = CLEANSED_SUBSTITUTE return credentials def _get_user_session_key(request): # This value in the session is always serialized to a string, so we need # to convert it back to Python whenever we access it. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): try: inspect.getcallargs(backend.authenticate, request, **credentials) except TypeError: # This backend doesn't accept these credentials as arguments. Try the next one. continue try: user = backend.authenticate(request, **credentials) except PermissionDenied: # This backend says to stop in our tracks - this user should not be allowed in at all. break if user is None: continue # Annotate the user object with the path of the backend. user.backend = backend_path return user # The credentials supplied are invalid to all backends, fire signal user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials), request=request) def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() try: backend = backend or user.backend except AttributeError: backends = _get_backends(return_tuples=True) if len(backends) == 1: _, backend = backends[0] else: raise ValueError( 'You have multiple authentication backends configured and ' 'therefore must provide the `backend` argument or set the ' '`backend` attribute on the user.' ) else: if not isinstance(backend, str): raise TypeError('backend must be a dotted import path string (got %r).' % backend) request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) request.session[BACKEND_SESSION_KEY] = backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user) def logout(request): """ Remove the authenticated user's ID from the request and flush their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, 'user', None) if not getattr(user, 'is_authenticated', True): user = None user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None: request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'): from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser() def get_user_model(): """ Return the User model that is active in this project. """ try: return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL ) def get_user(request): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or AnonymousUser() def get_permission_codename(action, opts): """ Return the codename of the permission for the specified action. """ return '%s_%s' % (action, opts.model_name) def update_session_auth_hash(request, user): """ Updating a user's password logs out all sessions for the user. Take the current request and the updated user object from which the new session hash will be derived and update the session hash appropriately to prevent a password change from logging out the session from which the password was changed. """ request.session.cycle_key() if hasattr(user, 'get_session_auth_hash') and request.user == user: request.session[HASH_SESSION_KEY] = user.get_session_auth_hash() default_app_config = 'django.contrib.auth.apps.AuthConfig'
7a697aacacb0e2b1081f104951ca8285476f7c487af4ca27ca3926f450d33a86
from itertools import chain from types import MethodType from django.apps import apps from django.conf import settings from django.core import checks from .management import _get_builtin_permissions def check_user_model(app_configs=None, **kwargs): if app_configs is None: cls = apps.get_model(settings.AUTH_USER_MODEL) else: app_label, model_name = settings.AUTH_USER_MODEL.split('.') for app_config in app_configs: if app_config.label == app_label: cls = app_config.get_model(model_name) break else: # Checks might be run against a set of app configs that don't # include the specified user model. In this case we simply don't # perform the checks defined below. return [] errors = [] # Check that REQUIRED_FIELDS is a list if not isinstance(cls.REQUIRED_FIELDS, (list, tuple)): errors.append( checks.Error( "'REQUIRED_FIELDS' must be a list or tuple.", obj=cls, id='auth.E001', ) ) # Check that the USERNAME FIELD isn't included in REQUIRED_FIELDS. if cls.USERNAME_FIELD in cls.REQUIRED_FIELDS: errors.append( checks.Error( "The field named as the 'USERNAME_FIELD' " "for a custom user model must not be included in 'REQUIRED_FIELDS'.", obj=cls, id='auth.E002', ) ) # Check that the username field is unique if not cls._meta.get_field(cls.USERNAME_FIELD).unique: if (settings.AUTHENTICATION_BACKENDS == ['django.contrib.auth.backends.ModelBackend']): errors.append( checks.Error( "'%s.%s' must be unique because it is named as the 'USERNAME_FIELD'." % ( cls._meta.object_name, cls.USERNAME_FIELD ), obj=cls, id='auth.E003', ) ) else: errors.append( checks.Warning( "'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique." % ( cls._meta.object_name, cls.USERNAME_FIELD ), hint='Ensure that your authentication backend(s) can handle non-unique usernames.', obj=cls, id='auth.W004', ) ) if isinstance(cls().is_anonymous, MethodType): errors.append( checks.Critical( '%s.is_anonymous must be an attribute or property rather than ' 'a method. Ignoring this is a security issue as anonymous ' 'users will be treated as authenticated!' % cls, obj=cls, id='auth.C009', ) ) if isinstance(cls().is_authenticated, MethodType): errors.append( checks.Critical( '%s.is_authenticated must be an attribute or property rather ' 'than a method. Ignoring this is a security issue as anonymous ' 'users will be treated as authenticated!' % cls, obj=cls, id='auth.C010', ) ) return errors def check_models_permissions(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) Permission = apps.get_model('auth', 'Permission') permission_name_max_length = Permission._meta.get_field('name').max_length errors = [] for model in models: opts = model._meta builtin_permissions = dict(_get_builtin_permissions(opts)) # Check builtin permission name length. max_builtin_permission_name_length = ( max(len(name) for name in builtin_permissions.values()) if builtin_permissions else 0 ) if max_builtin_permission_name_length > permission_name_max_length: verbose_name_max_length = ( permission_name_max_length - (max_builtin_permission_name_length - len(opts.verbose_name_raw)) ) errors.append( checks.Error( "The verbose_name of model '%s.%s' must be at most %d characters " "for its builtin permission names to be at most %d characters." % ( opts.app_label, opts.object_name, verbose_name_max_length, permission_name_max_length ), obj=model, id='auth.E007', ) ) codenames = set() for codename, name in opts.permissions: # Check custom permission name length. if len(name) > permission_name_max_length: errors.append( checks.Error( "The permission named '%s' of model '%s.%s' is longer than %d characters." % ( name, opts.app_label, opts.object_name, permission_name_max_length ), obj=model, id='auth.E008', ) ) # Check custom permissions codename clashing. if codename in builtin_permissions: errors.append( checks.Error( "The permission codenamed '%s' clashes with a builtin permission " "for model '%s.%s'." % ( codename, opts.app_label, opts.object_name ), obj=model, id='auth.E005', ) ) elif codename in codenames: errors.append( checks.Error( "The permission codenamed '%s' is duplicated for model '%s.%s'." % ( codename, opts.app_label, opts.object_name ), obj=model, id='auth.E006', ) ) codenames.add(codename) return errors
8895ca8eaec54a440f1ebb363a23f5bd5c41766f5df2444125205b02a2a31e52
from django.contrib import auth from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied from django.core.mail import send_mail from django.db import models from django.db.models.manager import EmptyManager from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .validators import UnicodeUsernameValidator def update_last_login(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ user.last_login = timezone.now() user.save(update_fields=['last_login']) class PermissionManager(models.Manager): use_in_migrations = True def get_by_natural_key(self, codename, app_label, model): return self.get( codename=codename, content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(app_label, model), ) class Permission(models.Model): """ The permissions system provides a way to assign permissions to specific users and groups of users. The permission system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows: - The "add" permission limits the user's ability to view the "add" form and add an object. - The "change" permission limits a user's ability to view the change list, view the "change" form and change an object. - The "delete" permission limits the ability to delete an object. Permissions are set globally per type of object, not per specific object instance. It is possible to say "Mary may change news stories," but it's not currently possible to say "Mary may change news stories, but only the ones she created herself" or "Mary may only change news stories that have a certain status or publication date." Three basic permissions -- add, change and delete -- are automatically created for each Django model. """ name = models.CharField(_('name'), max_length=255) content_type = models.ForeignKey( ContentType, models.CASCADE, verbose_name=_('content type'), ) codename = models.CharField(_('codename'), max_length=100) objects = PermissionManager() class Meta: verbose_name = _('permission') verbose_name_plural = _('permissions') unique_together = (('content_type', 'codename'),) ordering = ('content_type__app_label', 'content_type__model', 'codename') def __str__(self): return "%s | %s | %s" % ( self.content_type.app_label, self.content_type, self.name, ) def natural_key(self): return (self.codename,) + self.content_type.natural_key() natural_key.dependencies = ['contenttypes.contenttype'] class GroupManager(models.Manager): """ The manager for the auth's Group model. """ use_in_migrations = True def get_by_natural_key(self, name): return self.get(name=name) class Group(models.Model): """ Groups are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of groups. A user in a group automatically has all the permissions granted to that group. For example, if the group 'Site editors' has the permission can_edit_home_page, any user in that group will have that permission. Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only email messages. """ name = models.CharField(_('name'), max_length=80, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) objects = GroupManager() class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __str__(self): return self.name def natural_key(self): return (self.name,) class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, email, password, **extra_fields) # A few helper functions for common logic between User and AnonymousUser. def _user_get_all_permissions(user, obj): permissions = set() for backend in auth.get_backends(): if hasattr(backend, "get_all_permissions"): permissions.update(backend.get_all_permissions(user, obj)) return permissions def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: return False return False def _user_has_module_perms(user, app_label): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_module_perms'): continue try: if backend.has_module_perms(user, app_label): return True except PermissionDenied: return False return False class PermissionsMixin(models.Model): """ Add the fields and methods necessary to support the Group and Permission models using the ModelBackend. """ is_superuser = models.BooleanField( _('superuser status'), default=False, help_text=_( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) groups = models.ManyToManyField( Group, verbose_name=_('groups'), blank=True, help_text=_( 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' ), related_name="user_set", related_query_name="user", ) user_permissions = models.ManyToManyField( Permission, verbose_name=_('user permissions'), blank=True, help_text=_('Specific permissions for this user.'), related_name="user_set", related_query_name="user", ) class Meta: abstract = True def get_group_permissions(self, obj=None): """ Return a list of permission strings that this user has through their groups. Query all available auth backends. If an object is passed in, return only permissions matching this object. """ permissions = set() for backend in auth.get_backends(): if hasattr(backend, "get_group_permissions"): permissions.update(backend.get_group_permissions(self, obj)) return permissions def get_all_permissions(self, obj=None): return _user_get_all_permissions(self, obj) def has_perm(self, perm, obj=None): """ Return True if the user has the specified permission. Query all available auth backends, but return immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, check permissions for that object. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True # Otherwise we need to check the backends. return _user_has_perm(self, perm, obj) def has_perms(self, perm_list, obj=None): """ Return True if the user has each of the specified permissions. If object is passed, check if the user has all required perms for it. """ return all(self.has_perm(perm, obj) for perm in perm_list) def has_module_perms(self, app_label): """ Return True if the user has any permissions in the given app label. Use simlar logic as has_perm(), above. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True return _user_has_module_perms(self, app_label) class AbstractUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') abstract = True def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """Return the short name for the user.""" return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs) class User(AbstractUser): """ Users within the Django authentication system are represented by this model. Username and password are required. Other fields are optional. """ class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' class AnonymousUser: id = None pk = None username = '' is_staff = False is_active = False is_superuser = False _groups = EmptyManager(Group) _user_permissions = EmptyManager(Permission) def __str__(self): return 'AnonymousUser' def __eq__(self, other): return isinstance(other, self.__class__) def __hash__(self): return 1 # instances always return the same hash value def save(self): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") def delete(self): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") def set_password(self, raw_password): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") def check_password(self, raw_password): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") @property def groups(self): return self._groups @property def user_permissions(self): return self._user_permissions def get_group_permissions(self, obj=None): return set() def get_all_permissions(self, obj=None): return _user_get_all_permissions(self, obj=obj) def has_perm(self, perm, obj=None): return _user_has_perm(self, perm, obj=obj) def has_perms(self, perm_list, obj=None): return all(self.has_perm(perm, obj) for perm in perm_list) def has_module_perms(self, module): return _user_has_module_perms(self, module) @property def is_anonymous(self): return True @property def is_authenticated(self): return False def get_username(self): return self.username
73a27b703e5271ec968e621bc21f617bb89a2166952b6eec82b9168c69917b3b
from datetime import date from django.conf import settings from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.http import base36_to_int, int_to_base36 class PasswordResetTokenGenerator: """ Strategy object used to generate and check tokens for the password reset mechanism. """ key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" secret = settings.SECRET_KEY def make_token(self, user): """ Return a token that can be used once to do a password reset for the given user. """ return self._make_token_with_timestamp(user, self._num_days(self._today())) def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit. Timestamps are rounded to # midnight (server time) providing a resolution of only 1 day. If a # link is generated 5 minutes before midnight and used 6 minutes later, # that counts as 1 day. Therefore, PASSWORD_RESET_TIMEOUT_DAYS = 1 means # "at least 1 day, could be up to 2." if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True def _make_token_with_timestamp(self, user, timestamp): # timestamp is number of days since 2001-1-1. Converted to # base 36, this gives us a 3 digit string until about 2121 ts_b36 = int_to_base36(timestamp) hash = salted_hmac( self.key_salt, self._make_hash_value(user, timestamp), secret=self.secret, ).hexdigest()[::2] # Limit to 20 characters to shorten the URL. return "%s-%s" % (ts_b36, hash) def _make_hash_value(self, user, timestamp): """ Hash the user's primary key and some user state that's sure to change after a password reset to produce a token that invalidated when it's used: 1. The password field will change upon a password reset (even if the same password is chosen, due to password salting). 2. The last_login field will usually be updated very shortly after a password reset. Failing those things, settings.PASSWORD_RESET_TIMEOUT_DAYS eventually invalidates the token. Running this data through salted_hmac() prevents password cracking attempts using the reset token, provided the secret isn't compromised. """ # Truncate microseconds so that tokens are consistent even if the # database doesn't support microseconds. login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) return str(user.pk) + user.password + str(login_timestamp) + str(timestamp) def _num_days(self, dt): return (dt - date(2001, 1, 1)).days def _today(self): # Used for mocking in tests return date.today() default_token_generator = PasswordResetTokenGenerator()
a7a791b3822db1ef015af8664a0bc68073bd475035b609720fadb88ec0a90d97
import base64 import binascii import functools import hashlib import importlib import warnings from collections import OrderedDict from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receiver from django.utils.crypto import ( constant_time_compare, get_random_string, pbkdf2, ) from django.utils.module_loading import import_string from django.utils.translation import gettext_noop as _ UNUSABLE_PASSWORD_PREFIX = '!' # This will never be a valid encoded hash UNUSABLE_PASSWORD_SUFFIX_LENGTH = 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX def is_password_usable(encoded): """ Return True if this password wasn't generated by User.set_unusable_password(), i.e. make_password(None). """ return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX) def check_password(password, encoded, setter=None, preferred='default'): """ Return a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ if password is None or not is_password_usable(encoded): return False preferred = get_hasher(preferred) try: hasher = identify_hasher(encoded) except ValueError: # encoded is gibberish or uses a hasher that's no longer installed. return False hasher_changed = hasher.algorithm != preferred.algorithm must_update = hasher_changed or preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) # If the hasher didn't change (we don't protect against enumeration if it # does) and the password should get updated, try to close the timing gap # between the work factor of the current encoded password and the default # work factor. if not is_correct and not hasher_changed and must_update: hasher.harden_runtime(password, encoded) if setter and is_correct and must_update: setter(password) return is_correct def make_password(password, salt=None, hasher='default'): """ Turn a plain-text password into a hash for database storage Same as encode() but generate a new random salt. If password is None then return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string, which disallows logins. Additional random string reduces chances of gaining access to staff or superuser accounts. See ticket #20079 for more info. """ if password is None: return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH) hasher = get_hasher(hasher) salt = salt or hasher.salt() return hasher.encode(password, salt) @functools.lru_cache() def get_hashers(): hashers = [] for hasher_path in settings.PASSWORD_HASHERS: hasher_cls = import_string(hasher_path) hasher = hasher_cls() if not getattr(hasher, 'algorithm'): raise ImproperlyConfigured("hasher doesn't specify an " "algorithm name: %s" % hasher_path) hashers.append(hasher) return hashers @functools.lru_cache() def get_hashers_by_algorithm(): return {hasher.algorithm: hasher for hasher in get_hashers()} @receiver(setting_changed) def reset_hashers(**kwargs): if kwargs['setting'] == 'PASSWORD_HASHERS': get_hashers.cache_clear() get_hashers_by_algorithm.cache_clear() def get_hasher(algorithm='default'): """ Return an instance of a loaded password hasher. If algorithm is 'default', return the default hasher. Lazily import hashers specified in the project's settings file if needed. """ if hasattr(algorithm, 'algorithm'): return algorithm elif algorithm == 'default': return get_hashers()[0] else: hashers = get_hashers_by_algorithm() try: return hashers[algorithm] except KeyError: raise ValueError("Unknown password hashing algorithm '%s'. " "Did you specify it in the PASSWORD_HASHERS " "setting?" % algorithm) def identify_hasher(encoded): """ Return an instance of a loaded password hasher. Identify hasher algorithm by examining encoded hash, and call get_hasher() to return hasher. Raise ValueError if algorithm cannot be identified, or if hasher is not loaded. """ # Ancient versions of Django created plain MD5 passwords and accepted # MD5 passwords with an empty salt. if ((len(encoded) == 32 and '$' not in encoded) or (len(encoded) == 37 and encoded.startswith('md5$$'))): algorithm = 'unsalted_md5' # Ancient versions of Django accepted SHA1 passwords with an empty salt. elif len(encoded) == 46 and encoded.startswith('sha1$$'): algorithm = 'unsalted_sha1' else: algorithm = encoded.split('$', 1)[0] return get_hasher(algorithm) def mask_hash(hash, show=6, char="*"): """ Return the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons. """ masked = hash[:show] masked += char * len(hash[show:]) return masked class BasePasswordHasher: """ Abstract base class for password hashers When creating your own hasher, you need to override algorithm, verify(), encode() and safe_summary(). PasswordHasher objects are immutable. """ algorithm = None library = None def _load_library(self): if self.library is not None: if isinstance(self.library, (tuple, list)): name, mod_path = self.library else: mod_path = self.library try: module = importlib.import_module(mod_path) except ImportError as e: raise ValueError("Couldn't load %r algorithm library: %s" % (self.__class__.__name__, e)) return module raise ValueError("Hasher %r doesn't specify a library attribute" % self.__class__.__name__) def salt(self): """Generate a cryptographically secure nonce salt in ASCII.""" return get_random_string() def verify(self, password, encoded): """Check if the given password is correct.""" raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method') def encode(self, password, salt): """ Create an encoded database value. The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters. """ raise NotImplementedError('subclasses of BasePasswordHasher must provide an encode() method') def safe_summary(self, encoded): """ Return a summary of safe values. The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password. """ raise NotImplementedError('subclasses of BasePasswordHasher must provide a safe_summary() method') def must_update(self, encoded): return False def harden_runtime(self, password, encoded): """ Bridge the runtime gap between the work factor supplied in `encoded` and the work factor suggested by this hasher. Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and `self.iterations` is 30000, this method should run password through another 10000 iterations of PBKDF2. Similar approaches should exist for any hasher that has a work factor. If not, this method should be defined as a no-op to silence the warning. """ warnings.warn('subclasses of BasePasswordHasher should provide a harden_runtime() method') class PBKDF2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the PBKDF2 algorithm (recommended) Configured to use PBKDF2 + HMAC + SHA256. The result is a 64 byte binary string. Iterations may be changed safely but you must rename the algorithm if you change SHA256. """ algorithm = "pbkdf2_sha256" iterations = 150000 digest = hashlib.sha256 def encode(self, password, salt, iterations=None): assert password is not None assert salt and '$' not in salt iterations = iterations or self.iterations hash = pbkdf2(password, salt, iterations, digest=self.digest) hash = base64.b64encode(hash).decode('ascii').strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) def verify(self, password, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm encoded_2 = self.encode(password, salt, int(iterations)) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('iterations'), iterations), (_('salt'), mask_hash(salt)), (_('hash'), mask_hash(hash)), ]) def must_update(self, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) return int(iterations) != self.iterations def harden_runtime(self, password, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) extra_iterations = self.iterations - int(iterations) if extra_iterations > 0: self.encode(password, salt, extra_iterations) class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher): """ Alternate PBKDF2 hasher which uses SHA1, the default PRF recommended by PKCS #5. This is compatible with other implementations of PBKDF2, such as openssl's PKCS5_PBKDF2_HMAC_SHA1(). """ algorithm = "pbkdf2_sha1" digest = hashlib.sha1 class Argon2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the argon2 algorithm. This is the winner of the Password Hashing Competition 2013-2015 (https://password-hashing.net). It requires the argon2-cffi library which depends on native C code and might cause portability issues. """ algorithm = 'argon2' library = 'argon2' time_cost = 2 memory_cost = 512 parallelism = 2 def encode(self, password, salt): argon2 = self._load_library() data = argon2.low_level.hash_secret( password.encode(), salt.encode(), time_cost=self.time_cost, memory_cost=self.memory_cost, parallelism=self.parallelism, hash_len=argon2.DEFAULT_HASH_LENGTH, type=argon2.low_level.Type.I, ) return self.algorithm + data.decode('ascii') def verify(self, password, encoded): argon2 = self._load_library() algorithm, rest = encoded.split('$', 1) assert algorithm == self.algorithm try: return argon2.low_level.verify_secret( ('$' + rest).encode('ascii'), password.encode(), type=argon2.low_level.Type.I, ) except argon2.exceptions.VerificationError: return False def safe_summary(self, encoded): (algorithm, variety, version, time_cost, memory_cost, parallelism, salt, data) = self._decode(encoded) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('variety'), variety), (_('version'), version), (_('memory cost'), memory_cost), (_('time cost'), time_cost), (_('parallelism'), parallelism), (_('salt'), mask_hash(salt)), (_('hash'), mask_hash(data)), ]) def must_update(self, encoded): (algorithm, variety, version, time_cost, memory_cost, parallelism, salt, data) = self._decode(encoded) assert algorithm == self.algorithm argon2 = self._load_library() return ( argon2.low_level.ARGON2_VERSION != version or self.time_cost != time_cost or self.memory_cost != memory_cost or self.parallelism != parallelism ) def harden_runtime(self, password, encoded): # The runtime for Argon2 is too complicated to implement a sensible # hardening algorithm. pass def _decode(self, encoded): """ Split an encoded hash and return: ( algorithm, variety, version, time_cost, memory_cost, parallelism, salt, data, ). """ bits = encoded.split('$') if len(bits) == 5: # Argon2 < 1.3 algorithm, variety, raw_params, salt, data = bits version = 0x10 else: assert len(bits) == 6 algorithm, variety, raw_version, raw_params, salt, data = bits assert raw_version.startswith('v=') version = int(raw_version[len('v='):]) params = dict(bit.split('=', 1) for bit in raw_params.split(',')) assert len(params) == 3 and all(x in params for x in ('t', 'm', 'p')) time_cost = int(params['t']) memory_cost = int(params['m']) parallelism = int(params['p']) return ( algorithm, variety, version, time_cost, memory_cost, parallelism, salt, data, ) class BCryptSHA256PasswordHasher(BasePasswordHasher): """ Secure password hashing using the bcrypt algorithm (recommended) This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. """ algorithm = "bcrypt_sha256" digest = hashlib.sha256 library = ("bcrypt", "bcrypt") rounds = 12 def salt(self): bcrypt = self._load_library() return bcrypt.gensalt(self.rounds) def encode(self, password, salt): bcrypt = self._load_library() password = password.encode() # Hash the password prior to using bcrypt to prevent password # truncation as described in #20138. if self.digest is not None: # Use binascii.hexlify() because a hex encoded bytestring is str. password = binascii.hexlify(self.digest(password).digest()) data = bcrypt.hashpw(password, salt) return "%s$%s" % (self.algorithm, data.decode('ascii')) def verify(self, password, encoded): algorithm, data = encoded.split('$', 1) assert algorithm == self.algorithm encoded_2 = self.encode(password, data.encode('ascii')) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): algorithm, empty, algostr, work_factor, data = encoded.split('$', 4) assert algorithm == self.algorithm salt, checksum = data[:22], data[22:] return OrderedDict([ (_('algorithm'), algorithm), (_('work factor'), work_factor), (_('salt'), mask_hash(salt)), (_('checksum'), mask_hash(checksum)), ]) def must_update(self, encoded): algorithm, empty, algostr, rounds, data = encoded.split('$', 4) return int(rounds) != self.rounds def harden_runtime(self, password, encoded): _, data = encoded.split('$', 1) salt = data[:29] # Length of the salt in bcrypt. rounds = data.split('$')[2] # work factor is logarithmic, adding one doubles the load. diff = 2**(self.rounds - int(rounds)) - 1 while diff > 0: self.encode(password, salt.encode('ascii')) diff -= 1 class BCryptPasswordHasher(BCryptSHA256PasswordHasher): """ Secure password hashing using the bcrypt algorithm This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. This hasher does not first hash the password which means it is subject to bcrypt's 72 bytes password truncation. Most use cases should prefer the BCryptSHA256PasswordHasher. """ algorithm = "bcrypt" digest = None class SHA1PasswordHasher(BasePasswordHasher): """ The SHA1 password hashing algorithm (not recommended) """ algorithm = "sha1" def encode(self, password, salt): assert password is not None assert salt and '$' not in salt hash = hashlib.sha1((salt + password).encode()).hexdigest() return "%s$%s$%s" % (self.algorithm, salt, hash) def verify(self, password, encoded): algorithm, salt, hash = encoded.split('$', 2) assert algorithm == self.algorithm encoded_2 = self.encode(password, salt) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): algorithm, salt, hash = encoded.split('$', 2) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('salt'), mask_hash(salt, show=2)), (_('hash'), mask_hash(hash)), ]) def harden_runtime(self, password, encoded): pass class MD5PasswordHasher(BasePasswordHasher): """ The Salted MD5 password hashing algorithm (not recommended) """ algorithm = "md5" def encode(self, password, salt): assert password is not None assert salt and '$' not in salt hash = hashlib.md5((salt + password).encode()).hexdigest() return "%s$%s$%s" % (self.algorithm, salt, hash) def verify(self, password, encoded): algorithm, salt, hash = encoded.split('$', 2) assert algorithm == self.algorithm encoded_2 = self.encode(password, salt) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): algorithm, salt, hash = encoded.split('$', 2) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('salt'), mask_hash(salt, show=2)), (_('hash'), mask_hash(hash)), ]) def harden_runtime(self, password, encoded): pass class UnsaltedSHA1PasswordHasher(BasePasswordHasher): """ Very insecure algorithm that you should *never* use; store SHA1 hashes with an empty salt. This class is implemented because Django used to accept such password hashes. Some older Django installs still have these values lingering around so we need to handle and upgrade them properly. """ algorithm = "unsalted_sha1" def salt(self): return '' def encode(self, password, salt): assert salt == '' hash = hashlib.sha1(password.encode()).hexdigest() return 'sha1$$%s' % hash def verify(self, password, encoded): encoded_2 = self.encode(password, '') return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): assert encoded.startswith('sha1$$') hash = encoded[6:] return OrderedDict([ (_('algorithm'), self.algorithm), (_('hash'), mask_hash(hash)), ]) def harden_runtime(self, password, encoded): pass class UnsaltedMD5PasswordHasher(BasePasswordHasher): """ Incredibly insecure algorithm that you should *never* use; stores unsalted MD5 hashes without the algorithm prefix, also accepts MD5 hashes with an empty salt. This class is implemented because Django used to store passwords this way and to accept such password hashes. Some older Django installs still have these values lingering around so we need to handle and upgrade them properly. """ algorithm = "unsalted_md5" def salt(self): return '' def encode(self, password, salt): assert salt == '' return hashlib.md5(password.encode()).hexdigest() def verify(self, password, encoded): if len(encoded) == 37 and encoded.startswith('md5$$'): encoded = encoded[5:] encoded_2 = self.encode(password, '') return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): return OrderedDict([ (_('algorithm'), self.algorithm), (_('hash'), mask_hash(encoded, show=3)), ]) def harden_runtime(self, password, encoded): pass class CryptPasswordHasher(BasePasswordHasher): """ Password hashing using UNIX crypt (not recommended) The crypt module is not supported on all platforms. """ algorithm = "crypt" library = "crypt" def salt(self): return get_random_string(2) def encode(self, password, salt): crypt = self._load_library() assert len(salt) == 2 data = crypt.crypt(password, salt) assert data is not None # A platform like OpenBSD with a dummy crypt module. # we don't need to store the salt, but Django used to do this return "%s$%s$%s" % (self.algorithm, '', data) def verify(self, password, encoded): crypt = self._load_library() algorithm, salt, data = encoded.split('$', 2) assert algorithm == self.algorithm return constant_time_compare(data, crypt.crypt(password, data)) def safe_summary(self, encoded): algorithm, salt, data = encoded.split('$', 2) assert algorithm == self.algorithm return OrderedDict([ (_('algorithm'), algorithm), (_('salt'), salt), (_('hash'), mask_hash(data, show=3)), ]) def harden_runtime(self, password, encoded): pass
971d5fcae26be5cfdc2c9164fe5889cc4e3d397aed4510ce23d819aae54e4a81
from django.conf import settings from django.contrib import admin, messages from django.contrib.admin.options import IS_POPUP_VAR from django.contrib.admin.utils import unquote from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import ( AdminPasswordChangeForm, UserChangeForm, UserCreationForm, ) from django.contrib.auth.models import Group, User from django.core.exceptions import PermissionDenied from django.db import router, transaction from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import path, reverse from django.utils.decorators import method_decorator from django.utils.html import escape from django.utils.translation import gettext, gettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters csrf_protect_m = method_decorator(csrf_protect) sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) @admin.register(Group) class GroupAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('name',) filter_horizontal = ('permissions',) def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == 'permissions': qs = kwargs.get('queryset', db_field.remote_field.model.objects) # Avoid a major performance hit resolving permission names which # triggers a content_type load: kwargs['queryset'] = qs.select_related('content_type') return super().formfield_for_manytomany(db_field, request=request, **kwargs) @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = 'admin/auth/user/add_form.html' change_user_password_template = None fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'password1', 'password2'), }), ) form = UserChangeForm add_form = UserCreationForm change_password_form = AdminPasswordChangeForm list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') search_fields = ('username', 'first_name', 'last_name', 'email') ordering = ('username',) filter_horizontal = ('groups', 'user_permissions',) def get_fieldsets(self, request, obj=None): if not obj: return self.add_fieldsets return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: defaults['form'] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) def get_urls(self): return [ path( '<id>/password/', self.admin_site.admin_view(self.user_change_password), name='auth_user_password_change', ), ] + super().get_urls() def lookup_allowed(self, lookup, value): # Don't allow lookups involving passwords. return not lookup.startswith('password') and super().lookup_allowed(lookup, value) @sensitive_post_parameters_m @csrf_protect_m def add_view(self, request, form_url='', extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._add_view(request, form_url, extra_context) def _add_view(self, request, form_url='', extra_context=None): # It's an error for a user to have add permission but NOT change # permission for users. If we allowed such users to add users, they # could create superusers, which would mean they would essentially have # the permission to change users. To avoid the problem entirely, we # disallow users from adding users if they don't have change # permission. if not self.has_change_permission(request): if self.has_add_permission(request) and settings.DEBUG: # Raise Http404 in debug mode so that the user gets a helpful # error message. raise Http404( 'Your user does not have the "Change user" permission. In ' 'order to add users, Django requires that your user ' 'account have both the "Add user" and "Change user" ' 'permissions set.') raise PermissionDenied if extra_context is None: extra_context = {} username_field = self.model._meta.get_field(self.model.USERNAME_FIELD) defaults = { 'auto_populated_fields': (), 'username_help_text': username_field.help_text, } extra_context.update(defaults) return super().add_view(request, form_url, extra_context) @sensitive_post_parameters_m def user_change_password(self, request, id, form_url=''): if not self.has_change_permission(request): raise PermissionDenied user = self.get_object(request, unquote(id)) if user is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': self.model._meta.verbose_name, 'key': escape(id), }) if request.method == 'POST': form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() change_message = self.construct_change_message(request, form, None) self.log_change(request, user, change_message) msg = gettext('Password changed successfully.') messages.success(request, msg) update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( '%s:%s_%s_change' % ( self.admin_site.name, user._meta.app_label, user._meta.model_name, ), args=(user.pk,), ) ) else: form = self.change_password_form(user) fieldsets = [(None, {'fields': list(form.base_fields)})] adminForm = admin.helpers.AdminForm(form, fieldsets, {}) context = { 'title': _('Change password: %s') % escape(user.get_username()), 'adminForm': adminForm, 'form_url': form_url, 'form': form, 'is_popup': (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), 'add': True, 'change': False, 'has_delete_permission': False, 'has_change_permission': True, 'has_absolute_url': False, 'opts': self.model._meta, 'original': user, 'save_as': False, 'show_save': True, **self.admin_site.each_context(request), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_user_password_template or 'admin/auth/user/change_password.html', context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow. """ # We should allow further modification of the user just added i.e. the # 'Save' button should behave like the 'Save and continue editing' # button except in two scenarios: # * The user has pressed the 'Save and add another' button # * We are adding a user in a popup if '_addanother' not in request.POST and IS_POPUP_VAR not in request.POST: request.POST = request.POST.copy() request.POST['_continue'] = 1 return super().response_add(request, obj, post_url_continue)
346772d61e32ae88029fd6193a48673bb2dc5451d9012eb48fe05befe473d7b0
from django.apps import AppConfig from django.core import checks from django.db.models.query_utils import DeferredAttribute from django.db.models.signals import post_migrate from django.utils.translation import gettext_lazy as _ from . import get_user_model from .checks import check_models_permissions, check_user_model from .management import create_permissions from .signals import user_logged_in class AuthConfig(AppConfig): name = 'django.contrib.auth' verbose_name = _("Authentication and Authorization") def ready(self): post_migrate.connect( create_permissions, dispatch_uid="django.contrib.auth.management.create_permissions" ) last_login_field = getattr(get_user_model(), 'last_login', None) # Register the handler only if UserModel.last_login is a field. if isinstance(last_login_field, DeferredAttribute): from .models import update_last_login user_logged_in.connect(update_last_login, dispatch_uid='update_last_login') checks.register(check_user_model, checks.Tags.models) checks.register(check_models_permissions, checks.Tags.models)
fd035863e4739304ef637151a34d405b54be0fd97c9556f779bb7a1751817cc5
from django.dispatch import Signal user_logged_in = Signal(providing_args=['request', 'user']) user_login_failed = Signal(providing_args=['credentials', 'request']) user_logged_out = Signal(providing_args=['request', 'user'])
55bf757deb8a57d6b7041811d21aeb1a666f54fc34272620780fe6457f502b57
# PermWrapper and PermLookupDict proxy the permissions system into objects that # the template system can understand. class PermLookupDict: def __init__(self, user, app_label): self.user, self.app_label = user, app_label def __repr__(self): return str(self.user.get_all_permissions()) def __getitem__(self, perm_name): return self.user.has_perm("%s.%s" % (self.app_label, perm_name)) def __iter__(self): # To fix 'item in perms.someapp' and __getitem__ interaction we need to # define __iter__. See #18979 for details. raise TypeError("PermLookupDict is not iterable.") def __bool__(self): return self.user.has_module_perms(self.app_label) class PermWrapper: def __init__(self, user): self.user = user def __getitem__(self, app_label): return PermLookupDict(self.user, app_label) def __iter__(self): # I am large, I contain multitudes. raise TypeError("PermWrapper is not iterable.") def __contains__(self, perm_name): """ Lookup by "someapp" or "someapp.someperm" in perms. """ if '.' not in perm_name: # The name refers to module. return bool(self[perm_name]) app_label, perm_name = perm_name.split('.', 1) return self[app_label][perm_name] def auth(request): """ Return context variables required by apps that use Django's authentication system. If there is no 'user' attribute in the request, use AnonymousUser (from django.contrib.auth). """ if hasattr(request, 'user'): user = request.user else: from django.contrib.auth.models import AnonymousUser user = AnonymousUser() return { 'user': user, 'perms': PermWrapper(user), }
e8ce7879315d08512a5b4a73cca343e11e7ef12f49af3a0f71a56dd2a0372577
# The views used below are normally mapped in django.contrib.admin.urls.py # This URLs file is used to provide a reliable view deployment for test purposes. # It is also provided as a convenience to those who want to deploy these URLs # elsewhere. from django.contrib.auth import views from django.urls import path urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('password_change/', views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ]
198ceee4c157e2a03d4a40549ef8960c28677ba03e3e244ab8ecec31d5202c04
""" This module allows importing AbstractBaseUser even when django.contrib.auth is not in INSTALLED_APPS. """ import unicodedata from django.contrib.auth import password_validation from django.contrib.auth.hashers import ( check_password, is_password_usable, make_password, ) from django.db import models from django.utils.crypto import get_random_string, salted_hmac from django.utils.translation import gettext_lazy as _ class BaseUserManager(models.Manager): @classmethod def normalize_email(cls, email): """ Normalize the email address by lowercasing the domain part of it. """ email = email or '' try: email_name, domain_part = email.strip().rsplit('@', 1) except ValueError: pass else: email = email_name + '@' + domain_part.lower() return email def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789'): """ Generate a random password with the given length and given allowed_chars. The default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string(length, allowed_chars) def get_by_natural_key(self, username): return self.get(**{self.model.USERNAME_FIELD: username}) class AbstractBaseUser(models.Model): password = models.CharField(_('password'), max_length=128) last_login = models.DateTimeField(_('last login'), blank=True, null=True) is_active = True REQUIRED_FIELDS = [] # Stores the raw password if set_password() is called so that it can # be passed to password_changed() after the model is saved. _password = None class Meta: abstract = True def get_username(self): "Return the identifying username for this User" return getattr(self, self.USERNAME_FIELD) def __str__(self): return self.get_username() def clean(self): setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username())) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self._password is not None: password_validation.password_changed(self._password, self) self._password = None def natural_key(self): return (self.get_username(),) @property def is_anonymous(self): """ Always return False. This is a way of comparing User objects to anonymous users. """ return False @property def is_authenticated(self): """ Always return True. This is a way to tell if the user has been authenticated in templates. """ return True def set_password(self, raw_password): self.password = make_password(raw_password) self._password = raw_password def check_password(self, raw_password): """ Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) # Password hash upgrades shouldn't be considered password changes. self._password = None self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) def set_unusable_password(self): # Set a value that will never be a valid hash self.password = make_password(None) def has_usable_password(self): """ Return False if set_unusable_password() has been called for this user. """ return is_password_usable(self.password) def get_session_auth_hash(self): """ Return an HMAC of the password field. """ key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" return salted_hmac(key_salt, self.password).hexdigest() @classmethod def get_email_field_name(cls): try: return cls.EMAIL_FIELD except AttributeError: return 'email' @classmethod def normalize_username(cls, username): return unicodedata.normalize('NFKC', username) if isinstance(username, str) else username
a9d9eb529ecbf564c2562987d542c0a1972c68ee60ebfda213fa53e1d79ad1d6
from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured, PermissionDenied class AccessMixin: """ Abstract CBV mixin that gives access mixins the same customizable functionality. """ login_url = None permission_denied_message = '' raise_exception = False redirect_field_name = REDIRECT_FIELD_NAME def get_login_url(self): """ Override this method to override the login_url attribute. """ login_url = self.login_url or settings.LOGIN_URL if not login_url: raise ImproperlyConfigured( '{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override ' '{0}.get_login_url().'.format(self.__class__.__name__) ) return str(login_url) def get_permission_denied_message(self): """ Override this method to override the permission_denied_message attribute. """ return self.permission_denied_message def get_redirect_field_name(self): """ Override this method to override the redirect_field_name attribute. """ return self.redirect_field_name def handle_no_permission(self): if self.raise_exception or self.request.user.is_authenticated: raise PermissionDenied(self.get_permission_denied_message()) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) class LoginRequiredMixin(AccessMixin): """Verify that the current user is authenticated.""" def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() return super().dispatch(request, *args, **kwargs) class PermissionRequiredMixin(AccessMixin): """Verify that the current user has all specified permissions.""" permission_required = None def get_permission_required(self): """ Override this method to override the permission_required attribute. Must return an iterable. """ if self.permission_required is None: raise ImproperlyConfigured( '{0} is missing the permission_required attribute. Define {0}.permission_required, or override ' '{0}.get_permission_required().'.format(self.__class__.__name__) ) if isinstance(self.permission_required, str): perms = (self.permission_required,) else: perms = self.permission_required return perms def has_permission(self): """ Override this method to customize the way permissions are checked. """ perms = self.get_permission_required() return self.request.user.has_perms(perms) def dispatch(self, request, *args, **kwargs): if not self.has_permission(): return self.handle_no_permission() return super().dispatch(request, *args, **kwargs) class UserPassesTestMixin(AccessMixin): """ Deny a request with a permission error if the test_func() method returns False. """ def test_func(self): raise NotImplementedError( '{0} is missing the implementation of the test_func() method.'.format(self.__class__.__name__) ) def get_test_func(self): """ Override this method to use a different test_func method. """ return self.test_func def dispatch(self, request, *args, **kwargs): user_test_result = self.get_test_func()() if not user_test_result: return self.handle_no_permission() return super().dispatch(request, *args, **kwargs)
74719909a24f842685ad7e8d22361972b5c9ae4fb9e2d92ca45f414cb9c711d3
import unicodedata from django import forms from django.contrib.auth import ( authenticate, get_user_model, password_validation, ) from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, identify_hasher, ) from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMultiAlternatives from django.template import loader from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.utils.text import capfirst from django.utils.translation import gettext, gettext_lazy as _ UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) summary = [] if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX): summary.append({'label': gettext("No password set.")}) else: try: hasher = identify_hasher(value) except ValueError: summary.append({'label': gettext("Invalid password format or unknown hashing algorithm.")}) else: for key, value_ in hasher.safe_summary(value).items(): summary.append({'label': gettext(key), 'value': value_}) context['summary'] = summary return context class ReadOnlyPasswordHashField(forms.Field): widget = ReadOnlyPasswordHashWidget def __init__(self, *args, **kwargs): kwargs.setdefault("required", False) super().__init__(*args, **kwargs) def bound_data(self, data, initial): # Always return initial because the widget doesn't # render an input field. return initial def has_changed(self, initial, data): return False class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize('NFKC', super().to_python(value)) class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = UserModel fields = (UserModel.USERNAME_FIELD,) field_classes = {UserModel.USERNAME_FIELD: UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user's password, but you can change the password using " "<a href=\"{}\">this form</a>." ), ) class Meta: model = UserModel fields = '__all__' field_classes = {UserModel.USERNAME_FIELD: UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) password = self.fields.get('password') if password: password.help_text = password.help_text.format('../password/') user_permissions = self.fields.get('user_permissions') if user_permissions: user_permissions.queryset = user_permissions.queryset.select_related('content_type') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive."), } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super().__init__(*args, **kwargs) # Set the max length and label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) self.fields['username'].max_length = self.username_field.max_length or 254 if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``forms.ValidationError``. If the given user may log in, this method should return None. """ if not user.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) def get_user(self): return self.user_cache def get_invalid_login_error(self): return forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) class PasswordResetForm(forms.Form): email = forms.EmailField(label=_("Email"), max_length=254) def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ Send a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send() def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password. """ active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True, }) return (u for u in active_users if u.has_usable_password()) def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None): """ Generate a one-use only link for resetting password and send it to the user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', **(extra_email_context or {}), } self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, ) class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput, strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput, ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, 'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."), } old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={'autofocus': True}), ) field_order = ['old_password', 'new_password1', 'new_password2'] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password class AdminPasswordChangeForm(forms.Form): """ A form used to change the password of a user in the admin interface. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } required_css_class = 'required' password1 = forms.CharField( label=_("Password"), widget=forms.PasswordInput(attrs={'autofocus': True}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password (again)"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): """Save the new password.""" password = self.cleaned_data["password1"] self.user.set_password(password) if commit: self.user.save() return self.user @property def changed_data(self): data = super().changed_data for name in self.fields: if name not in data: return [] return ['password']
8a1b64c1dab220d6830e2c75c3758a13d19ac9a180058f3c8fa76b574987183b
from django.conf import settings from django.contrib import auth from django.contrib.auth import load_backend from django.contrib.auth.backends import RemoteUserBackend from django.core.exceptions import ImproperlyConfigured from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject def get_user(request): if not hasattr(request, '_cached_user'): request._cached_user = auth.get_user(request) return request._cached_user class AuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE%s setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) % ("_CLASSES" if settings.MIDDLEWARE is None else "") request.user = SimpleLazyObject(lambda: get_user(request)) class RemoteUserMiddleware(MiddlewareMixin): """ Middleware for utilizing Web-server-provided authentication. If request.user is not authenticated, then this middleware attempts to authenticate the username passed in the ``REMOTE_USER`` request header. If authentication is successful, the user is automatically logged in to persist the user in the session. The header used is configurable and defaults to ``REMOTE_USER``. Subclass this class and change the ``header`` attribute if you need to use a different header. """ # Name of request header to grab username from. This will be the key as # used in the request.META dictionary, i.e. the normalization of headers to # all uppercase and the addition of "HTTP_" prefix apply. header = "REMOTE_USER" force_logout_if_no_header = True def process_request(self, request): # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") try: username = request.META[self.header] except KeyError: # If specified header doesn't exist then remove any existing # authenticated remote-user, or return (leaving request.user set to # AnonymousUser by the AuthenticationMiddleware). if self.force_logout_if_no_header and request.user.is_authenticated: self._remove_invalid_user(request) return # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. if request.user.is_authenticated: if request.user.get_username() == self.clean_username(username, request): return else: # An authenticated user is associated with the request, but # it does not match the authorized user in the header. self._remove_invalid_user(request) # We are seeing this user for the first time in this session, attempt # to authenticate the user. user = auth.authenticate(request, remote_user=username) if user: # User is valid. Set request.user and persist user in the session # by logging the user in. request.user = user auth.login(request, user) def clean_username(self, username, request): """ Allow the backend to clean the username, if the backend defines a clean_username method. """ backend_str = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_str) try: username = backend.clean_username(username) except AttributeError: # Backend has no clean_username method. pass return username def _remove_invalid_user(self, request): """ Remove the current authenticated user in the request which is invalid but only if the user is authenticated via the RemoteUserBackend. """ try: stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, '')) except ImportError: # backend failed to load auth.logout(request) else: if isinstance(stored_backend, RemoteUserBackend): auth.logout(request) class PersistentRemoteUserMiddleware(RemoteUserMiddleware): """ Middleware for Web-server provided authentication on logon pages. Like RemoteUserMiddleware but keeps the user authenticated even if the header (``REMOTE_USER``) is not found in the request. Useful for setups when the external authentication via ``REMOTE_USER`` is only expected to happen on some "logon" URL and the rest of the application wants to use Django's authentication mechanism. """ force_logout_if_no_header = False
697d9faca8f50eb542b3e912bac2165086aa7dfcd75965dd039a03efb7d744fc
from urllib.parse import urlparse, urlunparse from django.conf import settings # Avoid shadowing the login() and logout() views below. from django.contrib.auth import ( REDIRECT_FIELD_NAME, get_user_model, login as auth_login, logout as auth_logout, update_session_auth_hash, ) from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm, ) from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ValidationError from django.http import HttpResponseRedirect, QueryDict from django.shortcuts import resolve_url from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.utils.http import is_safe_url, urlsafe_base64_decode from django.utils.translation import gettext_lazy as _ from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters from django.views.generic.base import TemplateView from django.views.generic.edit import FormView UserModel = get_user_model() class SuccessURLAllowedHostsMixin: success_url_allowed_hosts = set() def get_success_url_allowed_hosts(self): return {self.request.get_host(), *self.success_url_allowed_hosts} class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): if self.redirect_authenticated_user and self.request.user.is_authenticated: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def get_success_url(self): url = self.get_redirect_url() return url or resolve_url(settings.LOGIN_REDIRECT_URL) def get_redirect_url(self): """Return the user-originating redirect URL if it's safe.""" redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, '') ) url_is_safe = is_safe_url( url=redirect_to, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) return redirect_to if url_is_safe else '' def get_form_class(self): return self.authentication_form or self.form_class def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update({ self.redirect_field_name: self.get_redirect_url(), 'site': current_site, 'site_name': current_site.name, **(self.extra_context or {}) }) return context class LogoutView(SuccessURLAllowedHostsMixin, TemplateView): """ Log out the user and display the 'You are logged out' message. """ next_page = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/logged_out.html' extra_context = None @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): auth_logout(request) next_page = self.get_next_page() if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): """Logout may be done via POST.""" return self.get(request, *args, **kwargs) def get_next_page(self): if self.next_page is not None: next_page = resolve_url(self.next_page) elif settings.LOGOUT_REDIRECT_URL: next_page = resolve_url(settings.LOGOUT_REDIRECT_URL) else: next_page = self.next_page if (self.redirect_field_name in self.request.POST or self.redirect_field_name in self.request.GET): next_page = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name) ) url_is_safe = is_safe_url( url=next_page, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) # Security check -- Ensure the user-originating redirection URL is # safe. if not url_is_safe: next_page = self.request.path return next_page def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update({ 'site': current_site, 'site_name': current_site.name, 'title': _('Logged out'), **(self.extra_context or {}) }) return context def logout_then_login(request, login_url=None): """ Log out the user if they are logged in. Then redirect to the login page. """ login_url = resolve_url(login_url or settings.LOGIN_URL) return LogoutView.as_view(next_page=login_url)(request) def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Redirect the user to the login page, passing the given 'next' page. """ resolved_url = resolve_url(login_url or settings.LOGIN_URL) login_url_parts = list(urlparse(resolved_url)) if redirect_field_name: querystring = QueryDict(login_url_parts[4], mutable=True) querystring[redirect_field_name] = next login_url_parts[4] = querystring.urlencode(safe='/') return HttpResponseRedirect(urlunparse(login_url_parts)) # Class-based password reset views # - PasswordResetView sends the mail # - PasswordResetDoneView shows a success message for the above # - PasswordResetConfirmView checks the link the user clicked and # prompts for a new password # - PasswordResetCompleteView shows a success message for the above class PasswordContextMixin: extra_context = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'title': self.title, **(self.extra_context or {}) }) return context class PasswordResetView(PasswordContextMixin, FormView): email_template_name = 'registration/password_reset_email.html' extra_email_context = None form_class = PasswordResetForm from_email = None html_email_template_name = None subject_template_name = 'registration/password_reset_subject.txt' success_url = reverse_lazy('password_reset_done') template_name = 'registration/password_reset_form.html' title = _('Password reset') token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { 'use_https': self.request.is_secure(), 'token_generator': self.token_generator, 'from_email': self.from_email, 'email_template_name': self.email_template_name, 'subject_template_name': self.subject_template_name, 'request': self.request, 'html_email_template_name': self.html_email_template_name, 'extra_email_context': self.extra_email_context, } form.save(**opts) return super().form_valid(form) INTERNAL_RESET_URL_TOKEN = 'set-password' INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token' class PasswordResetDoneView(PasswordContextMixin, TemplateView): template_name = 'registration/password_reset_done.html' title = _('Password reset sent') class PasswordResetConfirmView(PasswordContextMixin, FormView): form_class = SetPasswordForm post_reset_login = False post_reset_login_backend = None success_url = reverse_lazy('password_reset_complete') template_name = 'registration/password_reset_confirm.html' title = _('Enter new password') token_generator = default_token_generator @method_decorator(sensitive_post_parameters()) @method_decorator(never_cache) def dispatch(self, *args, **kwargs): assert 'uidb64' in kwargs and 'token' in kwargs self.validlink = False self.user = self.get_user(kwargs['uidb64']) if self.user is not None: token = kwargs['token'] if token == INTERNAL_RESET_URL_TOKEN: session_token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN) if self.token_generator.check_token(self.user, session_token): # If the token is valid, display the password reset form. self.validlink = True return super().dispatch(*args, **kwargs) else: if self.token_generator.check_token(self.user, token): # Store the token in the session and redirect to the # password reset form at a URL without the token. That # avoids the possibility of leaking the token in the # HTTP Referer header. self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token redirect_url = self.request.path.replace(token, INTERNAL_RESET_URL_TOKEN) return HttpResponseRedirect(redirect_url) # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) def get_user(self, uidb64): try: # urlsafe_base64_decode() decodes to bytestring uid = urlsafe_base64_decode(uidb64).decode() user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist, ValidationError): user = None return user def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.user return kwargs def form_valid(self, form): user = form.save() del self.request.session[INTERNAL_RESET_SESSION_TOKEN] if self.post_reset_login: auth_login(self.request, user, self.post_reset_login_backend) return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.validlink: context['validlink'] = True else: context.update({ 'form': None, 'title': _('Password reset unsuccessful'), 'validlink': False, }) return context class PasswordResetCompleteView(PasswordContextMixin, TemplateView): template_name = 'registration/password_reset_complete.html' title = _('Password reset complete') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['login_url'] = resolve_url(settings.LOGIN_URL) return context class PasswordChangeView(PasswordContextMixin, FormView): form_class = PasswordChangeForm success_url = reverse_lazy('password_change_done') template_name = 'registration/password_change_form.html' title = _('Password change') @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(self.request, form.user) return super().form_valid(form) class PasswordChangeDoneView(PasswordContextMixin, TemplateView): template_name = 'registration/password_change_done.html' title = _('Password change successful') @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs)
15a6ad29a7ebc8e8219d6f0c5913741bb6dd1cf802994162752989377c5a10bf
import functools import gzip import re from difflib import SequenceMatcher from pathlib import Path from django.conf import settings from django.core.exceptions import ( FieldDoesNotExist, ImproperlyConfigured, ValidationError, ) from django.utils.functional import lazy from django.utils.html import format_html, format_html_join from django.utils.module_loading import import_string from django.utils.translation import gettext as _, ngettext @functools.lru_cache(maxsize=None) def get_default_password_validators(): return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) def get_password_validators(validator_config): validators = [] for validator in validator_config: try: klass = import_string(validator['NAME']) except ImportError: msg = "The module in NAME could not be imported: %s. Check your AUTH_PASSWORD_VALIDATORS setting." raise ImproperlyConfigured(msg % validator['NAME']) validators.append(klass(**validator.get('OPTIONS', {}))) return validators def validate_password(password, user=None, password_validators=None): """ Validate whether the password meets all validator requirements. If the password is valid, return ``None``. If the password is invalid, raise ValidationError with all error messages. """ errors = [] if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: try: validator.validate(password, user) except ValidationError as error: errors.append(error) if errors: raise ValidationError(errors) def password_changed(password, user=None, password_validators=None): """ Inform all validators that have implemented a password_changed() method that the password has been changed. """ if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: password_changed = getattr(validator, 'password_changed', lambda *a: None) password_changed(password, user) def password_validators_help_texts(password_validators=None): """ Return a list of all help texts of all configured validators. """ help_texts = [] if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: help_texts.append(validator.get_help_text()) return help_texts def _password_validators_help_text_html(password_validators=None): """ Return an HTML string with all help texts of all configured validators in an <ul>. """ help_texts = password_validators_help_texts(password_validators) help_items = format_html_join('', '<li>{}</li>', ((help_text,) for help_text in help_texts)) return format_html('<ul>{}</ul>', help_items) if help_items else '' password_validators_help_text_html = lazy(_password_validators_help_text_html, str) class MinimumLengthValidator: """ Validate whether the password is of a minimum length. """ def __init__(self, min_length=8): self.min_length = min_length def validate(self, password, user=None): if len(password) < self.min_length: raise ValidationError( ngettext( "This password is too short. It must contain at least %(min_length)d character.", "This password is too short. It must contain at least %(min_length)d characters.", self.min_length ), code='password_too_short', params={'min_length': self.min_length}, ) def get_help_text(self): return ngettext( "Your password must contain at least %(min_length)d character.", "Your password must contain at least %(min_length)d characters.", self.min_length ) % {'min_length': self.min_length} class UserAttributeSimilarityValidator: """ Validate whether the password is sufficiently different from the user's attributes. If no specific attributes are provided, look at a sensible list of defaults. Attributes that don't exist are ignored. Comparison is made to not only the full attribute value, but also its components, so that, for example, a password is validated against either part of an email address, as well as the full address. """ DEFAULT_USER_ATTRIBUTES = ('username', 'first_name', 'last_name', 'email') def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return for attribute_name in self.user_attributes: value = getattr(user, attribute_name, None) if not value or not isinstance(value, str): continue value_parts = re.split(r'\W+', value) + [value] for value_part in value_parts: if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() >= self.max_similarity: try: verbose_name = str(user._meta.get_field(attribute_name).verbose_name) except FieldDoesNotExist: verbose_name = attribute_name raise ValidationError( _("The password is too similar to the %(verbose_name)s."), code='password_too_similar', params={'verbose_name': verbose_name}, ) def get_help_text(self): return _("Your password can't be too similar to your other personal information.") class CommonPasswordValidator: """ Validate whether the password is a common password. The password is rejected if it occurs in a provided list, which may be gzipped. The list Django ships with contains 20000 common passwords, created by Royce Williams: https://gist.github.com/roycewilliams/281ce539915a947a23db17137d91aeb7 """ DEFAULT_PASSWORD_LIST_PATH = Path(__file__).resolve().parent / 'common-passwords.txt.gz' def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH): try: with gzip.open(str(password_list_path)) as f: common_passwords_lines = f.read().decode().splitlines() except IOError: with open(str(password_list_path)) as f: common_passwords_lines = f.readlines() self.passwords = {p.strip() for p in common_passwords_lines} def validate(self, password, user=None): if password.lower().strip() in self.passwords: raise ValidationError( _("This password is too common."), code='password_too_common', ) def get_help_text(self): return _("Your password can't be a commonly used password.") class NumericPasswordValidator: """ Validate whether the password is alphanumeric. """ def validate(self, password, user=None): if password.isdigit(): raise ValidationError( _("This password is entirely numeric."), code='password_entirely_numeric', ) def get_help_text(self): return _("Your password can't be entirely numeric.")
01794d85fc04776b289f3540b22b5b06f28b9c173d0aa746b809a3501f2610f3
import re from django.core import validators from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ @deconstructible class ASCIIUsernameValidator(validators.RegexValidator): regex = r'^[\w.@+-]+$' message = _( 'Enter a valid username. This value may contain only English letters, ' 'numbers, and @/./+/-/_ characters.' ) flags = re.ASCII @deconstructible class UnicodeUsernameValidator(validators.RegexValidator): regex = r'^[\w.@+-]+$' message = _( 'Enter a valid username. This value may contain only letters, ' 'numbers, and @/./+/-/_ characters.' ) flags = 0
8d04ba150d8fc5aa8661360d6b88ddc7ea9254f57d51fe5b4616c2f4f17404c3
def register(*models, site=None): """ Register the given model(s) classes and wrapped ModelAdmin class with admin site: @register(Author) class AuthorAdmin(admin.ModelAdmin): pass The `site` kwarg is an admin site to use instead of the default admin site. """ from django.contrib.admin import ModelAdmin from django.contrib.admin.sites import site as default_site, AdminSite def _model_admin_wrapper(admin_class): if not models: raise ValueError('At least one model must be passed to register.') admin_site = site or default_site if not isinstance(admin_site, AdminSite): raise ValueError('site must subclass AdminSite') if not issubclass(admin_class, ModelAdmin): raise ValueError('Wrapped class must subclass ModelAdmin.') admin_site.register(models, admin_class=admin_class) return admin_class return _model_admin_wrapper
b286ce807851635f624a73c40281c728332e5266c1e22a276ba9e2643fe9b127
import json from django import forms from django.conf import settings from django.contrib.admin.utils import ( display_for_field, flatten_fieldsets, help_text_for_field, label_for_field, lookup_field, ) from django.core.exceptions import ObjectDoesNotExist from django.db.models.fields.related import ManyToManyRel from django.forms.utils import flatatt from django.template.defaultfilters import capfirst, linebreaksbr from django.utils.html import conditional_escape, format_html from django.utils.safestring import mark_safe from django.utils.translation import gettext, gettext_lazy as _ ACTION_CHECKBOX_NAME = '_selected_action' class ActionForm(forms.Form): action = forms.ChoiceField(label=_('Action:')) select_across = forms.BooleanField( label='', required=False, initial=0, widget=forms.HiddenInput({'class': 'select-across'}), ) checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False) class AdminForm: def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None): self.form, self.fieldsets = form, fieldsets self.prepopulated_fields = [{ 'field': form[field_name], 'dependencies': [form[f] for f in dependencies] } for field_name, dependencies in prepopulated_fields.items()] self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __iter__(self): for name, options in self.fieldsets: yield Fieldset( self.form, name, readonly_fields=self.readonly_fields, model_admin=self.model_admin, **options ) @property def errors(self): return self.form.errors @property def non_field_errors(self): return self.form.non_field_errors @property def media(self): media = self.form.media for fs in self: media = media + fs.media return media class Fieldset: def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(), description=None, model_admin=None): self.form = form self.name, self.fields = name, fields self.classes = ' '.join(classes) self.description = description self.model_admin = model_admin self.readonly_fields = readonly_fields @property def media(self): if 'collapse' in self.classes: extra = '' if settings.DEBUG else '.min' js = [ 'vendor/jquery/jquery%s.js' % extra, 'jquery.init.js', 'collapse%s.js' % extra, ] return forms.Media(js=['admin/js/%s' % url for url in js]) return forms.Media() def __iter__(self): for field in self.fields: yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) class Fieldline: def __init__(self, form, field, readonly_fields=None, model_admin=None): self.form = form # A django.forms.Form instance if not hasattr(field, "__iter__") or isinstance(field, str): self.fields = [field] else: self.fields = field self.has_visible_field = not all( field in self.form.fields and self.form.fields[field].widget.is_hidden for field in self.fields ) self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __iter__(self): for i, field in enumerate(self.fields): if field in self.readonly_fields: yield AdminReadonlyField(self.form, field, is_first=(i == 0), model_admin=self.model_admin) else: yield AdminField(self.form, field, is_first=(i == 0)) def errors(self): return mark_safe( '\n'.join( self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields ).strip('\n') ) class AdminField: def __init__(self, form, field, is_first): self.field = form[field] # A django.forms.BoundField instance self.is_first = is_first # Whether this field is first on the line self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput) self.is_readonly = False def label_tag(self): classes = [] contents = conditional_escape(self.field.label) if self.is_checkbox: classes.append('vCheckboxLabel') if self.field.field.required: classes.append('required') if not self.is_first: classes.append('inline') attrs = {'class': ' '.join(classes)} if classes else {} # checkboxes should not have a label suffix as the checkbox appears # to the left of the label. return self.field.label_tag( contents=mark_safe(contents), attrs=attrs, label_suffix='' if self.is_checkbox else None, ) def errors(self): return mark_safe(self.field.errors.as_ul()) class AdminReadonlyField: def __init__(self, form, field, is_first, model_admin=None): # Make self.field look a little bit like a field. This means that # {{ field.name }} must be a useful class name to identify the field. # For convenience, store other field-related data here too. if callable(field): class_name = field.__name__ if field.__name__ != '<lambda>' else '' else: class_name = field if form._meta.labels and class_name in form._meta.labels: label = form._meta.labels[class_name] else: label = label_for_field(field, form._meta.model, model_admin) if form._meta.help_texts and class_name in form._meta.help_texts: help_text = form._meta.help_texts[class_name] else: help_text = help_text_for_field(class_name, form._meta.model) self.field = { 'name': class_name, 'label': label, 'help_text': help_text, 'field': field, } self.form = form self.model_admin = model_admin self.is_first = is_first self.is_checkbox = False self.is_readonly = True self.empty_value_display = model_admin.get_empty_value_display() def label_tag(self): attrs = {} if not self.is_first: attrs["class"] = "inline" label = self.field['label'] return format_html('<label{}>{}:</label>', flatatt(attrs), capfirst(label)) def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr) class InlineAdminFormSet: """ A wrapper around an inline formset for use in the admin system. """ def __init__(self, inline, formset, fieldsets, prepopulated_fields=None, readonly_fields=None, model_admin=None, has_add_permission=True, has_change_permission=True, has_delete_permission=True, has_view_permission=True): self.opts = inline self.formset = formset self.fieldsets = fieldsets self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields if prepopulated_fields is None: prepopulated_fields = {} self.prepopulated_fields = prepopulated_fields self.classes = ' '.join(inline.classes) if inline.classes else '' self.has_add_permission = has_add_permission self.has_change_permission = has_change_permission self.has_delete_permission = has_delete_permission self.has_view_permission = has_view_permission def __iter__(self): if self.has_change_permission: readonly_fields_for_editing = self.readonly_fields else: readonly_fields_for_editing = self.readonly_fields + flatten_fieldsets(self.fieldsets) for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()): view_on_site_url = self.opts.get_view_on_site_url(original) yield InlineAdminForm( self.formset, form, self.fieldsets, self.prepopulated_fields, original, readonly_fields_for_editing, model_admin=self.opts, view_on_site_url=view_on_site_url, ) for form in self.formset.extra_forms: yield InlineAdminForm( self.formset, form, self.fieldsets, self.prepopulated_fields, None, self.readonly_fields, model_admin=self.opts, ) if self.has_add_permission: yield InlineAdminForm( self.formset, self.formset.empty_form, self.fieldsets, self.prepopulated_fields, None, self.readonly_fields, model_admin=self.opts, ) def fields(self): fk = getattr(self.formset, "fk", None) empty_form = self.formset.empty_form meta_labels = empty_form._meta.labels or {} meta_help_texts = empty_form._meta.help_texts or {} for i, field_name in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field_name: continue if not self.has_change_permission or field_name in self.readonly_fields: yield { 'label': meta_labels.get(field_name) or label_for_field(field_name, self.opts.model, self.opts), 'widget': {'is_hidden': False}, 'required': False, 'help_text': meta_help_texts.get(field_name) or help_text_for_field(field_name, self.opts.model), } else: form_field = empty_form.fields[field_name] label = form_field.label if label is None: label = label_for_field(field_name, self.opts.model, self.opts) yield { 'label': label, 'widget': form_field.widget, 'required': form_field.required, 'help_text': form_field.help_text, } def inline_formset_data(self): verbose_name = self.opts.verbose_name return json.dumps({ 'name': '#%s' % self.formset.prefix, 'options': { 'prefix': self.formset.prefix, 'addText': gettext('Add another %(verbose_name)s') % { 'verbose_name': capfirst(verbose_name), }, 'deleteText': gettext('Remove'), } }) @property def forms(self): return self.formset.forms @property def non_form_errors(self): return self.formset.non_form_errors @property def media(self): media = self.opts.media + self.formset.media for fs in self: media = media + fs.media return media class InlineAdminForm(AdminForm): """ A wrapper around an inline form for use in the admin system. """ def __init__(self, formset, form, fieldsets, prepopulated_fields, original, readonly_fields=None, model_admin=None, view_on_site_url=None): self.formset = formset self.model_admin = model_admin self.original = original self.show_url = original and view_on_site_url is not None self.absolute_url = view_on_site_url super().__init__(form, fieldsets, prepopulated_fields, readonly_fields, model_admin) def __iter__(self): for name, options in self.fieldsets: yield InlineFieldset( self.formset, self.form, name, self.readonly_fields, model_admin=self.model_admin, **options ) def needs_explicit_pk_field(self): return ( # Auto fields are editable, so check for auto or non-editable pk. self.form._meta.model._meta.auto_field or not self.form._meta.model._meta.pk.editable or # Also search any parents for an auto field. (The pk info is # propagated to child models so that does not need to be checked # in parents.) any(parent._meta.auto_field or not parent._meta.model._meta.pk.editable for parent in self.form._meta.model._meta.get_parent_list()) ) def pk_field(self): return AdminField(self.form, self.formset._pk_field.name, False) def fk_field(self): fk = getattr(self.formset, "fk", None) if fk: return AdminField(self.form, fk.name, False) else: return "" def deletion_field(self): from django.forms.formsets import DELETION_FIELD_NAME return AdminField(self.form, DELETION_FIELD_NAME, False) def ordering_field(self): from django.forms.formsets import ORDERING_FIELD_NAME return AdminField(self.form, ORDERING_FIELD_NAME, False) class InlineFieldset(Fieldset): def __init__(self, formset, *args, **kwargs): self.formset = formset super().__init__(*args, **kwargs) def __iter__(self): fk = getattr(self.formset, "fk", None) for field in self.fields: if not fk or fk.name != field: yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) class AdminErrorList(forms.utils.ErrorList): """Store errors for the form/formsets in an add/change view.""" def __init__(self, form, inline_formsets): super().__init__() if form.is_bound: self.extend(form.errors.values()) for inline_formset in inline_formsets: self.extend(inline_formset.non_form_errors()) for errors_in_inline_form in inline_formset.errors: self.extend(errors_in_inline_form.values())
78efa2574f2aa3aceb36e3e26ed6f986b432072ab6d150e4d298d648b6135c51
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import modify_settings from django.test.selenium import SeleniumTestCase from django.utils.deprecation import MiddlewareMixin from django.utils.translation import gettext as _ class CSPMiddleware(MiddlewareMixin): """The admin's JavaScript should be compatible with CSP.""" def process_response(self, request, response): response['Content-Security-Policy'] = "default-src 'self'" return response @modify_settings(MIDDLEWARE={'append': 'django.contrib.admin.tests.CSPMiddleware'}) class AdminSeleniumTestCase(SeleniumTestCase, StaticLiveServerTestCase): available_apps = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', ] def wait_until(self, callback, timeout=10): """ Block the execution of the tests until the specified callback returns a value that is not falsy. This method can be called, for example, after clicking a link or submitting a form. See the other public methods that call this function for more details. """ from selenium.webdriver.support.wait import WebDriverWait WebDriverWait(self.selenium, timeout).until(callback) def wait_for_popup(self, num_windows=2, timeout=10): """ Block until `num_windows` are present (usually 2, but can be overridden in the case of pop-ups opening other pop-ups). """ self.wait_until(lambda d: len(d.window_handles) == num_windows, timeout) def wait_for(self, css_selector, timeout=10): """ Block until a CSS selector is found on the page. """ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec self.wait_until( ec.presence_of_element_located((By.CSS_SELECTOR, css_selector)), timeout ) def wait_for_text(self, css_selector, text, timeout=10): """ Block until the text is found in the CSS selector. """ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec self.wait_until( ec.text_to_be_present_in_element( (By.CSS_SELECTOR, css_selector), text), timeout ) def wait_for_value(self, css_selector, text, timeout=10): """ Block until the value is found in the CSS selector. """ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec self.wait_until( ec.text_to_be_present_in_element_value( (By.CSS_SELECTOR, css_selector), text), timeout ) def wait_until_visible(self, css_selector, timeout=10): """ Block until the element described by the CSS selector is visible. """ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec self.wait_until( ec.visibility_of_element_located((By.CSS_SELECTOR, css_selector)), timeout ) def wait_until_invisible(self, css_selector, timeout=10): """ Block until the element described by the CSS selector is invisible. """ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec self.wait_until( ec.invisibility_of_element_located((By.CSS_SELECTOR, css_selector)), timeout ) def wait_page_loaded(self): """ Block until page has started to load. """ from selenium.common.exceptions import TimeoutException try: # Wait for the next page to be loaded self.wait_for('body') except TimeoutException: # IE7 occasionally returns an error "Internet Explorer cannot # display the webpage" and doesn't load the next page. We just # ignore it. pass def admin_login(self, username, password, login_url='/admin/'): """ Log in to the admin. """ self.selenium.get('%s%s' % (self.live_server_url, login_url)) username_input = self.selenium.find_element_by_name('username') username_input.send_keys(username) password_input = self.selenium.find_element_by_name('password') password_input.send_keys(password) login_text = _('Log in') self.selenium.find_element_by_xpath( '//input[@value="%s"]' % login_text).click() self.wait_page_loaded() def get_css_value(self, selector, attribute): """ Return the value for the CSS attribute of a DOM element specified by the given selector. Uses the jQuery that ships with Django. """ return self.selenium.execute_script( 'return django.jQuery("%s").css("%s")' % (selector, attribute)) def get_select_option(self, selector, value): """ Return the <OPTION> with the value `value` inside the <SELECT> widget identified by the CSS selector `selector`. """ from selenium.common.exceptions import NoSuchElementException options = self.selenium.find_elements_by_css_selector('%s > option' % selector) for option in options: if option.get_attribute('value') == value: return option raise NoSuchElementException('Option "%s" not found in "%s"' % (value, selector)) def _assertOptionsValues(self, options_selector, values): if values: options = self.selenium.find_elements_by_css_selector(options_selector) actual_values = [] for option in options: actual_values.append(option.get_attribute('value')) self.assertEqual(values, actual_values) else: # Prevent the `find_elements_by_css_selector` call from blocking # if the selector doesn't match any options as we expect it # to be the case. with self.disable_implicit_wait(): self.wait_until( lambda driver: not driver.find_elements_by_css_selector(options_selector) ) def assertSelectOptions(self, selector, values): """ Assert that the <SELECT> widget identified by `selector` has the options with the given `values`. """ self._assertOptionsValues("%s > option" % selector, values) def assertSelectedOptions(self, selector, values): """ Assert that the <SELECT> widget identified by `selector` has the selected options with the given `values`. """ self._assertOptionsValues("%s > option:checked" % selector, values) def has_css_class(self, selector, klass): """ Return True if the element identified by `selector` has the CSS class `klass`. """ return (self.selenium.find_element_by_css_selector(selector) .get_attribute('class').find(klass) != -1)
2b9219e89e6e8ec86ca676bab9b4efa457d306353ba7c121b1bbd6e86edf3306
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.decorators import register from django.contrib.admin.filters import ( AllValuesFieldListFilter, BooleanFieldListFilter, ChoicesFieldListFilter, DateFieldListFilter, FieldListFilter, ListFilter, RelatedFieldListFilter, RelatedOnlyFieldListFilter, SimpleListFilter, ) from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ( HORIZONTAL, VERTICAL, ModelAdmin, StackedInline, TabularInline, ) from django.contrib.admin.sites import AdminSite, site from django.utils.module_loading import autodiscover_modules __all__ = [ "register", "ACTION_CHECKBOX_NAME", "ModelAdmin", "HORIZONTAL", "VERTICAL", "StackedInline", "TabularInline", "AdminSite", "site", "ListFilter", "SimpleListFilter", "FieldListFilter", "BooleanFieldListFilter", "RelatedFieldListFilter", "ChoicesFieldListFilter", "DateFieldListFilter", "AllValuesFieldListFilter", "RelatedOnlyFieldListFilter", "autodiscover", ] def autodiscover(): autodiscover_modules('admin', register_to=site) default_app_config = 'django.contrib.admin.apps.AdminConfig'
28b12f39f3f9c98a12138094ea7353dfa5d08fdc14855b30d8321b283104907e
import warnings from itertools import chain from django.apps import apps from django.conf import settings from django.contrib.admin.utils import ( NotRelationField, flatten, get_fields_from_path, ) from django.core import checks from django.core.exceptions import FieldDoesNotExist from django.db import models from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import Combinable, F, OrderBy from django.forms.models import ( BaseModelForm, BaseModelFormSet, _get_foreign_key, ) from django.template.engine import Engine from django.utils.deprecation import RemovedInDjango30Warning from django.utils.inspect import get_func_args def check_admin_app(app_configs, **kwargs): from django.contrib.admin.sites import all_sites errors = [] for site in all_sites: errors.extend(site.check(app_configs)) return errors def check_dependencies(**kwargs): """ Check that the admin's dependencies are correctly installed. """ errors = [] # contrib.contenttypes must be installed. if not apps.is_installed('django.contrib.contenttypes'): missing_app = checks.Error( "'django.contrib.contenttypes' must be in INSTALLED_APPS in order " "to use the admin application.", id="admin.E401", ) errors.append(missing_app) # The auth context processor must be installed if using the default # authentication backend. try: default_template_engine = Engine.get_default() except Exception: # Skip this non-critical check: # 1. if the user has a non-trivial TEMPLATES setting and Django # can't find a default template engine # 2. if anything goes wrong while loading template engines, in # order to avoid raising an exception from a confusing location # Catching ImproperlyConfigured suffices for 1. but 2. requires # catching all exceptions. pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors and 'django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS): missing_template = checks.Error( "'django.contrib.auth.context_processors.auth' must be in " "TEMPLATES in order to use the admin application.", id="admin.E402" ) errors.append(missing_template) return errors class BaseModelAdminChecks: def check(self, admin_obj, **kwargs): return [ *self._check_autocomplete_fields(admin_obj), *self._check_raw_id_fields(admin_obj), *self._check_fields(admin_obj), *self._check_fieldsets(admin_obj), *self._check_exclude(admin_obj), *self._check_form(admin_obj), *self._check_filter_vertical(admin_obj), *self._check_filter_horizontal(admin_obj), *self._check_radio_fields(admin_obj), *self._check_prepopulated_fields(admin_obj), *self._check_view_on_site_url(admin_obj), *self._check_ordering(admin_obj), *self._check_readonly_fields(admin_obj), ] def _check_autocomplete_fields(self, obj): """ Check that `autocomplete_fields` is a list or tuple of model fields. """ if not isinstance(obj.autocomplete_fields, (list, tuple)): return must_be('a list or tuple', option='autocomplete_fields', obj=obj, id='admin.E036') else: return list(chain.from_iterable([ self._check_autocomplete_fields_item(obj, obj.model, field_name, 'autocomplete_fields[%d]' % index) for index, field_name in enumerate(obj.autocomplete_fields) ])) def _check_autocomplete_fields_item(self, obj, model, field_name, label): """ Check that an item in `autocomplete_fields` is a ForeignKey or a ManyToManyField and that the item has a related ModelAdmin with search_fields defined. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E037') else: if not field.many_to_many and not isinstance(field, models.ForeignKey): return must_be( 'a foreign key or a many-to-many field', option=label, obj=obj, id='admin.E038' ) related_admin = obj.admin_site._registry.get(field.remote_field.model) if related_admin is None: return [ checks.Error( 'An admin for model "%s" has to be registered ' 'to be referenced by %s.autocomplete_fields.' % ( field.remote_field.model.__name__, type(obj).__name__, ), obj=obj.__class__, id='admin.E039', ) ] elif not related_admin.search_fields: return [ checks.Error( '%s must define "search_fields", because it\'s ' 'referenced by %s.autocomplete_fields.' % ( related_admin.__class__.__name__, type(obj).__name__, ), obj=obj.__class__, id='admin.E040', ) ] return [] def _check_raw_id_fields(self, obj): """ Check that `raw_id_fields` only contains field names that are listed on the model. """ if not isinstance(obj.raw_id_fields, (list, tuple)): return must_be('a list or tuple', option='raw_id_fields', obj=obj, id='admin.E001') else: return list(chain.from_iterable( self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index) for index, field_name in enumerate(obj.raw_id_fields) )) def _check_raw_id_fields_item(self, obj, model, field_name, label): """ Check an item of `raw_id_fields`, i.e. check that field named `field_name` exists in model `model` and is a ForeignKey or a ManyToManyField. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E002') else: if not field.many_to_many and not isinstance(field, models.ForeignKey): return must_be('a foreign key or a many-to-many field', option=label, obj=obj, id='admin.E003') else: return [] def _check_fields(self, obj): """ Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ if obj.fields is None: return [] elif not isinstance(obj.fields, (list, tuple)): return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004') elif obj.fieldsets: return [ checks.Error( "Both 'fieldsets' and 'fields' are specified.", obj=obj.__class__, id='admin.E005', ) ] fields = flatten(obj.fields) if len(fields) != len(set(fields)): return [ checks.Error( "The value of 'fields' contains duplicate field(s).", obj=obj.__class__, id='admin.E006', ) ] return list(chain.from_iterable( self._check_field_spec(obj, obj.model, field_name, 'fields') for field_name in obj.fields )) def _check_fieldsets(self, obj): """ Check that fieldsets is properly formatted and doesn't contain duplicates. """ if obj.fieldsets is None: return [] elif not isinstance(obj.fieldsets, (list, tuple)): return must_be('a list or tuple', option='fieldsets', obj=obj, id='admin.E007') else: seen_fields = [] return list(chain.from_iterable( self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index, seen_fields) for index, fieldset in enumerate(obj.fieldsets) )) def _check_fieldsets_item(self, obj, model, fieldset, label, seen_fields): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ if not isinstance(fieldset, (list, tuple)): return must_be('a list or tuple', option=label, obj=obj, id='admin.E008') elif len(fieldset) != 2: return must_be('of length 2', option=label, obj=obj, id='admin.E009') elif not isinstance(fieldset[1], dict): return must_be('a dictionary', option='%s[1]' % label, obj=obj, id='admin.E010') elif 'fields' not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, obj=obj.__class__, id='admin.E011', ) ] elif not isinstance(fieldset[1]['fields'], (list, tuple)): return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, id='admin.E008') seen_fields.extend(flatten(fieldset[1]['fields'])) if len(seen_fields) != len(set(seen_fields)): return [ checks.Error( "There are duplicate field(s) in '%s[1]'." % label, obj=obj.__class__, id='admin.E012', ) ] return list(chain.from_iterable( self._check_field_spec(obj, model, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]['fields'] )) def _check_field_spec(self, obj, model, fields, label): """ `fields` should be an item of `fields` or an item of fieldset[1]['fields'] for any `fieldset` in `fieldsets`. It should be a field name or a tuple of field names. """ if isinstance(fields, tuple): return list(chain.from_iterable( self._check_field_spec_item(obj, model, field_name, "%s[%d]" % (label, index)) for index, field_name in enumerate(fields) )) else: return self._check_field_spec_item(obj, model, fields, label) def _check_field_spec_item(self, obj, model, field_name, label): if field_name in obj.readonly_fields: # Stuff can be put in fields that isn't actually a model field if # it's in readonly_fields, readonly_fields will handle the # validation of such things. return [] else: try: field = model._meta.get_field(field_name) except FieldDoesNotExist: # If we can't find a field on the model that matches, it could # be an extra field on the form. return [] else: if (isinstance(field, models.ManyToManyField) and not field.remote_field.through._meta.auto_created): return [ checks.Error( "The value of '%s' cannot include the ManyToManyField '%s', " "because that field manually specifies a relationship model." % (label, field_name), obj=obj.__class__, id='admin.E013', ) ] else: return [] def _check_exclude(self, obj): """ Check that exclude is a sequence without duplicates. """ if obj.exclude is None: # default value is None return [] elif not isinstance(obj.exclude, (list, tuple)): return must_be('a list or tuple', option='exclude', obj=obj, id='admin.E014') elif len(obj.exclude) > len(set(obj.exclude)): return [ checks.Error( "The value of 'exclude' contains duplicate field(s).", obj=obj.__class__, id='admin.E015', ) ] else: return [] def _check_form(self, obj): """ Check that form subclasses BaseModelForm. """ if not issubclass(obj.form, BaseModelForm): return must_inherit_from(parent='BaseModelForm', option='form', obj=obj, id='admin.E016') else: return [] def _check_filter_vertical(self, obj): """ Check that filter_vertical is a sequence of field names. """ if not isinstance(obj.filter_vertical, (list, tuple)): return must_be('a list or tuple', option='filter_vertical', obj=obj, id='admin.E017') else: return list(chain.from_iterable( self._check_filter_item(obj, obj.model, field_name, "filter_vertical[%d]" % index) for index, field_name in enumerate(obj.filter_vertical) )) def _check_filter_horizontal(self, obj): """ Check that filter_horizontal is a sequence of field names. """ if not isinstance(obj.filter_horizontal, (list, tuple)): return must_be('a list or tuple', option='filter_horizontal', obj=obj, id='admin.E018') else: return list(chain.from_iterable( self._check_filter_item(obj, obj.model, field_name, "filter_horizontal[%d]" % index) for index, field_name in enumerate(obj.filter_horizontal) )) def _check_filter_item(self, obj, model, field_name, label): """ Check one item of `filter_vertical` or `filter_horizontal`, i.e. check that given field exists and is a ManyToManyField. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E019') else: if not field.many_to_many: return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020') else: return [] def _check_radio_fields(self, obj): """ Check that `radio_fields` is a dictionary. """ if not isinstance(obj.radio_fields, dict): return must_be('a dictionary', option='radio_fields', obj=obj, id='admin.E021') else: return list(chain.from_iterable( self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') + self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name) for field_name, val in obj.radio_fields.items() )) def _check_radio_fields_key(self, obj, model, field_name, label): """ Check that a key of `radio_fields` dictionary is name of existing field and that the field is a ForeignKey or has `choices` defined. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E022') else: if not (isinstance(field, models.ForeignKey) or field.choices): return [ checks.Error( "The value of '%s' refers to '%s', which is not an " "instance of ForeignKey, and does not have a 'choices' definition." % ( label, field_name ), obj=obj.__class__, id='admin.E023', ) ] else: return [] def _check_radio_fields_value(self, obj, val, label): """ Check type of a value of `radio_fields` dictionary. """ from django.contrib.admin.options import HORIZONTAL, VERTICAL if val not in (HORIZONTAL, VERTICAL): return [ checks.Error( "The value of '%s' must be either admin.HORIZONTAL or admin.VERTICAL." % label, obj=obj.__class__, id='admin.E024', ) ] else: return [] def _check_view_on_site_url(self, obj): if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): return [ checks.Error( "The value of 'view_on_site' must be a callable or a boolean value.", obj=obj.__class__, id='admin.E025', ) ] else: return [] def _check_prepopulated_fields(self, obj): """ Check that `prepopulated_fields` is a dictionary containing allowed field types. """ if not isinstance(obj.prepopulated_fields, dict): return must_be('a dictionary', option='prepopulated_fields', obj=obj, id='admin.E026') else: return list(chain.from_iterable( self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') + self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name) for field_name, val in obj.prepopulated_fields.items() )) def _check_prepopulated_fields_key(self, obj, model, field_name, label): """ Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E027') else: if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): return [ checks.Error( "The value of '%s' refers to '%s', which must not be a DateTimeField, " "a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name), obj=obj.__class__, id='admin.E028', ) ] else: return [] def _check_prepopulated_fields_value(self, obj, model, val, label): """ Check a value of `prepopulated_fields` dictionary, i.e. it's an iterable of existing fields. """ if not isinstance(val, (list, tuple)): return must_be('a list or tuple', option=label, obj=obj, id='admin.E029') else: return list(chain.from_iterable( self._check_prepopulated_fields_value_item(obj, model, subfield_name, "%s[%r]" % (label, index)) for index, subfield_name in enumerate(val) )) def _check_prepopulated_fields_value_item(self, obj, model, field_name, label): """ For `prepopulated_fields` equal to {"slug": ("title",)}, `field_name` is "title". """ try: model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E030') else: return [] def _check_ordering(self, obj): """ Check that ordering refers to existing fields or is random. """ # ordering = None if obj.ordering is None: # The default value is None return [] elif not isinstance(obj.ordering, (list, tuple)): return must_be('a list or tuple', option='ordering', obj=obj, id='admin.E031') else: return list(chain.from_iterable( self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index) for index, field_name in enumerate(obj.ordering) )) def _check_ordering_item(self, obj, model, field_name, label): """ Check that `ordering` refers to existing fields. """ if isinstance(field_name, (Combinable, OrderBy)): if not isinstance(field_name, OrderBy): field_name = field_name.asc() if isinstance(field_name.expression, F): field_name = field_name.expression.name else: return [] if field_name == '?' and len(obj.ordering) != 1: return [ checks.Error( "The value of 'ordering' has the random ordering marker '?', " "but contains other fields as well.", hint='Either remove the "?", or remove the other fields.', obj=obj.__class__, id='admin.E032', ) ] elif field_name == '?': return [] elif LOOKUP_SEP in field_name: # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). return [] else: if field_name.startswith('-'): field_name = field_name[1:] if field_name == 'pk': return [] try: model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033') else: return [] def _check_readonly_fields(self, obj): """ Check that readonly_fields refers to proper attribute or field. """ if obj.readonly_fields == (): return [] elif not isinstance(obj.readonly_fields, (list, tuple)): return must_be('a list or tuple', option='readonly_fields', obj=obj, id='admin.E034') else: return list(chain.from_iterable( self._check_readonly_fields_item(obj, obj.model, field_name, "readonly_fields[%d]" % index) for index, field_name in enumerate(obj.readonly_fields) )) def _check_readonly_fields_item(self, obj, model, field_name, label): if callable(field_name): return [] elif hasattr(obj, field_name): return [] elif hasattr(model, field_name): return [] else: try: model._meta.get_field(field_name) except FieldDoesNotExist: return [ checks.Error( "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % ( label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name ), obj=obj.__class__, id='admin.E035', ) ] else: return [] class ModelAdminChecks(BaseModelAdminChecks): def check(self, admin_obj, **kwargs): return [ *super().check(admin_obj), *self._check_save_as(admin_obj), *self._check_save_on_top(admin_obj), *self._check_inlines(admin_obj), *self._check_list_display(admin_obj), *self._check_list_display_links(admin_obj), *self._check_list_filter(admin_obj), *self._check_list_select_related(admin_obj), *self._check_list_per_page(admin_obj), *self._check_list_max_show_all(admin_obj), *self._check_list_editable(admin_obj), *self._check_search_fields(admin_obj), *self._check_date_hierarchy(admin_obj), *self._check_action_permission_methods(admin_obj), ] def _check_save_as(self, obj): """ Check save_as is a boolean. """ if not isinstance(obj.save_as, bool): return must_be('a boolean', option='save_as', obj=obj, id='admin.E101') else: return [] def _check_save_on_top(self, obj): """ Check save_on_top is a boolean. """ if not isinstance(obj.save_on_top, bool): return must_be('a boolean', option='save_on_top', obj=obj, id='admin.E102') else: return [] def _check_inlines(self, obj): """ Check all inline model admin classes. """ if not isinstance(obj.inlines, (list, tuple)): return must_be('a list or tuple', option='inlines', obj=obj, id='admin.E103') else: return list(chain.from_iterable( self._check_inlines_item(obj, obj.model, item, "inlines[%d]" % index) for index, item in enumerate(obj.inlines) )) def _check_inlines_item(self, obj, model, inline, label): """ Check one inline model admin. """ inline_label = inline.__module__ + '.' + inline.__name__ from django.contrib.admin.options import InlineModelAdmin if not issubclass(inline, InlineModelAdmin): return [ checks.Error( "'%s' must inherit from 'InlineModelAdmin'." % inline_label, obj=obj.__class__, id='admin.E104', ) ] elif not inline.model: return [ checks.Error( "'%s' must have a 'model' attribute." % inline_label, obj=obj.__class__, id='admin.E105', ) ] elif not issubclass(inline.model, models.Model): return must_be('a Model', option='%s.model' % inline_label, obj=obj, id='admin.E106') else: return inline(model, obj.admin_site).check() def _check_list_display(self, obj): """ Check that list_display only contains fields or usable attributes. """ if not isinstance(obj.list_display, (list, tuple)): return must_be('a list or tuple', option='list_display', obj=obj, id='admin.E107') else: return list(chain.from_iterable( self._check_list_display_item(obj, obj.model, item, "list_display[%d]" % index) for index, item in enumerate(obj.list_display) )) def _check_list_display_item(self, obj, model, item, label): if callable(item): return [] elif hasattr(obj, item): return [] elif hasattr(model, item): try: field = model._meta.get_field(item) except FieldDoesNotExist: return [] else: if isinstance(field, models.ManyToManyField): return [ checks.Error( "The value of '%s' must not be a ManyToManyField." % label, obj=obj.__class__, id='admin.E109', ) ] return [] else: return [ checks.Error( "The value of '%s' refers to '%s', which is not a callable, " "an attribute of '%s', or an attribute or method on '%s.%s'." % ( label, item, obj.__class__.__name__, model._meta.app_label, model._meta.object_name, ), obj=obj.__class__, id='admin.E108', ) ] def _check_list_display_links(self, obj): """ Check that list_display_links is a unique subset of list_display. """ from django.contrib.admin.options import ModelAdmin if obj.list_display_links is None: return [] elif not isinstance(obj.list_display_links, (list, tuple)): return must_be('a list, a tuple, or None', option='list_display_links', obj=obj, id='admin.E110') # Check only if ModelAdmin.get_list_display() isn't overridden. elif obj.get_list_display.__func__ is ModelAdmin.get_list_display: return list(chain.from_iterable( self._check_list_display_links_item(obj, field_name, "list_display_links[%d]" % index) for index, field_name in enumerate(obj.list_display_links) )) return [] def _check_list_display_links_item(self, obj, field_name, label): if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not defined in 'list_display'." % ( label, field_name ), obj=obj.__class__, id='admin.E111', ) ] else: return [] def _check_list_filter(self, obj): if not isinstance(obj.list_filter, (list, tuple)): return must_be('a list or tuple', option='list_filter', obj=obj, id='admin.E112') else: return list(chain.from_iterable( self._check_list_filter_item(obj, obj.model, item, "list_filter[%d]" % index) for index, item in enumerate(obj.list_filter) )) def _check_list_filter_item(self, obj, model, item, label): """ Check one item of `list_filter`, i.e. check if it is one of three options: 1. 'field' -- a basic field filter, possibly w/ relationships (e.g. 'field__rel') 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class """ from django.contrib.admin import ListFilter, FieldListFilter if callable(item) and not isinstance(item, models.Field): # If item is option 3, it should be a ListFilter... if not issubclass(item, ListFilter): return must_inherit_from(parent='ListFilter', option=label, obj=obj, id='admin.E113') # ... but not a FieldListFilter. elif issubclass(item, FieldListFilter): return [ checks.Error( "The value of '%s' must not inherit from 'FieldListFilter'." % label, obj=obj.__class__, id='admin.E114', ) ] else: return [] elif isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item if not issubclass(list_filter_class, FieldListFilter): return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label, obj=obj, id='admin.E115') else: return [] else: # item is option #1 field = item # Validate the field string try: get_fields_from_path(model, field) except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field), obj=obj.__class__, id='admin.E116', ) ] else: return [] def _check_list_select_related(self, obj): """ Check that list_select_related is a boolean, a list or a tuple. """ if not isinstance(obj.list_select_related, (bool, list, tuple)): return must_be('a boolean, tuple or list', option='list_select_related', obj=obj, id='admin.E117') else: return [] def _check_list_per_page(self, obj): """ Check that list_per_page is an integer. """ if not isinstance(obj.list_per_page, int): return must_be('an integer', option='list_per_page', obj=obj, id='admin.E118') else: return [] def _check_list_max_show_all(self, obj): """ Check that list_max_show_all is an integer. """ if not isinstance(obj.list_max_show_all, int): return must_be('an integer', option='list_max_show_all', obj=obj, id='admin.E119') else: return [] def _check_list_editable(self, obj): """ Check that list_editable is a sequence of editable fields from list_display without first element. """ if not isinstance(obj.list_editable, (list, tuple)): return must_be('a list or tuple', option='list_editable', obj=obj, id='admin.E120') else: return list(chain.from_iterable( self._check_list_editable_item(obj, obj.model, item, "list_editable[%d]" % index) for index, item in enumerate(obj.list_editable) )) def _check_list_editable_item(self, obj, model, field_name, label): try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E121') else: if field_name not in obj.list_display: return [ checks.Error( "The value of '%s' refers to '%s', which is not " "contained in 'list_display'." % (label, field_name), obj=obj.__class__, id='admin.E122', ) ] elif obj.list_display_links and field_name in obj.list_display_links: return [ checks.Error( "The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." % field_name, obj=obj.__class__, id='admin.E123', ) ] # If list_display[0] is in list_editable, check that # list_display_links is set. See #22792 and #26229 for use cases. elif (obj.list_display[0] == field_name and not obj.list_display_links and obj.list_display_links is not None): return [ checks.Error( "The value of '%s' refers to the first field in 'list_display' ('%s'), " "which cannot be used unless 'list_display_links' is set." % ( label, obj.list_display[0] ), obj=obj.__class__, id='admin.E124', ) ] elif not field.editable: return [ checks.Error( "The value of '%s' refers to '%s', which is not editable through the admin." % ( label, field_name ), obj=obj.__class__, id='admin.E125', ) ] else: return [] def _check_search_fields(self, obj): """ Check search_fields is a sequence. """ if not isinstance(obj.search_fields, (list, tuple)): return must_be('a list or tuple', option='search_fields', obj=obj, id='admin.E126') else: return [] def _check_date_hierarchy(self, obj): """ Check that date_hierarchy refers to DateField or DateTimeField. """ if obj.date_hierarchy is None: return [] else: try: field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of 'date_hierarchy' refers to '%s', which " "does not refer to a Field." % obj.date_hierarchy, obj=obj.__class__, id='admin.E127', ) ] else: if not isinstance(field, (models.DateField, models.DateTimeField)): return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128') else: return [] def _check_action_permission_methods(self, obj): """ Actions with an allowed_permission attribute require the ModelAdmin to implement a has_<perm>_permission() method for each permission. """ actions = obj._get_base_actions() errors = [] for func, name, _ in actions: if not hasattr(func, 'allowed_permissions'): continue for permission in func.allowed_permissions: method_name = 'has_%s_permission' % permission if not hasattr(obj, method_name): errors.append( checks.Error( '%s must define a %s() method for the %s action.' % ( obj.__class__.__name__, method_name, func.__name__, ), obj=obj.__class__, id='admin.E129', ) ) return errors class InlineModelAdminChecks(BaseModelAdminChecks): def check(self, inline_obj, **kwargs): self._check_has_add_permission(inline_obj) parent_model = inline_obj.parent_model return [ *super().check(inline_obj), *self._check_relation(inline_obj, parent_model), *self._check_exclude_of_parent_model(inline_obj, parent_model), *self._check_extra(inline_obj), *self._check_max_num(inline_obj), *self._check_min_num(inline_obj), *self._check_formset(inline_obj), ] def _check_exclude_of_parent_model(self, obj, parent_model): # Do not perform more specific checks if the base checks result in an # error. errors = super()._check_exclude(obj) if errors: return [] # Skip if `fk_name` is invalid. if self._check_relation(obj, parent_model): return [] if obj.exclude is None: return [] fk = _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) if fk.name in obj.exclude: return [ checks.Error( "Cannot exclude the field '%s', because it is the foreign key " "to the parent model '%s.%s'." % ( fk.name, parent_model._meta.app_label, parent_model._meta.object_name ), obj=obj.__class__, id='admin.E201', ) ] else: return [] def _check_relation(self, obj, parent_model): try: _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) except ValueError as e: return [checks.Error(e.args[0], obj=obj.__class__, id='admin.E202')] else: return [] def _check_extra(self, obj): """ Check that extra is an integer. """ if not isinstance(obj.extra, int): return must_be('an integer', option='extra', obj=obj, id='admin.E203') else: return [] def _check_max_num(self, obj): """ Check that max_num is an integer. """ if obj.max_num is None: return [] elif not isinstance(obj.max_num, int): return must_be('an integer', option='max_num', obj=obj, id='admin.E204') else: return [] def _check_min_num(self, obj): """ Check that min_num is an integer. """ if obj.min_num is None: return [] elif not isinstance(obj.min_num, int): return must_be('an integer', option='min_num', obj=obj, id='admin.E205') else: return [] def _check_formset(self, obj): """ Check formset is a subclass of BaseModelFormSet. """ if not issubclass(obj.formset, BaseModelFormSet): return must_inherit_from(parent='BaseModelFormSet', option='formset', obj=obj, id='admin.E206') else: return [] def _check_has_add_permission(self, obj): cls = obj.__class__ try: func = cls.has_add_permission except AttributeError: pass else: args = get_func_args(func) if 'obj' not in args: warnings.warn( "Update %s.has_add_permission() to accept a positional " "`obj` argument." % cls.__name__, RemovedInDjango30Warning ) def must_be(type, option, obj, id): return [ checks.Error( "The value of '%s' must be %s." % (option, type), obj=obj.__class__, id=id, ), ] def must_inherit_from(parent, option, obj, id): return [ checks.Error( "The value of '%s' must inherit from '%s'." % (option, parent), obj=obj.__class__, id=id, ), ] def refer_to_missing_field(field, option, model, obj, id): return [ checks.Error( "The value of '%s' refers to '%s', which is not an attribute of '%s.%s'." % ( option, field, model._meta.app_label, model._meta.object_name ), obj=obj.__class__, id=id, ), ]