Exemple #1
0
 def test_alter_null_to_not_null(self):
     """
     #23609 - Tests handling of default values when altering from NULL to NOT NULL.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Author)
     # Ensure the field is right to begin with
     columns = self.column_classes(Author)
     self.assertTrue(columns['height'][1][6])
     # Create some test data
     Author.objects.create(name='Not null author', height=12)
     Author.objects.create(name='Null author')
     # Verify null value
     self.assertEqual(Author.objects.get(name='Not null author').height, 12)
     self.assertIsNone(Author.objects.get(name='Null author').height)
     # Alter the height field to NOT NULL with default
     new_field = PositiveIntegerField(default=42)
     new_field.set_attributes_from_name("height")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Author,
             Author._meta.get_field_by_name("height")[0],
             new_field
         )
     # Ensure the field is right afterwards
     columns = self.column_classes(Author)
     self.assertFalse(columns['height'][1][6])
     # Verify default value
     self.assertEqual(Author.objects.get(name='Not null author').height, 12)
     self.assertEqual(Author.objects.get(name='Null author').height, 42)
Exemple #2
0
class Listing(QuicksellModel):
	"""Listing model."""

	class Status(IntegerChoices):
		"""Listing's poissble states."""

		draft = 0, 'Draft'
		active = 1, 'Active'
		sold = 2, 'Sold'
		closed = 3, 'Closed'
		deleted = 4, 'Deleted'

	uuid = UUIDField(default=uuid.uuid4, unique=True, editable=False)
	title = CharField(max_length=200)
	description = TextField(null=True, blank=True)
	price = PositiveIntegerField()
	category = ForeignKey('Category', on_delete=SET(uncategorized))
	status = PositiveSmallIntegerField(choices=Status.choices, default=0)
	quantity = PositiveIntegerField(default=1)
	sold = PositiveIntegerField(default=0)
	views = PositiveIntegerField(default=0)
	date_created = DateTimeField(default=datetime.now, editable=False)
	date_expires = DateTimeField(default=default_expiration_date)
	condition_new = BooleanField(default=False)
	properties = JSONField(null=True, blank=True)
	seller = ForeignKey('Profile', related_name='listings', on_delete=CASCADE)
	location = ForeignKey(**location_fk_kwargs)

	def __str__(self):
		return self.title
Exemple #3
0
class QuestionGroup_Setting(models.Model):
    ca_thi = ForeignKey(CaThi, verbose_name="Ca thi")
    
    question_group = ForeignKey(QuestionGroup, 
                                verbose_name="Nhóm câu hỏi")
    
    question_type = CharField(max_length=5,
                            choices=QUESTION_TYPES,
                            default=MCQUESTION,
                            verbose_name="Loại câu hỏi")
    
    mark_per_question = PositiveIntegerField(verbose_name="Điểm cho mỗi câu hỏi", 
                                             default=1) 
    num_of_questions = PositiveIntegerField(verbose_name="số câu hỏi",
                                            default=1)
    
    class Meta:
        verbose_name = "Cấu hình ca thi"
        verbose_name_plural = "Cấu hình ca thi"
#         managed=False
        
    def __unicode__(self):
        return u'%s:%s:%s' %(self.question_group.name,
                             self.num_of_questions,
                             self.mark_per_question)
