Example #1
0
 def test_rename(self):
     """
     Tests simple altering of fields
     """
     # 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.assertEqual(columns['name'][0], "CharField")
     self.assertNotIn("display_name", columns)
     # Alter the name field's name
     # The original test tried to resize the field from 255 to 254
     # Firebird doesn''t allow change to a smaller size than you had before
     #new_field = CharField(max_length=254)
     new_field = CharField(max_length=256)
     new_field.set_attributes_from_name("display_name")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Author,
             Author._meta.get_field_by_name("name")[0],
             new_field,
             strict=True,
         )
     # Ensure the field is right afterwards
     columns = self.column_classes(Author)
     self.assertEqual(columns['display_name'][0], "CharField")
     self.assertNotIn("name", columns)
Example #2
0
 def test_add_field_temp_default(self):
     """
     Tests adding fields to models with a temporary default
     """
     # 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 = CharField(max_length=30, default="Godwin")
     new_field.set_attributes_from_name("surname")
     with connection.schema_editor() as editor:
         editor.add_field(
             Author,
             new_field,
         )
     # Ensure the field is right afterwards
     columns = self.column_classes(Author)
     self.assertEqual(columns['surname'][0], "CharField")
     self.assertEqual(columns['surname'][1][6],
                      connection.features.interprets_empty_strings_as_nulls)
Example #3
0
 def test_rename(self):
     """
     Tests simple altering of fields
     """
     # 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.assertEqual(columns['name'][0], "CharField")
     self.assertNotIn("display_name", columns)
     # Alter the name field's name
     new_field = CharField(max_length=254)
     new_field.set_attributes_from_name("display_name")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Author,
             Author._meta.get_field_by_name("name")[0],
             new_field,
             strict=True,
         )
     # Ensure the field is right afterwards
     columns = self.column_classes(Author)
     self.assertEqual(columns['display_name'][0], "CharField")
     self.assertNotIn("name", columns)
	def contribute_to_class(self, cls, name):
		# let's sneak in our supporting foo_measured and foo_normalized_unit field and add it to our model definition
		foo_measured = CharField(help_text="Stores pre-normalized value of the '{0}' UOMField field. Modify " \
											 "directly at your own risk as there is no sync checking logic " \
											 "at present.".format(name),
										max_length=255, blank=True)
		foo_measured.creation_counter = self.creation_counter # we must ensure our supporting fields are init first  
		cls.add_to_class("{0}_measured".format(name), foo_measured) # when this increments self.creation_counter by 1
		del foo_measured  # the price to pay for no scope brackets and hence anonymous methods

		foo_unit = CharField(help_text="The unit of the normalized value in '{0}' UOMField field. Modify" \
										 " at your own risk as there is no sync checking logic at present" \
										 .format(name),
										max_length=255, blank=True,
										choices=[(x, x) for x in self.normalized_units])
		foo_unit.creation_counter = self.creation_counter # we must ensure our supporting fields are init first
		cls.add_to_class("{0}_unit".format(name), foo_unit)
		del foo_unit  # the price to pay for no scope brackets and hence anonymous methods

		# do default - we must ensure that our supporting fields are added first to the model so they 
		# avaiable when accessing our main (this) field and that's why do the code above and overide the creation_cunter
		super(UOMField, self).contribute_to_class(cls, name) 
		
		# Now we need to hook ourself as the attribute of the model itself 
		# in Django this is called attaching the 'descriptor protocol'  
		setattr(cls, self.name, self)		
Example #5
0
 def __init__(self, verbose_name=None, name=None,
              verify_exists=True, **kwargs):
     kwargs['max_length'] = kwargs.get('max_length', 200)
     CharField.__init__(self, verbose_name, name, **kwargs)
     validator = validators.ExtendedURLValidator(
         verify_exists=verify_exists)
     self.validators.append(validator)
 def __init__(self, *args, **kwargs):
     kwargs.setdefault('editable', True)
     kwargs.setdefault('max_length', 25)
     kwargs.setdefault('choices', DATE_ESTIMATED)
     kwargs.setdefault(
         'help_text',
         _('If the exact date is not known, please indicate which part of the date is estimated.'))
     CharField.__init__(self, *args, **kwargs)
Example #7
0
 def __init__(self, verbose_name=None, name=None, auto=True, **kwargs):
     self.auto = auto
     # Set this as a fixed value, we store UUIDs in text.
     kwargs['max_length'] = 36
     if auto:
         # Do not let the user edit UUIDs if they are auto-assigned.
         kwargs['editable'] = False
         kwargs['blank'] = True
     CharField.__init__(self, verbose_name, name, **kwargs)
