class Payment(models.Model): STATE_CREATED = 'created' STATE_OPENED = 'opened' STATE_BANK = 'bank' STATE_SUCCESS = 'successful' STATE_FAILURE = 'unsuccessful' STATE_CHOICES = ((STATE_CREATED, 'Created'), (STATE_OPENED, 'Opened'), (STATE_BANK, 'Sent to bank'), (STATE_SUCCESS, 'Successful payment'), (STATE_FAILURE, 'Unsuccessful payment')) price = models.PositiveIntegerField() token = models.CharField(max_length=500, unique=True, null=True, blank=True) slug = RandomCharField(length=8, unique=True) trace_number = RandomCharField(length=8, unique=True, include_alpha=False) state = models.CharField(max_length=30, choices=STATE_CHOICES, default=STATE_CREATED) payment_result = models.CharField(max_length=256, null=True, blank=True) verification_result = models.CharField(max_length=256, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) gateway = models.CharField(max_length=256, null=True) description = models.CharField(max_length=1024, null=True) login_required = models.BooleanField(default=False) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) ref_number = models.CharField(max_length=200, null=True, unique=True) # Returning user to your website callable_module = models.CharField(max_length=300, null=True) callable_name = models.CharField(max_length=100, null=True) return_url = models.CharField(max_length=1024, null=True) def verification_done(self): return self.state in [self.STATE_SUCCESS, self.STATE_FAILURE] def successful(self): return self.state == self.STATE_SUCCESS class Meta: app_label = 'pardakht'
class NoteBook(TimeStampedModel): ''' subclass of time stamped model, includes a created and modified field ''' # fields # uses randomchar from extensions to generate unique chars id = RandomCharField(length=12, unique=True, primary_key=True) name = models.CharField( max_length=70, blank=False, ) created_by = models.ForeignKey(UserModel, blank=True, null=False, on_delete=models.CASCADE, related_name='created_notebooks') # custom Manager objects = NoteBookManager() def __str__(self): return f'notebook: {self.name}' @property def get_absolute_url(self): """Returns the url to access a particular instance of the model.""" return reverse('notebook_detail', args=[str(self.id)]) def note_urls(self): return [note.get_absolute_url for note in self.notebook_notes.all()] def note_list(self): return [note.title for note in self.notebook_notes.all()] def notes_query(self): return self.notebook_notes.all()
class CSVFile(models.Model): uuid = RandomCharField(length=12) file = models.FileField(upload_to="csv_files/") created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.uuid
class ChatInbox(models.Model): pin_code = RandomCharField(length=4, unique=True, include_alpha=False) owner = models.ForeignKey(User) creation_time = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u"new ChatInbox was created for %s at %s with pin %s" % (self.owner, self.creation_time, self.pin_code)
class AmMatches(gameModels.SoftDeletionModel): team_one = models.ForeignKey(gameModels.AmTeam, models.DO_NOTHING, blank=True, null=True, related_name="first_team") team_two = models.ForeignKey(gameModels.AmTeam, models.DO_NOTHING, blank=True, null=True, related_name="second_team") slug = RandomCharField(length=6, include_digits=False, unique=True) match_own = models.ForeignKey(gameModels.AmTeam, models.DO_NOTHING, blank=True, null=True, related_name="match_winner") created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: app_label = 'matches' db_table = 'am_matches' verbose_name = "Matches" verbose_name_plural = "Matches" def __str__(self): return self.match_own.name
class Text(models.Model): site = models.ForeignKey(Site, default=1, editable=False, on_delete=models.CASCADE) objects = TypeManager() type = models.ForeignKey(Type, on_delete=models.CASCADE) title = models.CharField(_("title"), max_length=200) slug = RandomCharField(_("slug"), length=8, unique=True) intro = RichTextField(_("intro"), max_length=20000, blank=True) body = RichTextField(_("text"), max_length=20000) version = models.PositiveIntegerField(_("version"), default=0) pub_date = models.DateTimeField(_("date published"), auto_now_add=True) end_date = models.DateTimeField(_("date end"), blank=True, null=True) comments = GenericRelation(TextComment, object_id_field="object_pk") class Meta: verbose_name = _("text") verbose_name_plural = _("texts") def __str__(self): return "{}: {} ({})".format(self.type, self.title, self.slug) def get_absolute_url(self): return "/bettertexts/%s/" % self.slug def active(self): return self.end_date is None or timezone.now() <= self.end_date
class ActivityLog(PRMModel): """ An activity log is a moment in which you performed the activity, you can then add specific info of what you did and with who you did it. For example an activity could be biking an a log would be a day you went biking. """ code = RandomCharField(length=8, blank=False, null=False, unique=True) activity = models.ForeignKey('relations.Activity', on_delete=models.SET_NULL, null=True) owner = models.ForeignKey('users.User', on_delete=models.CASCADE) companions = models.ManyToManyField( 'relations.Contact', help_text='Contacts with who you did the activity') details = models.TextField() date = models.DateField() location = models.CharField(max_length=100, blank=True) def __str__(self): return f'{self.activity.name} on {self.date} by {self.owner}' class Meta: ordering = ['-date', '-created']
class Note(TimeStampedModel): ''' subclass of time stamped model, includes a created and modified field authstamped created_by is subbed out ''' # fields # uses randomchar from extensions to generate unique chars id = RandomCharField(length=12, unique=True, primary_key=True) title = models.CharField(max_length=50, blank=True, default=title_default) content = SummernoteTextField(blank=True) notebook = models.ManyToManyField('notebooks.NoteBook', related_name='notebook_notes', blank=True) created_by = models.ForeignKey(UserModel, on_delete=models.CASCADE, null=False, blank=True, related_name='created_notes') # custom Manager objects = NoteManager() def __str__(self): return f'note title: {self.title}' @property def get_absolute_url(self): """Returns the url to access a particular instance of the model.""" return reverse('note_detail', args=[str(self.id)])
class Invitation(TimeStampedModel): organization = ForeignKey(Organization, CASCADE, related_name='invitations') code = RandomCharField(length=8, unique=True) is_accepted = BooleanField(default=False) external_id = CharField(max_length=20, blank=True, verbose_name='External ID') email_address = EmailField() def __str__(self): return f'{self.email_address}' def save(self, **kwargs): # TODO Actually send notification email super().save(**kwargs) @classmethod def redeem(cls, user): invitations = cls.objects.filter(email_address=user.email, is_accepted=True) for inv in invitations: Membership.objects.create( user=user, organization=inv.organization, external_id=inv.external_id, status='active') invitations.delete() def invite_link(self): if self.code and self.organization.site: path = reverse('accept_invite', args=[self.code]) url = f'{self.organization.site.domain}{path}' return format_html(f'<a href="{url}">{url}</a>')
class RandomCharTestModelUniqueTogether(models.Model): random_char_field = RandomCharField(length=8) common_field = models.CharField(max_length=10) class Meta: app_label = 'django_extensions' unique_together = ('random_char_field', 'common_field')
class Lesson(models.Model): id = RandomCharField(unique=True, include_alpha=False, length=12, primary_key=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) title = models.CharField(max_length=100) body = models.URLField(help_text="Link to pdf content") video_link = models.URLField(help_text="Youtube link to the lesson") lesson_number = models.IntegerField( help_text="Serial number of Lesson in course, must be unique.") def linked_intro_video(self): return format_html('<a href="{}" target="_blank ">{}</a>', self.video_link, self.video_link) def linked_body_pdf(self): return format_html('<a href="{}" target="_blank ">{}</a>', self.body, self.body) def clean(self): if Lesson.objects.filter(course=self.course, lesson_number=self.lesson_number).count() > 0: raise ValidationError( "Lesson number already exists for this course.") def __str__(self): return "Lesson: {0}".format(self.title)
class User(AbstractUser): user_id = RandomCharField(length=8, unique=True) # Override the inherited user fields username = None email = models.EmailField( 'email address', unique=True, error_messages={ 'unique': "This email address has already been registered.", }) # Additional fields nickname = models.CharField( max_length=50, unique=True, error_messages={ 'unique': "This display name has already been registered.", }) avatar_image = models.ImageField(default='default/logo_transparent.png') avatar_image_thumbnail = models.ImageField( default='default/logo_transparent.png') biography = models.TextField(max_length=500, default='') USERNAME_FIELD = 'email' # email is already required as username_field REQUIRED_FIELDS = ['nickname'] # Assign the custom UserManager objects = UserManager()
class Activity(PRMModel): """ Activity or obligation an user has, could be a hobby, responsability, club membership, or any other that the user belongs to. """ owner = models.ForeignKey('users.User', on_delete=models.CASCADE) code = RandomCharField(length=8, blank=False, null=False, unique=True) name = models.CharField(max_length=50) description = models.TextField() is_active = models.BooleanField( "Is active", default=True, help_text="Are you currently actively doing it?") last_time = models.DateField('Last time done', blank=True, null=True) partners = models.ManyToManyField('relations.Contact') def __str__(self): return f'{self.name} by {self.owner}'
class AmTeam(SoftDeletionModel): name = models.CharField(max_length=255) logo = models.ImageField(upload_to='teams/', blank=True, null=True) slug = RandomCharField(length=6, include_digits=False, unique=True) country = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: app_label = 'game' db_table = 'am_team' verbose_name = "Team" verbose_name_plural = "Team" def __str__(self): return self.name def image_tag(self): try: return format_html( '<img src="{0}" style="max-width:200px;"/>'.format( self.logo.url)) except requests.exceptions.HTTPError as err: return None except ValueError as err: return None image_tag.short_description = 'Image' image_tag.allow_tags = True
class RandomCharTestModelUppercase(models.Model): random_char_field = RandomCharField(length=8, uppercase=True, include_digits=False) class Meta: app_label = 'django_extensions'
class RandomCharTestModelPunctuation(models.Model): random_char_field = RandomCharField( length=8, include_punctuation=True, include_digits=False, include_alpha=False, ) class Meta: app_label = 'django_extensions'
class Deposit(TimeStampedModel, SoftDeletableModel): wallet = models.ForeignKey(Wallet, on_delete=models.PROTECT) amount = models.DecimalField(decimal_places=8, max_digits=21) status = models.CharField(max_length=20, choices=DEPOSIT_WITHDRAWAL_STATUS_CHOICES, default='pending') invoice_number = RandomCharField(length=20, unique=True, blank=True, null=True)
class Kid(models.Model): id = RandomCharField(unique=True, include_alpha=False, length=12, primary_key=True) name = models.CharField(max_length=200, help_text="Full name of kid") parent = models.ForeignKey(Parent, on_delete=models.CASCADE) school = models.ForeignKey(School, on_delete=models.CASCADE, null=True) def __str__(self): return "Kid: {0}".format(self.name)
class Group(models.Model): group_name = models.CharField(max_length=500, verbose_name='խմբի անվանումը') group_slug = RandomCharField(length=8) def __str__(self): return self.group_name class Meta: managed = True verbose_name = 'խումբ' verbose_name_plural = 'խմբեր'
class User(TimeStampedModel, AbstractUser): ''' Base user model, Extends django base abstract user and a timestamped model (created, modified), id and pk is randomcharfield, 10 keys ''' id = RandomCharField(length=10, unique=True, primary_key=True) username = models.CharField( max_length=30, blank=False, null=False, unique=True, )
class CourseOwner(models.Model): id = RandomCharField(unique=True, include_alpha=False, length=12, primary_key=True) name = models.CharField(max_length=200) email = models.EmailField(unique=True) password = models.CharField(max_length=200, editable=False) mobile = models.CharField(max_length=15) def __str__(self): return "CourseOwner: {0}".format(self.name)
class AmPlayer(SoftDeletionModel): team = models.ForeignKey(AmTeam, models.DO_NOTHING, blank=True, null=True, related_name="player") first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) logo = models.ImageField(upload_to='players/', blank=True, null=True) slug = RandomCharField(length=6, include_digits=False, unique=True) jersey_number = models.IntegerField(blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) no_of_matches = models.IntegerField(blank=True, null=True) runs = models.IntegerField(blank=True, null=True) hieghest_score = models.IntegerField(blank=True, null=True) fifties = models.IntegerField(blank=True, null=True) hundreds = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: app_label = 'game' db_table = 'am_player' verbose_name = "Player" verbose_name_plural = "Player" def __str__(self): return "{} - {} ({})".format(self.first_name, self.last_name, self.team.name) def image_tag(self): try: return format_html( '<img src="{0}" style="max-width:200px;"/>'.format( self.logo.url)) except requests.exceptions.HTTPError as err: return None except ValueError as err: return None image_tag.short_description = 'Image' image_tag.allow_tags = True def image_src(self): if self.logo: x = self.logo.url.split('?')[0] return x else: return ''
class Parent(models.Model): id = RandomCharField(unique=True, include_alpha=False, length=12, primary_key=True) email = models.EmailField(unique=True) password = models.CharField(max_length=200, editable=False) first_name = models.CharField(max_length=200) surname = models.CharField(max_length=200) mobile = models.CharField(max_length=15) def __str__(self): return "Parent: {0} {1}".format(self.first_name, self.surname)
class QuizAnswerBase(CreationTrackingBaseModel): class Meta: abstract = True objects = IterativeDeletion_Manager() ref_id = RandomCharField( primary_key=True, unique=True, length=8, include_punctuation=False, ) position = models.PositiveIntegerField(default=0, blank=False, null=False)
class Withdrawal(TimeStampedModel, SoftDeletableModel): wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE) amount = models.DecimalField(decimal_places=8, max_digits=21) status = models.CharField(max_length=20, choices=DEPOSIT_WITHDRAWAL_STATUS_CHOICES, default='pending') invoice_number = RandomCharField(length=20, unique=True, blank=True, null=True) accepted_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.PROTECT)
class Comment(models.Model): id = RandomCharField(primary_key=True, editable=False, length=15, unique=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments', null=True, blank=True) parent = models.ForeignKey("self", on_delete=models.CASCADE, related_name='replies', null=True, blank=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='comments', ) content = models.TextField(default='') likes = GenericRelation(Like, related_query_name='comments') flags = GenericRelation(Flag, related_query_name='comments') created = CreationDateTimeField(verbose_name='Creation Time') class Meta: db_table = 'comments' ordering = ['-created'] verbose_name = 'Comment' verbose_name_plural = 'Comments' def __str__(self): return f'Comment #{self.id}' @property def post_name(self): """Get the name of the post its attached to """ if self.post is not None: return self.post.title return self.parent.post_name @property def number_of_likes(self): return self.likes.count() @property def number_of_flags(self): return self.flags.count() @property def is_flagged(self): return self.flags.count() > 0
class Teacher(models.Model): id = RandomCharField(unique=True, include_alpha=False, length=12, primary_key=True) school = models.ForeignKey(School, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=200) surname = models.CharField(max_length=200) email = models.EmailField(unique=True) password = models.CharField(max_length=200) mobile = models.CharField(max_length=15) def __str__(self): return "Teacher: {0} {1}".format(self.first_name, self.surname)
class Blog(models.Model): title = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') slug = RandomCharField(length=32, blank=True, null=True) category = models.CharField(max_length=32, default='') created = models.DateTimeField(auto_now=True, ) content = RichTextField(verbose_name='內容', null=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs)
class Contact(Entity): """Represents a contact of an user and holds all the personal information related to them.""" owner = models.ForeignKey('users.User', on_delete=models.CASCADE, help_text='User this contact belongs') code = RandomCharField(length=8, blank=False, null=False, unique=True) first_name = models.CharField('First name', max_length=40) middle_name = models.CharField(max_length=20, blank=True) last_name = models.CharField(max_length=40) email = models.EmailField(blank=True) nickname = models.CharField( max_length=40, blank=True, help_text="Nickname for what they're commonly known, if they have") phone_regex = RegexValidator( regex=r'\+?1?\d{9,15}$', message=('Phone number must be entered in the format: +999999999. Up ' 'to 15 digits allowed.')) phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) met = models.TextField('How you met', blank=True, help_text=('Describe how you met the contact, like' 'at tahe park or at a party')) food_preferences = models.TextField( 'Food preferences', blank=True, help_text='Food preferences, quirks or allergies of the contact') pets = models.TextField( "Pets", blank=True, help_text='Pets information, as their name, breed, etc..') def __str__(self): return f'{self.first_name} {self.last_name} of {self.owner}'
class Requerimento(models.Model): solicitante = models.CharField(max_length=200) matricula = models.CharField(max_length=100) tipo = models.ForeignKey(TipoRequerimento, on_delete=models.SET_NULL, null=True) email = models.EmailField() datetime_criacao = models.DateTimeField("Data de Criação", auto_now_add=True) datetime_edicao = models.DateTimeField("Data de Edição", auto_now=True) curso = models.ForeignKey(Curso, on_delete=models.SET_NULL, null=True) solicitacao = models.CharField(max_length=2000) deletado = models.BooleanField("Deletado", default=False) protocolo = RandomCharField(length=8, unique=True) def __str__(self): return self.tipo.nome + ' solicitado por ' + self.solicitante + ' de ' + self.curso.nome