Exemple #4
0
 def test_alter_null_to_not_null(self):
     """
     #23609 - Tests handling of default values when altering from NULL to NOT NULL.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Author)
     # Ensure the field is right to begin with
     columns = self.column_classes(Author)
     self.assertTrue(columns['height'][1][6])
     # Create some test data
     Author.objects.create(name='Not null author', height=12)
     Author.objects.create(name='Null author')
     # Verify null value
     self.assertEqual(Author.objects.get(name='Not null author').height, 12)
     self.assertIsNone(Author.objects.get(name='Null author').height)
     # Alter the height field to NOT NULL with default
     new_field = PositiveIntegerField(default=42)
     new_field.set_attributes_from_name("height")
     with connection.schema_editor() as editor:
         editor.alter_field(Author,
                            Author._meta.get_field_by_name("height")[0],
                            new_field)
     # Ensure the field is right afterwards
     columns = self.column_classes(Author)
     self.assertFalse(columns['height'][1][6])
     # Verify default value
     self.assertEqual(Author.objects.get(name='Not null author').height, 12)
     self.assertEqual(Author.objects.get(name='Null author').height, 42)
Exemple #5
0
class Course(models.Model):
    code = models.CharField(max_length=10,
                            null=False,
                            unique=True,
                            blank=False)
    name = models.CharField(max_length=100,
                            null=False,
                            unique=True,
                            blank=False)
    credit = models.PositiveIntegerField(default=0, null=False, blank=False)
    lecture_hours = PositiveIntegerField(null=True, )
    tutorial_hours = PositiveIntegerField(null=True)
    pratical_hours = PositiveIntegerField(null=True)
    discussion_hours = PositiveIntegerField(null=True)
    project_hours = PositiveIntegerField(null=True)
    pre_requisits = models.TextField(null=True)
    syllabus = models.TextField()
    evaluation_schema = models.TextField()
    ref_books = models.TextField()

    class Meta:
        unique_together = (
            'code',
            'name',
        )

    def __str__(self):
        return str(self.code + " - " + self.name)

    @property
    def courseslots(self):
        return CourseSlot.objects.filter(courses=self.id)

    def get_courseslots_objects(self):
        return CourseSlot.objects.filter(courses=self.id)
Exemple #6
0
class Course(models.Model):
    code = models.CharField(max_length=10,
                            null=False,
                            unique=True,
                            blank=False)
    name = models.CharField(max_length=100,
                            null=False,
                            unique=True,
                            blank=False)
    credit = models.PositiveIntegerField(default=0, null=False, blank=False)
    lecture_hours = PositiveIntegerField(null=True, )
    tutorial_hours = PositiveIntegerField(null=True)
    pratical_hours = PositiveIntegerField(null=True)
    discussion_hours = PositiveIntegerField(null=True)
    project_hours = PositiveIntegerField(null=True)
    pre_requisits = models.TextField(null=True, blank=True)
    pre_requisit_courses = models.ManyToManyField('self', blank=True)
    syllabus = models.TextField()
    percent_quiz_1 = models.PositiveIntegerField(default=10,
                                                 null=False,
                                                 blank=False)
    percent_midsem = models.PositiveIntegerField(default=20,
                                                 null=False,
                                                 blank=False)
    percent_quiz_2 = models.PositiveIntegerField(default=10,
                                                 null=False,
                                                 blank=False)
    percent_endsem = models.PositiveIntegerField(default=30,
                                                 null=False,
                                                 blank=False)
    percent_project = models.PositiveIntegerField(default=15,
                                                  null=False,
                                                  blank=False)
    percent_lab_evaluation = models.PositiveIntegerField(default=10,
                                                         null=False,
                                                         blank=False)
    percent_course_attendance = models.PositiveIntegerField(default=5,
                                                            null=False,
                                                            blank=False)
    ref_books = models.TextField()
    working_course = models.BooleanField(default=True)
    disciplines = models.ManyToManyField(Discipline, blank=True)

    class Meta:
        unique_together = (
            'code',
            'name',
        )

    def __str__(self):
        return str(self.code + " - " + self.name)

    @property
    def courseslots(self):
        return CourseSlot.objects.filter(courses=self.id)
Exemple #7
0
class Especialidad(models.Model):
    codigo = PositiveIntegerField()
    nombre = models.CharField(max_length=50)
    cantidad_A = PositiveIntegerField('cantidad de Años')
    tipo = PositiveSmallIntegerField()

    class Meta:
        verbose_name = "Especialidad"
        verbose_name_plural = "Especialidades"

    def __unicode__(self):
        return self.nombre
class Part(Model):
    """A part for a particular printer."""

    type = CharField(max_length=25, verbose_name='Type of Part')
    printer = ForeignKey(PrinterType, verbose_name='Associated Printer')
    quantity = PositiveIntegerField(default=0)
    ordered = PositiveIntegerField(default=0)

    def __str__(self):
        return str(self.type)

    class Meta:
        unique_together = ['type', 'printer']
        verbose_name = 'Printer Part'
class Toner(Model):
    """A toner cartrige for a particular printer."""

    color = CharField(max_length=10)
    printer = ForeignKey(PrinterType, verbose_name='Associated Printer')
    quantity = PositiveIntegerField(default=0)
    ordered = PositiveIntegerField(default=0)

    def __str__(self):
        return str(self.color)

    class Meta:
        unique_together = ['color', 'printer']
        verbose_name = 'Printer Toner Cartridge'
Exemple #10
0
class VersionMixin(models.Model):
    _manipulator = None

    action_id = PositiveIntegerField(null=True)

    # action definition
    action_name = CharField(max_length=16, null=True)
    manipulator_id = VersionManipulatorIdField(max_length=255)
    revert_data = jsonfield.JSONField(
        help_text="The serialized form of this version of the model.")

    # serialized object representation
    revert_fields = jsonfield.JSONField(
        help_text="The serialized form of affected model fields.")
    versioned_type = models.ForeignKey(ContentType,
                                       related_name='version_versioned')
    versioned_id = PositiveIntegerField()

    # versioned object relation
    versioned = GenericForeignKey('versioned_type', 'versioned_id')
    versioned_related_type = models.ForeignKey(
        ContentType,
        related_name='version_versioned_related',
        null=True)

    # versioned_related object relation
    versioned_related_id = PositiveIntegerField(null=True)
    versioned_related = GenericForeignKey('versioned_related_type',
                                          'versioned_related_id')
    created_at = models.DateTimeField(auto_now_add=True)

    # timestamp and created_by
    updated_at = models.DateTimeField(auto_now=True)

    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=PROTECT,
                                   null=True)

    class Meta:
        abstract = True

    def get_manipulator(self):
        if not self._manipulator:
            from libs.version.manipulator import factory_manipulator

            self._manipulator = factory_manipulator(self, self.manipulator_id)
        return self._manipulator

    def __unicode__(self):
        return 'Version({}):{}:{}'.format(self.id, self.action_name,
                                          self.action_code)
Exemple #11
0
class Repository(models.Model):
    owner = CharField(max_length=100)
    name = CharField(max_length=100)
    slug = SlugField(max_length=201)
    host_slug = SlugField(max_length=302, unique=True)
    language = CharField(max_length=100, null=True)
    html_url = URLField(null=True, max_length=400)
    homepage = URLField(null=True, max_length=400)
    watchers = PositiveIntegerField(null=True)
    created_at = DateTimeField(null=True)
    pushed_at = DateTimeField(null=True)
    description = TextField(null=True)
    extra_data = JSONField(null=True)
    last_modified = DateTimeField(auto_now=True)
    scm = CharField(max_length=100, choices=SCM_CHOICES, null=True)
    host = CharField(max_length=100, choices=HOST_CHOICES)
    private = BooleanField(default=False)

    class Meta:
        unique_together = ("owner", "name", "host")
        ordering = ['-watchers']

    def save(self, *args, **kwargs):
        self.slug = self.owner.lower() + '/' + self.name.lower()
        self.host_slug = self.host + '/' + self.slug
        if self.html_url == None or self.html_url == '':
            if self.host == 'bitbucket':
                self.html_url = 'https://bitbucket.org/%s/%s' % (self.owner,
                                                                 self.name)
            if self.host == 'github':
                self.html_url = 'https://github.com/%s/%s' % (self.owner,
                                                              self.name)

        super(Repository, self).save(*args, **kwargs)
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')
Exemple #13
0
    def text_to_value(self, text, query, lookups):
        model_key = lookups[-2]['model'] if len(
            lookups) > 1 else query['model']
        app_label, model_name = model_key.split('.')
        model = apps.get_model(app_label, model_name)
        lookup = lookups[-1]

        if lookup['equality'] == '__isnull':
            return True
        elif text is not None and lookup['equality'] in ('__day', '__month',
                                                         '__year'):
            return PositiveIntegerField().to_python(text)

        if text is None:
            return None

        if not 'field' in lookup:
            return None

        field = model._meta.get_field_by_name(lookup['field'])[0]
        if lookup['equality'] == '__in':
            items = text.split(',')
            return [
                self.text_to_value_based_on_field(item, field)
                for item in items
            ]
        return self.text_to_value_based_on_field(text, field)
Exemple #14
0
class CourseAssetCacheTtlConfig(ConfigurationModel):
    """
    Configuration for the TTL of course assets.

    .. no_pii:
    """
    class Meta(object):
        app_label = 'contentserver'

    cache_ttl = PositiveIntegerField(
        default=0,
        help_text=
        "The time, in seconds, to report that a course asset is allowed to be cached for."
    )

    @classmethod
    def get_cache_ttl(cls):
        """Gets the cache TTL for course assets, if present"""
        return cls.current().cache_ttl

    def __repr__(self):
        return '<CourseAssetCacheTtlConfig(cache_ttl={})>'.format(
            self.get_cache_ttl())

    def __unicode__(self):
        return unicode(repr(self))
Exemple #15
0
class Chapter_Setting(models.Model):
    ca_thi = ForeignKey(CaThi, verbose_name="Ca thi")
            
    chapter = PositiveIntegerField(verbose_name="Chương", 
                                             default=1,
                                             help_text="ví dụ: 1,2,...") 
    num_of_questions = PositiveIntegerField(verbose_name="số câu hỏi",
                                            default=1)
    
    class Meta:
        verbose_name = "Thiết lập số câu hỏi cho từng chương"
        verbose_name_plural = "Thiết lập số câu hỏi cho từng chương"
#         managed=False
        
    def __unicode__(self):
        return u'%s:%s' %(self.chapter,
                             self.num_of_questions)
Exemple #16
0
class TrackerPosition(Model):
    tracker = ForeignKey('Tracker',
                         on_delete=models.CASCADE,
                         verbose_name=_('tracker'))
    datetime = DateTimeField(auto_now_add=True,
                             verbose_name=_('datetime'),
                             db_index=True)
    latitude = DecimalField(max_digits=9,
                            decimal_places=6,
                            verbose_name=_('latitude'))
    longitude = DecimalField(max_digits=9,
                             decimal_places=6,
                             verbose_name=_('longitude'))
    gps_datetime = DateTimeField(auto_now_add=True,
                                 verbose_name=_('datetime'),
                                 db_index=True)
    speed = PositiveIntegerField(null=True,
                                 blank=True,
                                 verbose_name=_('speed'))
    direction_longitude = CharField(max_length=20,
                                    null=True,
                                    blank=True,
                                    choices=LONGITUDE_DIRECTION,
                                    verbose_name=_('longitude direction'))
    direction_latitude = CharField(max_length=20,
                                   null=True,
                                   blank=True,
                                   choices=LATITUDE__DIRECTION,
                                   verbose_name=_('latitude direction'))
    direction_angle = PositiveIntegerField(null=True,
                                           blank=True,
                                           verbose_name=_('direction angle'))
    message = TextField(verbose_name=_('message'))

    def __str__(self):
        return u'{tracker} - {datetime}'.format(tracker=self.tracker,
                                                datetime=self.datetime)

    class Meta:
        app_label = 'tracker'
        ordering = [
            'datetime',
        ]
        verbose_name_plural = _('tracker positions')
        verbose_name = _('tracker position')
Exemple #17
0
class UserRepositoryLink(models.Model):
    user = ForeignKey(UserProfile)
    repository = ForeignKey(Repository)
    order = PositiveIntegerField()
    repository_category = ForeignKey(RepositoryCategory)
    link_type = ForeignKey(LinkType)
    last_modified = DateTimeField(auto_now=True)

    class Meta:
        ordering = ['repository_category__name', 'order']
        unique_together = ("user", "repository", 'link_type')
Exemple #18
0
class SlugMixin(models.Model):
    slug = models.CharField(max_length=255, unique=True, db_index=True)

    content_type = models.ForeignKey(ContentType)
    object_id = PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True
Exemple #19
0
class Note(models.Model):
    class Meta:
        verbose_name_plural = "Notes"
        ordering = ["added"]

    added = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey(Person, null=True, blank=True)
    notes = models.TextField(blank=True, null=True)

    content_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = PositiveIntegerField(null=True)
    location = GenericForeignKey('content_type', 'object_id')
class EmailStatisticDate(Model):
    date = DateField(verbose_name=_('date'))
    status = CharField(max_length=20, choices=EMAIL_STATISTIC_STATUS_CHOICES, verbose_name=_('type'))
    quantity = PositiveIntegerField(default=0, verbose_name=_('quantity'))

    def __str__(self):
        return u'{0}'.format(self.date.strftime('%Y/%m/%d'))

    class Meta:
        unique_together = (("date", "status"),)
        verbose_name_plural = _('emails statistics by date')
        verbose_name = _('email statistic by date')
Exemple #21
0
class CaThiTuLuan(models.Model):
    ten_ca_thi = CharField(max_length=100,
                           verbose_name="Tiêu đề ca thi")
    
    nam_hoc = CharField(max_length=9,
                        verbose_name="Năm học",
                        help_text="Nhập năm học theo định dạng XXXX-XXXX. Ví dụ 2015-2016")
    
    hoc_ky = CharField(max_length=3,
                              choices=HOC_KY,
                            default=HK1,
                            verbose_name="Học kỳ")

    doi_tuong = ForeignKey(DoiTuong,
                           verbose_name="Đối tượng")
    
    mon_thi = ForeignKey(MonThi,
                         verbose_name = "Môn thi")
    
    lop = ForeignKey(Lop,
                     verbose_name = "Lớp")

    ngay_thi = DateField(verbose_name="Ngày thi")
#     
    giam_thi = ManyToManyField(GiaoVien, blank=False, 
                              verbose_name=u'Danh sách giám thị coi thi')

#     giam_thi = ManyToManyField(GiaoVien, blank=False,
#                                 verbose_name = u'GT')
    
    so_de_thi = PositiveIntegerField(verbose_name = "Số đề thi",
                                     default=1,
                                     help_text = u"Số đề thi là số nguyên dương, lớn hơn 0")
    ds_de_thi = ManyToManyField(DeThiTuLuan, blank=True,
                                verbose_name = u'DT')

    class Meta:
        verbose_name = u"Kế hoạch thi - bốc đề"
        verbose_name_plural = u"Kế hoạch thi - bốc đề"

    def __unicode__(self):
        return u'%s-%s-%s' %(self.doi_tuong, self.mon_thi, self.lop)
    
#     def save(self, *args, **kwargs):
#         # lay ngan hang de thi tuong ung voi doi_tuong va mon_thi
#         ngan_hang_dt = NganHangDeThiTuLuan.objects.filter(doi_tuong=self.doi_tuong, 
#                                                           mon_thi=self.mon_thi)
#         # lay so_de_thi
#         de_thi_s = random.sample(ngan_hang_dt, self.so_de_thi)
#         for de_thi in de_thi_s:
#             self.ds_de_thi.add(de_thi)
#         super(CaThiTuLuan, self).save(*args, **kwargs)
Exemple #22
0
class News(Information):
    id_vk = PositiveIntegerField(
        'Номер записи в вк',
        editable=False,
        default=0,
    )

    def __str__(self) -> str:
        return f'Новость #{self.id}'

    class Meta:
        verbose_name = u'Новость'
        verbose_name_plural = u'Новости'
Exemple #23
0
class Slide(Model):
    title = CharField(max_length=255)
    description = CharField(max_length=255)
    url = URLField(blank=True)
    image = ImageField(storage=FileSystemStorage('{}/carousel/slides/'.format(MEDIA_ROOT), '{}/carousel/slides/'.format(MEDIA_URL)))
    order = PositiveIntegerField(default=0)
    active = BooleanField()
    
    def __unicode__(self):
        return self.title
    
    class Meta:
        ordering = ['order']
Exemple #24
0
class Photograph(models.Model):
    image = ImageField(upload_to=PHOTO_UPLOAD_TO, height_field='image_height', width_field='image_width', max_length=1000)
    thumbnail = ImageField(upload_to=PHOTO_UPLOAD_TO, height_field='thumb_height', width_field='thumb_width', max_length=1000, blank=True)
    image_width = PositiveIntegerField()
    image_height = PositiveIntegerField()
    thumb_width = PositiveIntegerField(null=True)
    thumb_height = PositiveIntegerField(null=True)
    description = models.TextField(blank=True, null=True, default='')
    date = models.DateTimeField(default=timezone.now)
    notes = models.TextField(blank=True, null=True, default='')
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)
    occurrence_fk = models.PositiveIntegerField(blank=True, null=True)
    occurrence = GenericForeignKey('content_type', 'occurrence_fk')

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        try:
            (thumb, date) = get_thumbnail_and_date(self.image, self.image.path)
            self.thumbnail = thumb
            self.date = date
        except:
            pass
        super(Photograph, self).save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
Exemple #25
0
class Lop(models.Model):
    ma_lop = CharField(verbose_name="Mã lớp", unique=True, max_length=5)
    ten_lop = CharField(verbose_name = "Lớp", unique=True, max_length=200)
    si_so = PositiveIntegerField(verbose_name="Sĩ số", blank=True,null=True)
    doi_tuong = ForeignKey(DoiTuong, verbose_name="Đối tượng", 
                           blank=False, null=False)

    class Meta:
        verbose_name = "Lớp"
        verbose_name_plural = "Danh sách lớp"
    
    def __unicode__(self):
        return u'%s' %(self.ten_lop)
Exemple #26
0
def get_last_hunt_or_none(request):
    if (request.user.is_staff):
        hunt = Hunt.objects.filter(is_current_hunt=True)
        nb_puzzle = len([
            0 for episode in hunt.first().episode_set.all()
            for puzzle in episode.puzzle_set.all()
        ])
        return hunt.annotate(
            puz=Value(nb_puzzle, output_field=PositiveIntegerField())).first()

    last_hunts = Hunt.objects.filter(
        end_date__lt=timezone.now()).order_by('-end_date')
    if last_hunts.count() == 0:
        return None
    nb_puzzle = len([
        0 for episode in last_hunts.first().episode_set.all()
        for puzzle in episode.puzzle_set.all()
    ])

    hunt = last_hunts[:1].annotate(
        puz=Value(nb_puzzle, output_field=PositiveIntegerField())).first()
    return hunt
class Offer(models.Model):
    title = models.CharField(max_length=100, verbose_name='title')
    content = models.TextField(verbose_name='content')
    location = models.CharField(max_length=100, verbose_name='location')
    date = models.DateField(default='20/12/2021')
    time = TimeField(null=True)
    duration = PositiveIntegerField(null=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(default='defaultservice.jpg',
                              upload_to='post_pics')

    max_participants = models.PositiveIntegerField(
        default=3, validators=[MinValueValidator(1)])
    timecredit = models.PositiveIntegerField(default=1)
    num_participants = models.PositiveIntegerField(default=0)

    finished_participants = models.ManyToManyField(
        User, related_name="finished_offers")
    current_participants = models.ManyToManyField(
        User, related_name="current_offers")
    waiting_participants = models.ManyToManyField(
        User, related_name="waiting_offers")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        #redirect to its own detail page after being created
        return reverse('offer-detail', kwargs={'pk': self.pk})

    def clean(self):
        if self.num_participants > self.max_participants:
            raise ValidationError(
                _('Maximum number of participants cannot be less than number of current participants!'
                  ))

    @property
    def feedback_senders(self):

        return list(self.feedbacks.values_list("sender__username", flat=True))

    @property
    def feedback_receivers(self):

        return list(self.feedbacks.values_list("receiver__username",
                                               flat=True))

    def get_type(self):
        return "offer"
Exemple #28
0
 def test_alter_null_to_not_null_keeping_default(self):
     """
     #23738 - Can change a nullable field with default to non-nullable
     with the same default.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(AuthorWithDefaultHeight)
     # Ensure the field is right to begin with
     columns = self.column_classes(AuthorWithDefaultHeight)
     self.assertTrue(columns['height'][1][6])
     # Alter the height field to NOT NULL keeping the previous default
     new_field = PositiveIntegerField(default=42)
     new_field.set_attributes_from_name("height")
     with connection.schema_editor() as editor:
         editor.alter_field(
             AuthorWithDefaultHeight,
             AuthorWithDefaultHeight._meta.get_field_by_name("height")[0],
             new_field,
         )
     # Ensure the field is right afterwards
     columns = self.column_classes(AuthorWithDefaultHeight)
     self.assertFalse(columns['height'][1][6])