Example #8
0
 def __init__(self, verbose_name=None, name=None, verify_exists=None, **kwargs):
     kwargs["max_length"] = kwargs.get("max_length", 200)
     CharField.__init__(self, verbose_name, name, **kwargs)
     # 'verify_exists' was deprecated in Django 1.4. To ensure backwards
     # compatibility, it is still accepted here, but only passed
     # on to the parent class if it was specified.
     self.verify_exists = verify_exists
     if verify_exists is not None:
         validator = validators.ExtendedURLValidator(verify_exists=verify_exists)
     else:
         validator = validators.ExtendedURLValidator()
     self.validators.append(validator)
Example #9
0
    def __init__(self, default=False, formatter=formatter, *args, **kwargs):
        # Check that the default value is a valid filter
        if default:
            if default not in formatter.filter_list:
                raise ImproperlyConfigured("'%s' is not a registered markup filter. Registered filters are: %s." %
                                           (default, ', '.join(formatter.filter_list.iterkeys())))
            kwargs.setdefault('default', default)

        kwargs.setdefault('max_length', 255)
        kwargs.setdefault('choices', formatter.choices())
        kwargs.setdefault('verbose_name', ugettext_lazy('markup'))
        CharField.__init__(self, *args, **kwargs)
Example #10
0
 def test_field_rename_inside_atomic_block(self):
     """
     NotImplementedError is raised when a model field rename is attempted
     inside an atomic block.
     """
     new_field = CharField(max_length=255, unique=True)
     new_field.set_attributes_from_name('renamed')
     msg = (
         "Renaming the 'backends_author'.'name' column while in a "
         "transaction is not supported on SQLite < 3.26 because it would "
         "break referential integrity. Try adding `atomic = False` to the "
         "Migration class."
     )
     with self.assertRaisesMessage(NotSupportedError, msg):
         with connection.schema_editor(atomic=True) as editor:
             editor.alter_field(Author, Author._meta.get_field('name'), new_field)
Example #11
0
 def __init__(self,
              verbose_name=_('Tags'),
              max_length=4000,
              blank=True,
              null=True,
              help_text=_('A comma-separated list of tags.'),
              **kwargs):
     kwargs['max_length'] = max_length
     kwargs['blank'] = blank
     kwargs['null'] = null
     kwargs['verbose_name'] = verbose_name
     kwargs['help_text'] = help_text
     self.max_length = max_length
     self.blank = blank
     self.null = null
     self.verbose_name = verbose_name
     self.help_text = help_text
     CharField.__init__(self, **kwargs)
Example #12
0
    def __init__(self, verbose_name=None, name=None, verify_exists=True,
            allow_schemes=("http", "https"), allow_all_schemes=False, allow_netloc=True,
            allow_query=True, allow_fragment=True, **kwargs):

        kwargs['max_length'] = kwargs.get('max_length', 200)
        OriginModelCharField.__init__(self, verbose_name, name, **kwargs)

        self.allow_schemes = allow_schemes or ()
        self.allow_all_schemes = allow_all_schemes
        self.allow_netloc = allow_netloc
        self.allow_query = allow_query
        self.allow_fragment = allow_fragment

        self.validators.append(
            URLValidator2(
                allow_schemes=allow_schemes, allow_all_schemes=allow_all_schemes, allow_netloc=allow_netloc,
                allow_query=allow_query, allow_fragment=allow_fragment
            )
        )
Example #13
0
 def test_indexes(self):
     """
     Tests creation/altering of indexes
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Author)
         editor.create_model(Book)
     # Ensure the table is there and has the right index
     self.assertIn("title", connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table))
     # Alter to remove the index
     new_field = CharField(max_length=100, db_index=False)
     new_field.set_attributes_from_name("title")
     with connection.schema_editor() as editor:
         editor.alter_field(Book, Book._meta.get_field_by_name("title")[0], new_field, strict=True)
     # Ensure the table is there and has no index
     self.assertNotIn("title", connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table))
     # Alter to re-add the index
     with connection.schema_editor() as editor:
         editor.alter_field(Book, new_field, Book._meta.get_field_by_name("title")[0], strict=True)
     # Ensure the table is there and has the index again
     self.assertIn("title", connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table))
     # Add a unique column, verify that creates an implicit index
     with connection.schema_editor() as editor:
         editor.add_field(Book, BookWithSlug._meta.get_field_by_name("slug")[0])
     self.assertIn("slug", connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table))
     # Remove the unique, check the index goes with it
     new_field2 = CharField(max_length=20, unique=False)
     new_field2.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_field(BookWithSlug, BookWithSlug._meta.get_field_by_name("slug")[0], new_field2, strict=True)
     self.assertNotIn("slug", connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table))
Example #14
0
 def test_add_field_use_effective_default(self):
     """
     #23987 - effective_default() should be used as the field default when
     adding a new field.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Author)
     # Ensure there's no surname field
     columns = self.column_classes(Author)
     self.assertNotIn("surname", columns)
     # Create a row
     Author.objects.create(name='Anonymous1')
     # Add new CharField to ensure default will be used from effective_default
     new_field = CharField(max_length=15, blank=True)
     new_field.set_attributes_from_name("surname")
     with connection.schema_editor() as editor:
         editor.add_field(Author, new_field)
     # Ensure field was added with the right default
     with connection.cursor() as cursor:
         cursor.execute("SELECT surname FROM schema_author;")
         item = cursor.fetchall()[0]
         self.assertEqual(item[0], None if connection.features.interprets_empty_strings_as_nulls else '')
