class Course(Model): PROXIMITIES = ['DIRECTLY_AFTER', 'SAME_DAY', 'DIFFERENT_DAY'] PROXIMITY_CHOICES = [(PROXIMITIES.index(proximity), proximity) for proximity in PROXIMITIES] prefix = CharField(max_length=4) number = PositiveSmallIntegerField() title = CharField(max_length=60) units = PositiveSmallIntegerField(default=4) wtu = PositiveSmallIntegerField(default=5) requires_equipment = BooleanField(default=False) # Lab Fields has_lab = BooleanField(default=False) lab_requires_equipment = BooleanField(default=False) lab_length = DecimalField(max_digits=3, decimal_places=2, default=0, verbose_name='Lab Length (Hours)') lab_time_proximity = PositiveSmallIntegerField(default=0, choices=PROXIMITY_CHOICES) def __unicode__(self): return self.prefix + " " + unicode(self.number) class Meta: unique_together = ("prefix", "number")
class EmailLog(Model): email_from = EmailField(verbose_name=_('email from')) email_to = TextField(verbose_name=_('email to')) hidden_copy = BooleanField(default=False, choices=BOOLEAN_CHOICES, verbose_name=_('has attachment')) subject = TextField(verbose_name=_('subject')) body = TextField(verbose_name=_('body')) body_html = BooleanField(default=False, choices=BOOLEAN_CHOICES, verbose_name=_('body is html ')) has_attachment = BooleanField(default=False, choices=BOOLEAN_CHOICES, verbose_name=_('has attachment')) register_datetime = DateTimeField(auto_now_add=True, verbose_name=_('register datetime')) sended = BooleanField(default=False, choices=BOOLEAN_CHOICES, verbose_name=_('sended')) sended_datetime = DateTimeField(null=True, blank=True, verbose_name=_('sended datetime')) error_quantity = PositiveIntegerField(default=0, verbose_name=_('error quantity')) exceeded_max_retry = BooleanField(default=False, choices=BOOLEAN_CHOICES, verbose_name=_('exceeded max retry')) def __str__(self): return u'{0}'.format(self.subject) class Meta: ordering = ['register_datetime', 'subject'] verbose_name_plural = _('emails logs') verbose_name = _('email log')
def test_boolean_constraints(self): """Boolean fields have check constraints on their values.""" for field in (BooleanField(), NullBooleanField(), BooleanField(null=True)): with self.subTest(field=field): field.set_attributes_from_name('is_nice') self.assertIn('"IS_NICE" IN (0,1)', field.db_check(connection))
class User(AbstractBaseUser, PermissionsMixin): username = CharField(max_length=25, blank=True, null=True, unique=True, db_index=True) email = EmailField(unique=True, db_index=True) is_superuser = BooleanField(default=False) is_staff = BooleanField(default=False) is_active = BooleanField(default=True) first_name = CharField(max_length=100, blank=True, null=True) last_name = CharField(max_length=100, blank=True, null=True) created = DateTimeField(auto_now_add=True) last_login = DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self) -> str: return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return self.is_superuser def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return self.is_superuser
def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field( Author, new_field, ) # Ensure the field is right afterwards columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns['awesome'][0] self.assertEqual(field_type, connection.features.introspected_boolean_field_type(new_field, created_separately=True))
class Ensemble(models.Model): # old: ensemble SECTION_ASSGT_NULL = 1 SECTION_ASSGT_RAND = 2 SECTION_ASSGT_TYPES = ((SECTION_ASSGT_NULL, "NULL"), (SECTION_ASSGT_RAND, "RANDOM")) name = CharField(max_length=255) # old: name text description = CharField(max_length=255, default="No description available") allow_staffonly = BooleanField( default=True, verbose_name="Allow users to write 'staff-only' comments") allow_anonymous = BooleanField( default=True, verbose_name="Allow users to write anonymous comments") allow_guest = BooleanField( default=False, verbose_name="Allow guests (i.e. non-members) to access the site") invitekey = CharField(max_length=63, blank=True, null=True) # new use_invitekey = BooleanField( default=True, verbose_name= "Allow users who have the 'subscribe link' to register by themselves") allow_download = BooleanField( default=True, verbose_name="Allow users to download the PDFs") section_assignment = IntegerField(choices=SECTION_ASSGT_TYPES, default=SECTION_ASSGT_NULL, null=True) def __unicode__(self): return "%s %s: %s" % (self.__class__.__name__, self.id, self.name) class Meta: ordering = ["id"]
def annotate_is_admin(self, user): """Annotate each project with whether or not the given user is an admin for it """ if user.is_authenticated: return self.annotate( is_admin=Cast( Subquery( user.collaboration_set.filter( project_id=OuterRef("pk"), access=CollaboratorAccess.admin ) .values("pk") .order_by() ), output_field=BooleanField(), ), is_editor=Cast( Subquery( user.collaboration_set.filter( project_id=OuterRef("pk"), access__in=[ CollaboratorAccess.admin, CollaboratorAccess.edit, ], ) .values("pk") .order_by() ), output_field=BooleanField(), ), ) else: return self.annotate(is_admin=Value(False, output_field=BooleanField()))
def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field( Author, new_field, ) # Ensure the field is right afterwards columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type, field_info = columns['awesome'] if connection.vendor == 'mysql': self.assertEqual(field_type, 'IntegerField') self.assertEqual(field_info.precision, 1) elif connection.vendor == 'oracle' and connection.version_has_default_introspection_bug: self.assertEqual(field_type, 'IntegerField') self.assertEqual(field_info.precision, 0) else: self.assertEqual(field_type, 'BooleanField')
class User(AbstractUser): class Meta: verbose_name = '用户' verbose_name_plural = verbose_name first_name = None last_name = None username = FixedCharField( max_length=20, null=False, blank=False, charset='utf8mb4', collade='utf8mb4_general_ci', verbose_name='昵称' ) is_superuser = BooleanField(null=False, default=True) is_staff = BooleanField(null=False, default=False) is_active = BooleanField(null=False, default=True) email = EmailField(unique=True) img = CharField( null=True, max_length=255, blank=False, verbose_name='头像' ) auth = ManyToManyField( to=Auth, db_table='user_auth', db_constraint=False, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] LOGIN_USERNAME_FIELDS = ['email', ] objects = UserManager()
def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field( Author, new_field, ) # Ensure the field is right afterwards columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type, field_info = columns['awesome'] if connection.vendor == 'mysql': self.assertEqual(field_type, 'IntegerField') self.assertEqual(field_info.precision, 1) else: self.assertEqual(field_type, 'BooleanField')
class User(models.Model): email = EmailField(max_length=63, unique=True) firstname = CharField(max_length=63, blank=True, null=True) lastname = CharField(max_length=63, blank=True, null=True) pseudonym = CharField(max_length=63, blank=True, null=True) password = CharField(max_length=63, blank=True, null=True) # old; should be null salt = CharField(max_length=32, blank=False, null=True) # new secure authentication saltedhash = CharField(max_length=128, blank=False, null=True) # new secure authentication confkey = CharField(max_length=63, blank=True, null=True) guest = BooleanField(default=False) valid = BooleanField(default=False) def __unicode__(self): return "%s %s: %s %s <%s>" % (self.__class__.__name__, self.id, self.firstname, self.lastname, self.email) # Returns 'True' if password is correct, 'False' othrewise def authenticate(self, password): user_hash = hashlib.sha512( password.encode('ascii', 'xmlcharrefreplace') + self.salt).hexdigest() return (self.saltedhash == user_hash) # Updates 'salt' and 'saltedhash' to correspond to new password # this method does notcall 'save' def set_password(self, password): self.salt = uuid.uuid4().hex self.saltedhash = hashlib.sha512( password.encode('ascii', 'xmlcharrefreplace') + self.salt).hexdigest() return
class Comment(models.Model): # old: nb2_comment TYPES = ((1, "Private"), (2, "Staff"), (3, "Class"), (4, "Tag Private")) location = ForeignKey(Location) # old: id_location integer parent = ForeignKey('self', null=True) # old: id_parent integer author = ForeignKey(User) # old: id_author integer, ctime = DateTimeField(default=datetime.now, db_index=True) # old: ctime timestamp body = TextField(blank=True, null=True) type = IntegerField(choices=TYPES) signed = BooleanField(default=True) # old: signed integer DEFAULT 0, deleted = BooleanField(default=False) # old: vis_status integer DEFAULT 0 moderated = BooleanField(default=False) def __unicode__(self): return "%s %s: %s " % (self.__class__.__name__, self.id, self.body[:50]) @property def created(self): if (timezone.is_naive(self.ctime)): return str( calendar.timegm(pytz.utc.localize(self.ctime).timetuple())) else: return str( calendar.timegm(self.ctime.astimezone(pytz.utc).timetuple()))
class Comment(models.Model): # old: nb2_comment TYPES = ((1, "Private"), (2, "Staff"), (3, "Class")) location = ForeignKey(Location) # old: id_location integer parent = ForeignKey('self', null=True) # old: id_parent integer author = ForeignKey(User) # old: id_author integer, ctime = DateTimeField(default=datetime.now) # old: ctime timestamp body = TextField(blank=True, null=True) type = IntegerField(choices=TYPES) signed = BooleanField(default=True) # old: signed integer DEFAULT 0, deleted = BooleanField(default=False) # old: vis_status integer DEFAULT 0 moderated = BooleanField(default=False) def __unicode__(self): return "%s %s: %s " % (self.__class__.__name__, self.id, self.body[:50]) @property def created(self): t_d = self.ctime.isocalendar() t_now = datetime.now().isocalendar() if t_d[0] != t_now[0]: #not even this year return self.ctime.strftime("%d %b %Y") if t_d[1] != t_now[1]: #this year but not this week return self.ctime.strftime("%d %b, %I:%M%p") if t_d[2] != t_now[2]: #this week but not today return self.ctime.strftime("%a %I:%M%p") #today: return self.ctime.strftime("%I:%M%p")
def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field( Author, new_field, ) # Ensure the field is right afterwards columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns['awesome'][0] self.assertEqual( field_type, connection.features.introspected_boolean_field_type( new_field, created_separately=True))
class Matching(Model): id_user = ForeignKey(CroomiesUser, on_delete=CASCADE) id_seeker = ForeignKey(Seeker, on_delete=CASCADE) skip = BooleanField(default=False) like = BooleanField(default=False) def __str__(self): return "%s %s" % (self.id_matcher, self.id_seeker)
class Plan(Model): plan_name = CharField(max_length=100) acces_original = BooleanField(default=False) expiration_links = BooleanField(default=False) def __str__(self): return f"{self.plan_name}"
class User(models.Model): # old: users email = EmailField(max_length=63, unique=True) firstname = CharField(max_length=63, blank=True, null=True) # new lastname = CharField(max_length=63, blank=True, null=True) # new pseudonym = CharField(max_length=63, blank=True, null=True) # new password = CharField(max_length=63, blank=True, null=True) confkey = CharField(max_length=63, blank=True, null=True) guest = BooleanField(default=False) # new valid = BooleanField(default=False) # new
class Notification(AuditedModel): """ Rules for notifications """ type = ForeignKey('rules.Type', related_name='notifications', blank=True, null=True, verbose_name='on a', db_constraint=False, on_delete=models.PROTECT) status = ForeignKey('rules.Status', related_name='notifications', verbose_name='When', db_constraint=False, on_delete=models.PROTECT) target = ForeignKey('rules.Type', related_name='notification_targets', blank=True, null=True, verbose_name='tell', db_constraint=False, on_delete=models.PROTECT) todo = BooleanField(default=False, verbose_name="Is Todo") silent = BooleanField(default=False, verbose_name="Is silent") discards = ForeignKey('self', related_name='discarding', verbose_name='Discards ...', blank=True, null=True, db_constraint=False, on_delete=models.PROTECT) # condition = ForeignKey('rules.Condition', blank=True, null=True, related_name='notifications', help_text='Condition to be true to notify by email', on_delete=models.PROTECT) # for_target = CharField(max_length=4096, verbose_name='Notification', default='You did STATUS on ITEM', blank=True, null=True) webhook = ForeignKey('webhooks.Webhook', related_name='notifications', blank=True, null=True, verbose_name='Webhook', db_constraint=False, on_delete=models.PROTECT) title = CharField(max_length=156, verbose_name='Webhook title', default='', blank=True) message = TextField(verbose_name='Webhook message', blank=True, null=True) # for_others = CharField(max_length=4096, verbose_name='Event observed', default='ACTOR did STATUS on ITEM', blank=True, null=True) # for_actor = CharField(max_length=4096, verbose_name='Event actor - deprecated', default='You did STATUS on ITEM', blank=True, null=True) class Meta: ordering = ['type', 'status', 'target'] def __str__(self): return str(self.type)+'/'+str(self.status)+'>'+str(self.target) def get_parsed_message(self, event, actor=None): #return parse_message(self.for_others, event) if not actor: actor = request_switch.akey #if event.akey == actor: # message = parse_message(self.for_actor, event) if event.target == actor: message = parse_message(self.for_target, event) else: message = parse_message(self.for_others, event) return message
class Ownership(models.Model): # old: ownership source = ForeignKey(Source) # old: id_source integer ensemble = ForeignKey(Ensemble) # old: id_ensemble integer folder = ForeignKey(Folder, null=True) # old: id_folder integer published = DateTimeField(default=datetime.now) # old: published timestamp without time zone DEFAULT now() deleted = BooleanField(default=False) assignment = BooleanField(default=False) due = DateTimeField(default=datetime.now(), null=True) def __unicode__(self): return "%s %s: source %s in ensemble %s" % (self.__class__.__name__,self.id, self.source_id, self.ensemble_id)
class Ownership(models.Model): # old: ownership source = ForeignKey(Source) # old: id_source integer ensemble = ForeignKey(Ensemble) # old: id_ensemble integer folder = ForeignKey(Folder, null=True) # old: id_folder integer published = DateTimeField( default=datetime.now ) # old: published timestamp without time zone DEFAULT now() deleted = BooleanField(default=False) assignment = BooleanField(default=False) due = DateTimeField(default=datetime.now(), null=True)
class Membership(models.Model): # old: membership user = ForeignKey(User) # old: id_user ensemble = ForeignKey(Ensemble) # old: id_ensemble section = ForeignKey(Section, null=True) admin = BooleanField(default=False) # old: admin integer deleted = BooleanField(default=False) guest = BooleanField(default=False) # Adding guest membership to remember section_id. #FIXME Note: To preserve compatibility w/ previous production DB, I also added a default=false at the SQL level for the 'guest' field , so that we don't create null records if using the old framework def __unicode__(self): return "%s %s: (user %s, ensemble %s)" % (self.__class__.__name__,self.id, self.user_id, self.ensemble_id)
class User(models.Model): # old: users email = EmailField(max_length=63, unique=True) firstname = CharField(max_length=63, blank=True, null=True) # new lastname = CharField(max_length=63, blank=True, null=True) # new pseudonym = CharField(max_length=63, blank=True, null=True) # new password = CharField(max_length=63, blank=True, null=True) confkey = CharField(max_length=63, blank=True, null=True) guest = BooleanField(default=False) # new valid = BooleanField(default=False) # new def __unicode__(self): return "%s %s: %s %s <%s>" % (self.__class__.__name__,self.id, self.firstname, self.lastname, self.email)
def completed_by_values(self, user, *, order_by): qs = self.order_by(order_by) qs1 = qs.completed_by(user).annotate(completed=Value(True, BooleanField())) qs2 = qs.not_completed_by(user).annotate(completed=Value(False, BooleanField())) reverse = order_by.startswith('-') order_by = order_by.lstrip('-') def keyfunc(task): return getattr(task, order_by) return sorted(itertools.chain(qs1, qs2), key=keyfunc, reverse=reverse)
def get_queryset(self): """Union in state options with include local set to True""" queryset = super().get_queryset() queryset = (queryset.annotate( include_local=Value(False, output_field=BooleanField())).union( queryset.filter(level="s").annotate(include_local=Value( True, output_field=BooleanField()))).order_by( "-level", "name")) return queryset
class Notify(models.Model): title = CharField(max_length=1000, blank=True, default="") subtitle = CharField(max_length=1000, blank=True, default="") info = TextField(blank=True, default="") showDate = DateTimeField() vibrate = BooleanField(default=True) song = BooleanField(default=False) def __unicode__(self): return self.title + " - " + self.subtitle
class Message(models.Model): ensemble = ForeignKey(Ensemble) author = CharField(max_length=255, default="The NB Team<*****@*****.**>") title = CharField(max_length=512, default="untitled") body = TextField() ctime = DateTimeField(default=datetime.now) students = BooleanField(default=False) admins = BooleanField(default=False) sent = DateTimeField(default=None, null=True, blank=True) draft = BooleanField(default=False) def __unicode__(self): return "To %s on %s" % (self.ensemble.name, self.ctime)
class LiveEmbedEvent(Model): """ This is an event not inherited from BaseEvent because it doesn't need some required attributes, in the future this app can be refactored and we can change BaseEvent to a more minimal version. This events will be used for the metadata needed to display a live event embeded in a page of our site. """ active = BooleanField(u'activo', default=False) access_type = CharField(u'acceso al evento', max_length=1, choices=LIVE_EMBED_EVENT_ACCESS_TYPES, default='s') in_home = BooleanField(u'agregar a portada', default=False) notification = BooleanField(u'mostrar notificación en artículos', default=False) notification_text = CharField(u'texto', max_length=255, null=True, blank=True) notification_url = URLField(u'url', null=True, blank=True) title = CharField(u'título', max_length=255) embed_content = TextField(u'contenido incrustado', blank=True, null=True) embed_chat = TextField(u'chat incrustado', blank=True, null=True) def is_free(self): return self.access_type == u'f' def clean(self): from django.core.exceptions import ValidationError active_now = LiveEmbedEvent.objects.filter(active=True) if self.active: if (active_now.exclude(id=self.id) if self.id else active_now): # Don't allow more than one active instance raise ValidationError( u'Only one event can be active at the same time.') if not self.embed_content: raise ValidationError( u'Embed content should be set if the event is active.') def save(self, *args, **kwargs): self.full_clean() # calls self.clean() as well cleans other fields return super(LiveEmbedEvent, self).save(*args, **kwargs) def __unicode__(self): return self.title class Meta: verbose_name = u'evento en vivo' verbose_name_plural = u'eventos en vivo'
class Project(models.Model): """ Object representing a project """ # The unique camelCase project name name = CharField(unique=True, max_length=255) # The project title to display title = CharField(max_length=255) subtitle = CharField(max_length=255) # Whether or not the project is still actively developed active = BooleanField() # The project description that is always visible shortDescription = CharField(max_length=4096) # The project description that is shown/hidden through the javascript link longDescription = CharField(max_length=4096) # The link to the source code location sourceUrl = URLField() # The link to the live URL liveUrl = URLField()
class Article(models.Model): """ Represents an article table """ name = CharField(max_length=200) # String representation of the article's XML file. text = TextField() # List of unique people cited in the article people = JSONField() # Article text surrounded by a list of tokens tokens = JSONField() # List of all sentence indices that are the ends of paragraphs paragraphs = JSONField() # List of all token indices that are the ends of sentences sentences = JSONField() # List of boolean values {0, 1} representing if a sentence is fully labeled or labeled = JSONField() # List of boolean values {0, 1} representing if a token is in between quotes or not in_quotes = JSONField() # List of values, where value j is in (0, 1) representing the confidence of the current ML models predictions in # deciding if sentence j is a quote or not. 1 means absolute confidence, while 0 means completely unsure. confidence = JSONField() # If this article can only be seen by admins admin_article = BooleanField() # The newspaper in which the article was published source = CharField(max_length=200) # Date of instance creation created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Article id: {self.id}'
def get_field(self): from django.db.models.fields import IntegerField, DecimalField, BooleanField, TextField from django.core.validators import MaxValueValidator, MinValueValidator args = self.get_args() if self.kind == 0: dbfield = TextField(self.name) if self.kind == 1: dbfield = IntegerField(self.name, validators=[ MinValueValidator(float(args['min'])), MaxValueValidator(float(args['max'])) ]) if self.kind == 2: dbfield = DecimalField(self.name, decimal_places=int(args['prec']), validators=[ MinValueValidator(float(args['min'])), MaxValueValidator(float(args['max'])) ]) if self.kind == 3: dbfield = BooleanField(self.name) if self.kind == 4: choices = [] for item in args['list']: choices.append((len(choices), item)) dbfield = IntegerField(self.name, choices=tuple(choices)) return dbfield
class Assignment(MPTTModel, TimeStampedModel): parent = TreeForeignKey("self", blank=True, null=True, related_name="children") worksheet = ForeignKey(Worksheet, related_name="assignments") unit = ForeignKey("Unit", related_name="assignments") start = DateTimeField(blank=True, null=True) end = DateTimeField(blank=True, null=True) hide_until_start = BooleanField(default=False) users = ManyToManyField(User, related_name="assignments", through="Engagement") objects = tree = TreeManager() def __unicode__(self): name = "%s assigned for %s %s" % (self.worksheet, self.unit.type, self.unit) if self.start: name += " starting %s" % (self.start) if self.end: name += " until %s" % (self.end) return name
class UserDetails(Model): user = OneToOneField( to=User, on_delete=CASCADE, # 级联删除 db_constraint=False, # False表示逻辑外键 db_column='id', primary_key=True, related_name='details', # 默认类名全小写 ) motto = CharField( max_length=255, verbose_name='个性签名', default=None, blank=True, null=True ) favorite_color = FixedCharField( max_length=6, null=True, blank=True, default=None, charset='ascii', verbose_name='页面颜色' ) gender = BooleanField( null=True, blank=True, default=None, verbose_name='性别', choices=((True, '女'), (False, '男'), (None, '未指定')) ) class Meta: verbose_name = "用户资料" verbose_name_plural = "用户资料"