Exemple #29
0
class GiaoVien(models.Model):
    user = OneToOneField(User)
    
    ma_so=PositiveIntegerField(blank=False, null=False,
                               unique=True,
                               verbose_name="Mã số")
    
    ho_ten = CharField(blank=False, null=False,
                       max_length=50,
                       verbose_name="Họ và tên")
    
    don_vi = ForeignKey(DonVi, verbose_name='Đơn vị', help_text="Đơn vị quản lý trực tiếp")
    
#     lop = ForeignKey(Lop, blank=False, null=False,
#                      verbose_name="Lớp")
    # tam the da, co the can them cac truong khac
    

    class Meta:
        verbose_name = "Giáo viên"
        verbose_name_plural = "Danh sách giáo viên"

    def __unicode__(self):
        return u'%s (%s)' %(self.ho_ten, self.don_vi)
    
    def save(self, *args, **kwargs):
        '''
        when save a student, we also make a user who can login to make exam
        '''
        u = 'GV'+str(self.ma_so)
        # check if this GV already exist in user table
        users = User.objects.filter(username=u)
        # if not
        if len(users) == 0:
            # then create a new user 
            new_user = User.objects.create_user(username=u, password=self.ma_so)
            new_user.is_staff = True
            new_user.save()
            self.user = new_user
        else:
            self.user = users[0];
        super(GiaoVien, self).save(*args, **kwargs)
        
    def delete(self, using=None):
        '''
        also delete from user table
        '''
        user = User.objects.get_by_natural_key(self.ma_so)
        User.delete(user, using)
        models.Model.delete(self, using=using)