Example #15
0
class DiChallenge(Challenge):
    """Dispatchable value Challenge."""

    value = CharField(max_length=64, null=True)
    device = ForeignKey(DiDevice, on_delete=CASCADE)

    def dispatch(self):
        """'Dispatch' a value."""
        self.value = generate_token()
        self.save()

    def verify(self, value, save=True):
        """Verify a value."""
        self.confirm = self.value is not None and value == self.value

        if save:
            self.save()

        return self.confirm
Example #16
0
class EventProcessingException(models.Model):
    event = ForeignKey("Event", on_delete=models.CASCADE, null=True)
    data = TextField()
    message = CharField(max_length=500)
    traceback = TextField()

    created = DateTimeField(auto_now_add=True, editable=False)
    modified = DateTimeField(auto_now=True, editable=False)

    @classmethod
    def log(cls, data, exception, event):
        cls.objects.create(event=event,
                           data=data or "",
                           message=str(exception),
                           traceback=exception_traceback.format_exc())

    def __str__(self):
        return smart_text("<{message}, pk={pk}, Event={event}>".format(
            message=self.message, pk=self.pk, event=self.event))
Example #17
0
class MCQuestion(Question):
    answer_order = CharField(
        max_length=30, null=True    , blank=True,
        choices=ANSWER_ORDER_OPTIONS,
#         help_text=_("The order in which multichoice "
#                     "answer options are displayed "
#                     "to the user"),
        verbose_name="Thứ tự hiển thị câu trả lời")
    
    def save(self, *args, **kwargs):
        self.question_type = MCQUESTION
        super(MCQuestion, self).save(*args, **kwargs)
        
    class Meta:
        verbose_name = "Câu hỏi loại Multiple choice"
        verbose_name_plural = "Danh sách câu hỏi loại Multiple choice"
        
    def getAnswers(self):
        return Answer.objects.filter(question=self.id)
Example #18
0
class Order(Model):
    """
    An order made
    """
    FULFILLED = 'fulfilled'
    CREATED = 'created'

    STATUSES = [CREATED, FULFILLED]

    user = ForeignKey(User)
    status = CharField(
        choices=[(status, status) for status in STATUSES],
        default=CREATED,
        max_length=30,
    )

    created_at = DateTimeField(auto_now_add=True)
    modified_at = DateTimeField(auto_now=True)
    total_price_paid = DecimalField(decimal_places=2, max_digits=20)
Example #19
0
class IdempotencyKey(models.Model):
    uuid = UUIDField(max_length=36,
                     primary_key=True,
                     editable=False,
                     default=uuid.uuid4)
    action = CharField(max_length=100)
    livemode = BooleanField(
        help_text="Whether the key was used in live or test mode.")
    created = DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("action", "livemode")

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

    @property
    def is_expired(self):
        return timezone.now() > self.created + timedelta(hours=24)
class ModelWithoutUser(SerializableModel):
    name = CharField(max_length=30, unique=True)

    def __str__(self):
        return '{} - {}'.format(self.name, self.uuid)

    @classmethod
    def find_by_name(self, name):
        try:
            return ModelWithoutUser.objects.get(name=name)
        except ObjectDoesNotExist:
            return None

    @classmethod
    def find_by_id(cls, id):
        try:
            return ModelWithoutUser.objects.get(id=id)
        except ObjectDoesNotExist:
            return None
