class FlatPage(models.Model): url = models.CharField(_('URL'), max_length=100, db_index=True) title = models.CharField(_('title'), max_length=200) content = models.TextField(_('content'), blank=True) enable_comments = models.BooleanField(_('enable comments'), default=False) template_name = models.CharField( _('template name'), max_length=70, blank=True, help_text=_( "Example: 'flatpages/contact_page.html'. If this isn't provided, " "the system will use 'flatpages/default.html'."), ) registration_required = models.BooleanField( _('registration required'), help_text= _("If this is checked, only logged-in users will be able to view the page." ), default=False, ) sites = models.ManyToManyField(Site, verbose_name=_('sites')) class Meta: db_table = 'server_flatpage' verbose_name = _('flat page') verbose_name_plural = _('flat pages') ordering = ('url', ) def __str__(self): return "%s -- %s" % (self.url, self.title) def get_absolute_url(self): # Handle script prefix manually because we bypass reverse() return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
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 = 'server_redirect' unique_together = (('site', 'old_path'), ) ordering = ('old_path', ) def __str__(self): return "%s ---> %s" % (self.old_path, self.new_path)
class Migration(models.Model): app = models.CharField(max_length=255) name = models.CharField(max_length=255) applied = models.DateTimeField(default=now) class Meta: apps = Apps() app_label = "migrations" db_table = "server_migrations" def __str__(self): return "Migration %s for %s" % (self.name, self.app)
class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.CreateModel( name='FlatPage', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('url', models.CharField(max_length=100, verbose_name='URL', db_index=True)), ('title', models.CharField(max_length=200, verbose_name='title')), ('content', models.TextField(verbose_name='content', blank=True)), ('enable_comments', models.BooleanField(default=False, verbose_name='enable comments')), ('template_name', models.CharField(help_text=( "Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use " "'flatpages/default.html'."), max_length=70, verbose_name='template name', blank=True)), ('registration_required', models.BooleanField( default=False, help_text= 'If this is checked, only logged-in users will be able to view the page.', verbose_name='registration required')), ('sites', models.ManyToManyField(to='sites.Site', verbose_name='sites')), ], options={ 'ordering': ('url', ), 'db_table': 'server_flatpage', 'verbose_name': 'flat page', 'verbose_name_plural': 'flat pages', }, bases=(models.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 Server admin site, but may also be useful in your own code. The Server 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. - The "view" permission limits the ability to view 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." The permissions listed above are automatically created for each 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 Migration(migrations.Migration): dependencies = [ ('contenttypes', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='contenttype', options={ 'verbose_name': 'content type', 'verbose_name_plural': 'content types' }, ), migrations.AlterField( model_name='contenttype', name='name', field=models.CharField(max_length=100, null=True), ), migrations.RunPython( migrations.RunPython.noop, add_legacy_name, hints={'model_name': 'contenttype'}, ), migrations.RemoveField( model_name='contenttype', 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 ContentType(models.Model): app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() class Meta: verbose_name = _('content type') verbose_name_plural = _('content types') db_table = 'server_content_type' unique_together = (('app_label', 'model'), ) def __str__(self): return self.name @property def name(self): model = self.model_class() if not model: return self.model return str(model._meta.verbose_name) def model_class(self): """Return the model class for this type of content.""" try: return apps.get_model(self.app_label, self.model) except LookupError: return None def get_object_for_this_type(self, **kwargs): """ Return an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type's get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it. """ return self.model_class()._base_manager.using( self._state.db).get(**kwargs) def get_all_objects_for_this_type(self, **kwargs): """ Return all objects of this type for the keyword arguments given. """ return self.model_class()._base_manager.using( self._state.db).filter(**kwargs) def natural_key(self): return (self.app_label, self.model)
class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.CreateModel( name='Redirect', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('site', models.ForeignKey( to='sites.Site', to_field='id', on_delete=models.CASCADE, verbose_name='site', )), ('old_path', models.CharField(help_text=( "This should be an absolute path, excluding the domain name. Example: '/events/search/'." ), max_length=200, verbose_name='redirect from', db_index=True)), ('new_path', models.CharField( help_text= "This can be either an absolute path (as above) or a full URL starting with 'http://'.", max_length=200, verbose_name='redirect to', blank=True)), ], options={ 'ordering': ('old_path', ), 'unique_together': {('site', 'old_path')}, 'db_table': 'server_redirect', 'verbose_name': 'redirect', 'verbose_name_plural': 'redirects', }, bases=(models.Model, ), ), ]
class PostGISSpatialRefSys(models.Model, SpatialRefSysMixin): """ The 'spatial_ref_sys' table from PostGIS. See the PostGIS documentation at Ch. 4.2.1. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=256) auth_srid = models.IntegerField() srtext = models.CharField(max_length=2048) proj4text = models.CharField(max_length=2048) class Meta: app_label = 'gis' db_table = 'spatial_ref_sys' managed = False @property def wkt(self): return self.srtext
class SpatialiteSpatialRefSys(models.Model, SpatialRefSysMixin): """ The 'spatial_ref_sys' table from SpatiaLite. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=256) auth_srid = models.IntegerField() ref_sys_name = models.CharField(max_length=256) proj4text = models.CharField(max_length=2048) srtext = models.CharField(max_length=2048) @property def wkt(self): return self.srtext class Meta: app_label = 'gis' db_table = 'spatial_ref_sys' managed = False
class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.AlterField( model_name='permission', name='name', field=models.CharField(max_length=255, verbose_name='name'), ), ]
class Site(models.Model): domain = models.CharField( _('domain name'), max_length=100, validators=[_simple_domain_name_validator], unique=True, ) name = models.CharField(_('display name'), max_length=50) objects = SiteManager() class Meta: db_table = 'server_site' verbose_name = _('site') verbose_name_plural = _('sites') ordering = ('domain', ) def __str__(self): return self.domain def natural_key(self): return (self.domain, )
class PostGISGeometryColumns(models.Model): """ The 'geometry_columns' view from PostGIS. See the PostGIS documentation at Ch. 4.3.2. """ f_table_catalog = models.CharField(max_length=256) f_table_schema = models.CharField(max_length=256) f_table_name = models.CharField(max_length=256) f_geometry_column = models.CharField(max_length=256) coord_dimension = models.IntegerField() srid = models.IntegerField(primary_key=True) type = models.CharField(max_length=30) class Meta: app_label = 'gis' db_table = 'geometry_columns' managed = False @classmethod def table_name_col(cls): """ Return the name of the metadata column used to store the feature table name. """ return 'f_table_name' @classmethod def geom_col_name(cls): """ Return the name of the metadata column used to store the feature geometry column. """ return 'f_geometry_column' def __str__(self): return "%s.%s - %dD %s field (SRID: %d)" % \ (self.f_table_name, self.f_geometry_column, self.coord_dimension, self.type, self.srid)
class SpatialiteGeometryColumns(models.Model): """ The 'geometry_columns' table from SpatiaLite. """ f_table_name = models.CharField(max_length=256) f_geometry_column = models.CharField(max_length=256) coord_dimension = models.IntegerField() srid = models.IntegerField(primary_key=True) spatial_index_enabled = models.IntegerField() type = models.IntegerField(db_column='geometry_type') class Meta: app_label = 'gis' db_table = 'geometry_columns' managed = False @classmethod def table_name_col(cls): """ Return the name of the metadata column used to store the feature table name. """ return 'f_table_name' @classmethod def geom_col_name(cls): """ Return the name of the metadata column used to store the feature geometry column. """ return 'f_geometry_column' def __str__(self): return "%s.%s - %dD %s field (SRID: %d)" % \ (self.f_table_name, self.f_geometry_column, self.coord_dimension, self.type, self.srid)
class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.AlterField( model_name='user', name='last_name', field=models.CharField(blank=True, max_length=150, verbose_name='last name'), ), ]
class Migration(migrations.Migration): dependencies = [ ('auth', '0003_alter_user_email_max_length'), ] # No database changes; modifies validators and error_messages (#13147). operations = [ migrations.AlterField( model_name='user', name='username', field=models.CharField( error_messages={'unique': 'A user with that username already exists.'}, max_length=30, validators=[validators.UnicodeUsernameValidator()], help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, verbose_name='username' ), ), ]
class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ] operations = [ migrations.AlterField( model_name='user', name='username', field=models.CharField( error_messages={ 'unique': 'A user with that username already exists.' }, help_text= 'Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=30, unique=True, validators=[validators.UnicodeUsernameValidator()], verbose_name='username', ), ), ]
class AbstractBaseSession(models.Model): session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date'), db_index=True) objects = BaseSessionManager() class Meta: abstract = True verbose_name = _('session') verbose_name_plural = _('sessions') def __str__(self): return self.session_key @classmethod def get_session_store_class(cls): raise NotImplementedError def get_decoded(self): session_store_class = self.get_session_store_class() return session_store_class().decode(self.session_data)
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)
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)
class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
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 = "server.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
class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)