Exemple #30
0
 def test_alter_null_to_not_null_keeping_default(self):
     """
     #23738 - Can change a nullable field with default to non-nullable
     with the same default.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(AuthorWithDefaultHeight)
     # Ensure the field is right to begin with
     columns = self.column_classes(AuthorWithDefaultHeight)
     self.assertTrue(columns['height'][1][6])
     # Alter the height field to NOT NULL keeping the previous default
     new_field = PositiveIntegerField(default=42)
     new_field.set_attributes_from_name("height")
     with connection.schema_editor() as editor:
         editor.alter_field(
             AuthorWithDefaultHeight,
             AuthorWithDefaultHeight._meta.get_field_by_name("height")[0],
             new_field,
         )
     # Ensure the field is right afterwards
     columns = self.column_classes(AuthorWithDefaultHeight)
     self.assertFalse(columns['height'][1][6])
def lookup(request):
    """
    A view to search for users/teams
    """
    person = None
    team = None
    curr_hunt = Hunt.objects.get(is_current_hunt=True)
    if request.method == 'POST':
        lookup_form = LookupForm(request.POST)
        if lookup_form.is_valid():
            search_string = lookup_form.cleaned_data['search_string']
            results = {
                'teams': Team.objects.search(search_string),
                'people': Person.objects.search(search_string)
            }
    else:
        if ("person_pk" in request.GET):
            person = Person.objects.get(pk=request.GET.get("person_pk"))
        if ("team_pk" in request.GET):
            team = Team.objects.get(pk=request.GET.get("team_pk"))
            team.latest_submissions = team.submission_set.values_list('puzzle')
            team.latest_submissions = team.latest_submissions.annotate(
                Max('submission_time'))
            sq1 = Solve.objects.filter(team__pk=OuterRef('pk'),
                                       puzzle__is_meta=True).order_by()
            sq1 = sq1.values('team').annotate(c=Count('*')).values('c')
            sq1 = Subquery(sq1, output_field=PositiveIntegerField())
            all_teams = team.hunt.team_set.annotate(metas=sq1,
                                                    solves=Count('solved'))
            all_teams = all_teams.annotate(
                last_time=Max('solve__submission__submission_time'))
            ids = all_teams.order_by(
                F('metas').desc(nulls_last=True),
                F('solves').desc(nulls_last=True),
                F('last_time').asc(nulls_last=True))
            team.rank = list(ids.values_list('pk', flat=True)).index(
                team.pk) + 1

        lookup_form = LookupForm()
        results = {}
    context = {
        'lookup_form': lookup_form,
        'results': results,
        'person': person,
        'team': team,
        'curr_hunt': curr_hunt
    }
    return render(request, 'lookup.html',
                  add_apps_to_context(context, request))
Exemple #32
0
class RepositoryUser(models.Model):
    login = CharField(max_length=100, db_index=True)
    name = CharField(max_length=100, null=True)
    slug = SlugField(max_length=201, unique=True)
    email = EmailField(max_length=254, null=True)
    blog = URLField(null=True)
    followers = PositiveIntegerField(null=True)
    following = PositiveIntegerField(null=True)
    public_repos = PositiveIntegerField(null=True)
    created_at = DateTimeField(null=True)
    extra_data = JSONField(null=True)
    last_modified = DateTimeField(auto_now=True)
    repositories = models.ManyToManyField(
        Repository, through='RepositoryUserRepositoryLink')
    starred = PositiveIntegerField(null=True)
    watched = PositiveIntegerField(null=True)
    host = CharField(max_length=100, choices=HOST_CHOICES, db_index=True)

    class Meta:
        unique_together = ("login", "host")

    def save(self, *args, **kwargs):
        self.slug = self.host + '/' + self.login.lower()
        super(RepositoryUser, self).save(*args, **kwargs)