Example #21
0
class Diem(models.Model):
    sinh_vien=ForeignKey(SinhVien,
                         blank=False, null=False, 
                         verbose_name="Sinh viên")
    mon_thi = ForeignKey(MonThi,
                         blank=False, null=False,
                         verbose_name="Môn thi")
    
    trang_thai_thi = CharField(max_length=20,
                               choices=TRANG_THAI_THI,
                               default='DA_THI',
                               verbose_name='Trạng thái thi')
    
    diem=CommaSeparatedIntegerField(max_length=5, blank=True, null=True,
                              verbose_name="Điểm")
    class Meta:
        unique_together = (('sinh_vien', 'mon_thi'),)
        verbose_name = "Điểm"
        verbose_name_plural = "Bảng điểm"
Example #22
0
def your_lead_lineage_by_period(user: User,
                                date_from: date,
                                date_to: date,
                                projects: list = None,
                                label_type=None,
                                label_values=None,
                                os_groups=None,
                                browser_groups=None,
                                traffic_channels=None):
    your_leads_qs = Lead.objects.filter(pixel__project__user=user)
    your_leads_qs = _apply_lead_common_filters(your_leads_qs, date_from,
                                               date_to, projects, label_type,
                                               label_values, os_groups,
                                               browser_groups,
                                               traffic_channels)
    your_leads_qs = _apply_lineage_qs(your_leads_qs, date_from, date_to)
    your_leads_qs = your_leads_qs.annotate(
        lead_type=Value('your', output_field=CharField()))
    return your_leads_qs
Example #23
0
def xml_to_field(field_type, **kwargs):
    if field_type == 'int':
        #TODO fix max_length
        field = IntegerField(max_length=MAX_LENGHT_INT, **kwargs)
    if field_type == 'char':
        #TODO fix max_length
        field = CharField(max_length=MAX_LENGHT_CHAR, **kwargs)
    if field_type == 'text':
        field = TextField(**kwargs)
    if field_type == 'boolean':
        field = BooleanField(**kwargs)
    if field_type == 'date':
        field = DateField(**kwargs)
    if field_type == 'datetime':
        field = DateTimeField(**kwargs)
    if field_type == 'float':
        field = FloatField(**kwargs)

    return field
Example #24
0
class SinhVien(models.Model):
    user = OneToOneField(User)
    ma_sv=PositiveIntegerField(blank=False, null=False,
                               unique=True,
                               verbose_name="Mã sinh viên")
    ho_ten = CharField(blank=False, null=False,
                       max_length=50,
                       verbose_name="Họ và tên")
    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 = "Sinh viên"
        verbose_name_plural = "Danh sách sinh viên"

    def __unicode__(self):
        return u'%s-%s' %(self.ho_ten, self.lop.ma_lop)
    
    def save(self, *args, **kwargs):
        '''
        when save a student, we also make a user who can login to make exam
        '''
#         print self.ma_sv
        u = User.objects.filter(username=self.ma_sv)
        if len(u) == 0: 
            new_user = User.objects.create_user(username=self.ma_sv, password=self.ma_sv)
            new_user.is_staff = True
            new_user.save()
            self.user = new_user
        else:
            self.user = u[0];
        super(SinhVien, self).save(*args, **kwargs)
        
    def delete(self, using=None):
        '''
        also delete from user table
        '''
        user = User.objects.get_by_natural_key(self.ma_sv)
        User.delete(user, using)
        models.Model.delete(self, using=using)
class CourseNotice(models.Model):
    sourceCourse = ForeignKey(
        "Course",
        verbose_name="源课程",
        on_delete=CASCADE,
        null=True,
        blank=True,
        related_name="sourceCourse",
    )
    Title = CharField(verbose_name="公告标题", default="新公告标题", max_length=20)
    Message = TextField(verbose_name="课程公告", default="新公告内容")
    createTime = DateTimeField(verbose_name="发布时间", auto_now_add=True)

    def __str__(self) -> str:
        return self.Title

    class Meta:
        ordering = ["-createTime"]
        verbose_name = "课程公告"
        verbose_name_plural = "课程公告"
Example #26
0
class DomainName(Model):
    """Domain Names."""

    ip_address = GenericIPAddressField(protocol='IPv4', verbose_name='IP Address')
    domain_name = CharField(max_length=100, verbose_name='Domain Name')
    sr_number = IntegerField(null=True, verbose_name='SR Number', db_column='ticket_id')

    def __str__(self):
        return 'DNS Record: ' + str(self.ip_address)

    @property
    def domain_name_request(self):
        if self.sr_number:
            # TODO: Update to use updated srsconnector
            # return DomainNameRequest.objects.get(ticket_id=self.sr_number)
            return None
        return None

    class Meta:
        verbose_name = 'Domain Name'
Example #27
0
class Answer(models.Model):
    question = ForeignKey(MCQuestion, verbose_name="Câu hỏi")

    content = CharField(max_length=1000,
                               blank=False,
#                                help_text=_("Enter the answer text that "
#                                            "you want displayed"),
                               verbose_name="Phương án trả lời")

    is_correct = BooleanField(blank=False,
                                  default=False,
                                  help_text="Phương án đúng?",
                                  verbose_name="Là phương án đúng")

    def __unicode__(self):
        return u'%s' %(self.content)

    class Meta:
        verbose_name = "Phương án trả lời"
        verbose_name_plural = "Danh sách phương án trả lời"
Example #28
0
class ReceiverGroup(Model):
    """
    Model for groups of receivers
    """
    name = CharField(_('Group Name'), max_length=100, blank=False, null=False)
    company = ForeignKey('ReceiverCompany',
                         on_delete=CASCADE,
                         blank=True,
                         null=True)
    cashier = ForeignKey('Receiver', on_delete=CASCADE, blank=True, null=True)

    class Meta:
        verbose_name = _('Receiver Group')
        verbose_name_plural = _('Receiver Groups')

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name
Example #29
0
class DNSPublication(Model):
    """A row in this table denotes a DNS publication request.

    Typically this will be populated by a trigger within the database. A
    listeners in regiond will be notified and consult the most recent record
    in this table. This way we can consistently publish zones with the same
    serial in an HA environment, and newly starting regiond processes can
    immediately be consistent with their peers.
    """

    class Meta(DefaultMeta):
        """Needed for South to recognize this model."""

    objects = DNSPublicationManager()

    # The serial number with which to publish the zone. We don't use the
    # primary key for this because zone serials are allowed to cycle.
    serial = BigIntegerField(
        editable=False,
        null=False,
        default=next_serial,
        unique=False,
        validators=(
            MinValueValidator(zone_serial.minvalue),
            MaxValueValidator(zone_serial.maxvalue),
        ),
    )

    # This field is informational.
    created = DateTimeField(
        editable=False, null=False, auto_now=False, auto_now_add=True
    )

    # This field is informational.
    source = CharField(
        editable=False,
        max_length=255,
        null=False,
        blank=True,
        help_text="A brief explanation why DNS was published.",
    )
Example #30
0
class UserProfile(models.Model):
    """ User Profile model to maintain
    current bookings, history of bookings """
    class Meta:
        verbose_name_plural = 'Users Profiles'

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    full_name = CharField(max_length=200, blank=True)
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    email_address = models.EmailField(max_length=254, null=False, blank=True)
    phone_number = models.CharField(max_length=20, blank=True)
    street_address1 = models.CharField(max_length=80, blank=True)
    street_address2 = models.CharField(max_length=80, blank=True)
    postcode = models.CharField(max_length=20, blank=True)
    town_or_city = models.CharField(max_length=40, blank=True)
    county = models.CharField(max_length=80, blank=True)
    country = CountryField(blank_label='Select Country', blank=True)

    def __str__(self):
        return self.user.username
Example #31
0
class Pinhole(Model):
    """Firewall Pinholes."""

    ip_address = GenericIPAddressField(protocol='IPv4', verbose_name='IP Address')
    service_name = CharField(max_length=50, verbose_name='Service Name')
    inner_fw = BooleanField(default=None, verbose_name='Inner Firewall')
    border_fw = BooleanField(default=None, verbose_name='Border Firewall')
    tcp_ports = ListField(verbose_name='TCP Ports')
    udp_ports = ListField(verbose_name='UDP Ports')
    sr_number = IntegerField(null=True, verbose_name='SR Number', db_column='ticket_id')

    def __str__(self):
        return 'Pinhole: ' + str(self.ip_address)

    @property
    def pinhole_request(self):
        if self.sr_number:
            # TODO: Update to use updated srsconnector
            # return PinholeRequest.objects.get(ticket_id=self.sr_number)
            return None
        return None
class ProjectEditorValidationSet(Model):
    """
    A set of project editor validations, with a name and description. The name and description will
    be displayed together with the progress bar in the project editor.
    """
    name = CharField(_(u'name'), max_length=255)
    description = TextField(_(u'description'), max_length=5000)

    def delete(self, *args, **kwargs):
        if not self.pk == 1:
            # Do not allow the RSR validation set to be deleted
            super(ProjectEditorValidationSet, self).delete(*args, **kwargs)

    def __unicode__(self):
        return self.name if self.name else "{0}".format(_(u'Untitled validation set'))

    class Meta:
        app_label = 'rsr'
        verbose_name = _(u'project editor validation set')
        verbose_name_plural = _(u'project editor validation sets')
        ordering = ('id', )
Example #33
0
class Question(MetaBase, Model):
    """
    A single question to be answered.

    When the 'evaluate_employer' flag is set then there
    will be a notification that the employee wishes to
    evaluate with the employer.

    When the 'evaluate_administrator' flag is set then
    the user wishes to evaluate further with a employee
    of 'home4talent'.
    """
    class Meta:
        ordering = ("id", )

    set = ForeignKey(QuestionSet, CASCADE, "questions")

    deleted = DateTimeField(null=True)
    answers = ForeignKey(Answers, CASCADE, "questions")

    question = CharField(max_length=255, unique=True)
Example #34
0
class Source(models.Model):
    TYPE_PDF = 1
    TYPE_YOUTUBE = 2
    TYPE_HTML5VIDEO = 3
    TYPE_HTML5 = 4
    TYPES = ((TYPE_PDF, "PDF"), (TYPE_YOUTUBE, "YOUTUBE"),
             (TYPE_HTML5VIDEO, "HTML5VIDEO"), (TYPE_HTML5, "HTML5"))
    title = CharField(max_length=255, default="untitled")  # old: title text
    submittedby = ForeignKey(User, blank=True,
                             null=True)  # old: submittedby integer
    numpages = IntegerField(default=0)
    w = IntegerField(default=0)  # old: ncols integer
    h = IntegerField(default=0)  # old: nrows integer
    rotation = IntegerField(default=0)  # new
    version = IntegerField(default=0)  #incremented when adding src
    type = IntegerField(choices=TYPES, default=TYPE_PDF)
    x0 = IntegerField(default=0)  #x-coordinate of lower-left corner of trimbox
    y0 = IntegerField(default=0)  #y-coordinate of lower-left corner of trimbox

    def __unicode__(self):
        return "%s %s: %s" % (self.__class__.__name__, self.id, self.title)
class ProjectEditorValidation(Model):
    """
    A validation is used to set a certain field or combination of fields in the project editor as
    mandatory, hidden or read only.

    The rule field is the key in this model. There are 2 options for this field:
    - Only a model (e.g. "partnership") indicating that at least one partnership is mandatory or
    that partnerships should be hidden in the project editor.
    - A model and a field (e.g. "budgetitem.other_extra") indicating that the field is mandatory
    or that the field should be hidden in the project editor.

    Also, any combination of the above options is possible. Separated by ||, which
    indicates an OR relationship. So "project.title||project.subtitle" with a mandatory action
    indicates that either the title or the subtitle of a project is mandatory.
    """
    MANDATORY_ACTION = 1
    HIDDEN_ACTION = 2

    ACTIONS_LIST = [MANDATORY_ACTION, HIDDEN_ACTION, ]

    ACTIONS_LABELS = [
        _(u'Mandatory'),
        _(u'Hidden'),
    ]

    ACTIONS = zip(ACTIONS_LIST, ACTIONS_LABELS)

    validation_set = ForeignKey(
        ProjectEditorValidationSet, verbose_name=_(u'validation set'), related_name='validations'
    )
    validation = CharField(_(u'validation'), max_length=255)
    action = PositiveSmallIntegerField(_(u'action'), choices=ACTIONS, db_index=True)

    def __unicode__(self):
        return "{0} ({1})".format(self.validation, unicode(dict(self.ACTIONS)[self.action]))

    class Meta:
        app_label = 'rsr'
        verbose_name = _(u'project editor validation')
        verbose_name_plural = _(u'project editor validations')
Example #36
0
class Quiz(Model):
    """
    Quiz
    """
    name = CharField('name', max_length=255, null=False)

    count = IntegerField('count', default=0)
    sendCount = IntegerField('sendCount', default=1)

    startTime = DateTimeField(
        'startTime',
        null=False,
        help_text='Format: YYYY-MM-DDThh:mm, example 2021-01-01T15:30')
    endTime = DateTimeField(
        'endTime',
        null=False,
        help_text='Format: YYYY-MM-DDThh:mm, example 2021-01-01T15:30')

    department = ForeignKey(Department, on_delete=CASCADE)

    def __str__(self):
        return "Quiz:" + self.name
Example #37
0
class ReceiverCompany(Model):
    """
    Where receivers work
    """
    name = CharField(_('Company Name'),
                     max_length=100,
                     blank=False,
                     null=False)
    address = ForeignKey('deliverers.Address',
                         on_delete=CASCADE,
                         blank=True,
                         null=True)

    class Meta:
        verbose_name = _('Receiver Company')
        verbose_name_plural = _('Receiver Companies')

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name
Example #38
0
class UserLabel(models.Model):
    """
    Lists of labels given by users to sentences in the paragraph.
    """
    # Each user labelling is for a sentence in a particular article
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    # Stores a unique identifier for the user session that created this label
    session_id = CharField(max_length=50)
    # List of the labels given to each word by the user
    labels = JSONField()
    # The index of the sentence that has these labels
    sentence_index = IntegerField()
    # A list of the token indices that are the author of this citation
    author_index = JSONField()
    # If this label was added by an admin user
    admin_label = BooleanField()
    # Date of instance creation
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'Label id: {self.id}, Session id: {self.session_id}, {self.article}, Sentence Number: ' \
               f'{self.sentence_index}'
Example #39
0
class _ModelWithOptionalUniqueNameABC(
        _ModelWithObjectsManagerAndDefaultMetaOptionsABC):
    name: CharField = \
        CharField(
            verbose_name='(optional) Unique Name',
            help_text='(optional) Unique Name',

            max_length=MAX_CHAR_FLD_LEN,

            null=True,
            blank=True,
            choices=None,
            db_column=None,
            db_index=True,
            db_tablespace=None,
            default=None,
            editable=True,
            # error_messages={},
            primary_key=False,
            unique=True,
            unique_for_date=None,
            unique_for_month=None,
            unique_for_year=None,
            # validators=()
        )

    class Meta(_ModelWithObjectsManagerAndDefaultMetaOptionsABC.Meta):
        # pylint: disable=too-few-public-methods
        """Metadata."""

        abstract: bool = True

        ordering: Sequence[str] = ('name',)

    def __str__(self) -> str:
        # pylint: disable=no-member
        return (f'{self._meta.verbose_name} "{self.name}"'
                if self.name
                else super().__str__())
Example #40
0
class Airport(models.Model):

    # Airport identification
    code = CharField(max_length=100, blank=True, default='', null=True)
    name = CharField(max_length=100, blank=True, default='', null=True)

    # Airport location
    country = CharField(max_length=100, blank=True, default='', null=True)
    state = CharField(max_length=100, blank=True, default='', null=True)
    city = CharField(max_length=100, blank=True, default='', null=True)
    latitude = DecimalField(max_digits=20, decimal_places=10, default=0.0)
    longitude = DecimalField(max_digits=20, decimal_places=10, default=0.0)

    type = CharField(max_length=100, blank=True, default='', null=True)

    def __unicode__(self):
        return "Airport " + self.prefix + " - " + self.name
Example #41
0
def _lead_age_groups_case(groups: list = None, now: datetime = None):
    """
    returns Case object for time groups
    Case (
        when created__range=(5,30), then='5 to 30 mins'
        when created__range=(1,4), then='1 to 4 hours'
        ...
        default='Others'
    )
    :param groups:
    :param now:
    :return:
    """
    if now is None:
        now = timezone.now()
    if not groups:
        groups = LEAD_AGE_GROUPS.keys()

    group_whens = []
    for group_id in groups:
        try:
            group = LEAD_AGE_GROUPS[group_id]
        except KeyError:
            raise AnalyticsError(_('Invalid group parameter'))
        if group.operator == 'range':
            expr_value = (_lead_age_boundary(now, group.val1),
                          _lead_age_boundary(now, group.val2))
        else:
            expr_value = _lead_age_boundary(now, group.val1)
        group_whens.append(
            When(**{
                'created__' + group.operator: expr_value,
                'then': Value(group_id)
            }))

    return Case(*group_whens,
                default=Value('Others'),
                output_field=CharField())
Example #42
0
class Package(AuditedModel):
    name = CharField(max_length=128)
    organization = ForeignKey(Organization,
                              null=True,
                              blank=True,
                              related_name='packages',
                              db_constraint=False,
                              on_delete=models.PROTECT)

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

    def get_actions_names(self):
        return self.actions.values_list('name', flat=True)

    def get_actions_ids(self):
        return self.actions.values_list('name', flat=True)

    def get_types_names(self):
        return self.types.values_list('name', flat=True)

    def get_types_ids(self):
        return self.types.values_list('name', flat=True)
Example #43
0
class ScoresheetView(models.Model):
    id = models.IntegerField(primary_key=True) # AutoField?
    sid = models.CharField(max_length=16, null=False, blank=True, default='')
    first_name = models.CharField(max_length=32, blank=True, default='')
    last_name = models.CharField(max_length=32,blank=True, default='')
    email = models.EmailField()
    comments = models.TextField(max_length=255, null=True, blank=True, default='')
    user_id = models.IntegerField()
    cas_user = models.CharField(max_length=255)
    level_id = models.IntegerField()
    level = CharField(max_length=500)
    exam_date = models.DateField()
    language_id = models.IntegerField()
    language_name = models.CharField(max_length=255, null=True)
    needs_review = models.BooleanField(default=0)
     
    def __unicode__(self):
        return self.sid
     
    class Meta:
        managed = False
        app_label ='scoresheet'
        db_table = 'scoresheets_view'
Example #44
0
    def test_alter(self):
        """
        Tests simple altering of fields
        Firebird: changes from varchar to Text (blob sub_type 1) is nor allowed
        """
        # 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.assertEqual(columns['name'][0], "CharField")
        self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls))

        # Alter the name field to a CharField
        new_field = CharField(max_length=2000, null=True)
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(
                Author,
                Author._meta.get_field_by_name("name")[0],
                new_field,
                strict=True,
            )

        # Ensure the field is right afterwards
        columns = self.column_classes(Author)
        self.assertEqual(columns['name'][0], "CharField")
        self.assertEqual(columns['name'][1][6], True)  # Is null?

        # Change nullability again
        new_field2 = CharField(max_length=2000, null=False)
        new_field2.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(
                Author,
                new_field,
                new_field2,
                strict=True,
            )

        # Ensure the field is right afterwards
        columns = self.column_classes(Author)
        self.assertEqual(columns['name'][0], "CharField")
        self.assertEqual(bool(columns['name'][1][6]), False)
Example #45
0
class Question(models.Model):
    id = CharField(max_length=20, primary_key=True, db_column='id')
    exam_id = ForeignKey(Exam,
                         default=None,
                         db_column='EXAMID',
                         on_delete=models.CASCADE)
    context = CharField(max_length=1000, default='', db_column='CONTEXT')
    choice1 = CharField(max_length=400, default='', db_column='CHOICE1')
    choice2 = CharField(max_length=400, default='', db_column='CHOICE2')
    choice3 = CharField(max_length=400, default='', db_column='CHOICE3')
    choice4 = CharField(max_length=400, default='', db_column='CHOICE4')
    correct = IntegerField(db_column='CORRECT',
                           default=1,
                           validators=[validate_choice])
    point = IntegerField(default=0, validators=[under100])

    class Meta:
        db_table = "QUESTION"
Example #46
0
 def __init__(self, *args, **kwargs):
     kwargs['max_length'] = kwargs.get('max_length', 200)
     CharField.__init__(self, *args, **kwargs)
     self.validators.append(validators.ExtendedURLValidator())
Example #47
0
 def __init__(self, *args, **kwargs):
     from country_utils.countries import COUNTRY_CHOICES
     kwargs['max_length'] = 2
     kwargs['choices'] = COUNTRY_CHOICES
     kwargs['null'] = kwargs.get('null', False)
     CharField.__init__(self, *args, **kwargs)
Example #48
0
 def __init__(self, verbose_name=None, name=None, **kwargs):
     kwargs['max_length'] = 250 #less than 2^8
     CharField.__init__(self, verbose_name, name, **kwargs)
Example #49
0
def email_field_init(self, *args, **kwargs):
  kwargs['max_length'] = kwargs.get('max_length', 200)
  CharField.__init__(self, *args, **kwargs)
 def __init__(self, *args, **kwargs):
     kwargs['maxlength'] = 70
     CharField.__init__(self, *args, **kwargs)
Example #51
0
 def __init__(self, *args, **kwargs):
     kwargs['max_length'] = kwargs.get('max_length', 100)
     CharField.__init__(self, *args, **kwargs)
 def test_get_internal_type(self):
     item = SelectMultipleField()
     charfield = CharField()
     self.assertEquals(item.get_internal_type(),
                       charfield.get_internal_type())
Example #53
0
 def __init__(self, verbose_name=None, name=None,
              verify_exists=None, **kwargs):
     kwargs['max_length'] = kwargs.get('max_length', DEFAULT_MAX_LENGTH)
     CharField.__init__(self, verbose_name, name, **kwargs)
     validator = VATINValidator(None)
     self.validators.append(validator)
Example #54
0
 def __init__(self, verbose_name=None, name=None, **kwargs):
     kwargs['max_length'] = 8
     kwargs['help_text'] ="ISO Language Code - ISO Country Code"
     CharField.__init__(self, verbose_name, name, **kwargs)
Example #55
0
 def __init__(self, verbose_name=None, name=None, **kwargs):
     kwargs['max_length'] = 200
     CharField.__init__(self, verbose_name, name, **kwargs)