Esempio n. 1
0
    def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value))
Esempio n. 2
0
class Config(singleton_model.SingletonModel):

    location = models.TextField(
        null=True,
        default=(
            '{"insee":"75056","name":"Paris 14",'
            '"lat":48.8331,"lon":2.3264,"country":"FR",'
            '"admin":"Île-de-France","admin2":"75",'
            '"postCode":"75014"}'
        ),
    )

    location_user_friendly = models.TextField(
        null=True, default="Paris 14 - Île-de-France (75) - FR"
    )

    unit = models.IntegerField(null=False, default=1)
    next_performance_date = models.DateTimeField(null=True)
    next_performance_type = models.TextField(null=True)
    weather_animation_type = models.TextField(
        null=True, default="weather_and_rain"
    )
    weather_frequency = models.IntegerField(default=0)

    next_performance_weather_vocal_date = models.DateTimeField(null=True)
    next_performance_weather_vocal_flag = models.IntegerField(
        null=False, default=0
    )

    weather_playtime_hour = models.IntegerField(
        default=7,
        validators=[
            validators.MinValueValidator(0),
            validators.MaxValueValidator(23),
        ],
    )
    weather_playtime_min = models.IntegerField(
        default=0,
        validators=[
            validators.MinValueValidator(0),
            validators.MaxValueValidator(59),
        ],
    )

    class Meta:
        app_label = "nabweatherd"
Esempio n. 3
0
class Plan(models.Model):
    owner = models.ForeignKey(User,
                              related_name="plans",
                              on_delete=models.CASCADE)
    title = models.CharField(max_length=60)
    date_and_time = models.DateTimeField()
    duration = models.PositiveSmallIntegerField(
        validators=[validators.MaxValueValidator(840)], default=240)
Esempio n. 4
0
class EventType(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)

    location = models.CharField(max_length=200, blank=True)
    description = models.TextField(blank=True)

    duration = models.IntegerField(
        validators=[validators.MinValueValidator(15), validators.MaxValueValidator(60)]
    )

    max_booking_time = models.IntegerField(
        "Tiempo máximo de reserva (en dias)",
        validators=[validators.MinValueValidator(1), validators.MaxValueValidator(30)],
    )

    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.name} ({self.user})"

    def slots(self):
        ruleset = rruleset()

        if not self.rules.all().exists():
            ruleset.rrule(
                rrule(
                    MINUTELY,
                    interval=self.duration,
                    dtstart=now(),
                    until=now() + relativedelta(days=self.max_booking_time),
                )
            )
        else:
            for rule in self.rules.all():
                ruleset.rrule(rule.as_rrule())

        for event in Event.objects.filter(eventtype=self):
            ruleset.exrule(rrule(
                MINUTELY,
                dtstart=event.start_at,
                until=event.ends_at,
            ))

        return ruleset
Esempio n. 5
0
class ParticipateForm(forms.Form):
    email = forms.EmailField(help_text="Email", required=True)
    packages_count = forms.IntegerField(
        validators=[v.MaxValueValidator(100),
                    v.MinValueValidator(1)])
    meals_per_day = forms.IntegerField(
        validators=[v.MaxValueValidator(5),
                    v.MinValueValidator(1)])
    package_volume = forms.IntegerField(
        validators=[v.MaxValueValidator(5000),
                    v.MinValueValidator(100)])
    wb_per_meal = forms.IntegerField(
        validators=[v.MaxValueValidator(500),
                    v.MinValueValidator(100)])
    hungry_people = forms.IntegerField(
        validators=[v.MaxValueValidator(10),
                    v.MinValueValidator(1)])
Esempio n. 6
0
class Bb(models.Model):
    KINDS = (
        ('Куплю', 'Куплю'),
        ('Продам', 'Продам'),
        ('Обменяю', 'Обменяю'),
    )
    rubric = models.ForeignKey('Rubric',
                               null=True,
                               on_delete=models.PROTECT,
                               verbose_name='Рубрика')
    title = models.CharField(max_length=50,
                             verbose_name='Товар',
                             validators=[
                                 validators.MinLengthValidator(
                                     2, message='Слишком маленькое название')
                             ])
    content = models.TextField(
        null=True,
        blank=True,
        verbose_name='Описание',
        unique=True,
        error_messages={'unique': 'Такое описание уже используется'})
    price = models.FloatField(
        null=True,
        blank=True,
        verbose_name='Цена',
        validators=[validators.MaxValueValidator(9999999)],
        error_messages={'max_value': 'Слишком большая цена'})
    published = models.DateTimeField(auto_now_add=True,
                                     db_index=True,
                                     verbose_name='Опубликовано')
    kind = models.CharField(max_length=10,
                            choices=KINDS,
                            blank=True,
                            verbose_name='Действие')

    def clean(self):
        errors = {}
        if not self.content:
            errors['content'] = ValidationError(
                'Укажите описание продаваемого товара')
        if self.price < 0:
            errors['price'] = ValidationError(
                'Укажите неотрицательное значение цены')
        if errors:
            raise ValidationError(errors)

    class Meta:
        verbose_name_plural = 'Объявления'
        verbose_name = 'объявление'
        ordering = ['-published']

    def title_and_price(self):
        if self.price:
            return '%s' '  ' '%d' % (self.title, self.price)
        else:
            return self.title
        title_and_price.short_description = 'Название и цена'
Esempio n. 7
0
class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)

    # +999999999
    # +905469692012

    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$',
        message=
        "Telefon numarası '+999999999' biçiminde girilmelidir. 15 haneye kadar izin verilir.\nÖrneğin: +905121231234"
    )
    phone_number = models.CharField(validators=[phone_regex],
                                    max_length=17,
                                    blank=True)  # validators should be a list

    # 10000000000 - 99999999999
    kimlik_numarası = models.BigIntegerField(
        default=10000000000,
        validators=[
            validators.MinValueValidator(10000000000),
            validators.MaxValueValidator(99999999999)
        ])
    vergi_numarası = models.BigIntegerField(
        default=1000000000,
        validators=[
            validators.MinValueValidator(1000000000),
            validators.MaxValueValidator(9999999999)
        ])
    first_name = models.CharField(_('first name'), max_length=50, null=True)
    last_name = models.CharField(_('last name'), max_length=50, null=True)

    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [
        'kimlik_numarası', 'phone_number', 'vergi_numarası', 'first_name',
        'last_name'
    ]

    objects = CustomUserManager()

    def __str__(self):
        return self.email
Esempio n. 8
0
class ProjectContract(Contract):
    """Project contract model."""

    fixed_fee = models.DecimalField(max_digits=9,
                                    decimal_places=2,
                                    validators=[
                                        validators.MinValueValidator(0),
                                        validators.MaxValueValidator(9999999),
                                    ])
Esempio n. 9
0
class ContactForm(forms.Form):
    name = forms.CharField(max_length=25,
                           validators=[validators.MaxLengthValidator(5)])
    num = forms.IntegerField(max_value=78,
                             validators=[validators.MaxValueValidator(34)])
    phone = forms.CharField(
        max_length=10,
        min_length=10,
        validators=[validators.RegexValidator('[6-9]\d{9}')])
Esempio n. 10
0
    def create_field(self, *, name, data, emodels):
        if is_name_forbidden(name):
            raise IncorrectConfigurationError(
                f"El nombre de atributo {name} esta prohibido")

        # copiamos los datos para manipular tranquilos
        data = copy.deepcopy(data)

        # primero sacamos el tipo
        ftype = data.pop("type")
        dj_ftype = FIELD_TYPES.get(ftype, ftype)

        # aca saco todos las configuraciones que se usaran vara parsear y no
        # para crear cosas
        for tr in KEYS_TO_REMOVE:
            data.pop(tr, None)

        # add the default fields if not present
        for k, v in ATTRS_DEFAULT.items():
            if k not in data:
                data[k] = v

        # ahora el tipo puede ser uno nativo o un foreign key
        if inspect.isclass(dj_ftype) and issubclass(dj_ftype, models.Field):

            if "sep" in data:
                raise IncorrectConfigurationError(
                    "sep solo puede ser definida con una referencia")

            if "choices" in data:
                data["choices"] = [(e, e) for e in data["choices"]]

            fvalidators = []
            if "min" in data:
                min_value = data.pop("min")
                fvalidators.append(validators.MinValueValidator(min_value))
            if "max" in data:
                max_value = data.pop("max")
                fvalidators.append(validators.MaxValueValidator(max_value))
            if fvalidators:
                data["validators"] = fvalidators

            return dj_ftype(**data)

        else:
            # here we have some kind of FK
            link_to = emodels[dj_ftype]

            # if we have sep is a many to many
            sep = data.pop("sep", None)
            if sep:
                data.pop("null", None)
                return models.ManyToManyField(link_to, **data)
            else:
                return models.ForeignKey(link_to,
                                         on_delete=models.CASCADE,
                                         **data)
Esempio n. 11
0
 def __init__(self, max_value, decimal_places=2, **kwargs):
     self.max_value = max_value
     super().__init__(decimal_places=decimal_places,
                      max_digits=int(math.log10(max_value)) + 3,
                      validators=[
                          dj_validators.MinValueValidator(0),
                          dj_validators.MaxValueValidator(max_value)
                      ],
                      **kwargs)
Esempio n. 12
0
    def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        kwargs.setdefault('widget', NumberInput if not kwargs.get('localize') else self.widget)
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value))
Esempio n. 13
0
class Movie(models.Model):
    Name = models.CharField(max_length=50)
    Actor = models.CharField(max_length=50)
    Actress = models.CharField(max_length=50)
    Date = models.DateField()
    Rating = models.IntegerField(validators=[
        validators.MaxValueValidator(10),
        validators.MinValueValidator(1)
    ])
Esempio n. 14
0
def long_to_ip(value):
    validators.validate_integer(value)
    value = long(value)

    validators.MinValueValidator(0)(value)
    validators.MaxValueValidator(4294967295)(value)

    return '%d.%d.%d.%d' % (value >> 24, value >> 16 & 255, value >> 8 & 255,
                            value & 255)
Esempio n. 15
0
class SizeType(models.Model):
    system = models.TextField("system")
    dim = models.IntegerField("dim", null=True)
    value = models.IntegerField("value",
                                null=True,
                                validators=[
                                    validators.MinValueValidator(2),
                                    validators.MaxValueValidator(20)
                                ])
Esempio n. 16
0
    def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        self.max_digits, self.decimal_places = max_digits, decimal_places
        super(DecimalField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value))
Esempio n. 17
0
class WeeklyTeachingForm(forms.Form):
    rate = forms.DecimalField(max_digits=10, decimal_places=4, widget=PoundInput(), disabled=True, label='Hourly rate')
    length = forms.DecimalField(
        max_digits=10,
        decimal_places=1,
        validators=[validators.MinValueValidator(0), validators.MaxValueValidator(100)],
        label='Hours per week (prep & teaching)',
        help_text='Typically 4 for in-person, 5 for online',
    )
    no_meetings = forms.IntegerField(
        validators=[validators.MinValueValidator(1), validators.MaxValueValidator(21)],
        label='Number of meetings',
    )
    schedule = forms.TypedChoiceField(choices=schedule_choices, coerce=int)
    approver = ApproverChoiceField('tutor_payment.approve')

    def clean(self) -> None:
        self.cleaned_data['schedule'] = models.schedules[self.cleaned_data['schedule']]
Esempio n. 18
0
class Batch(models.Model):
    number = models.PositiveSmallIntegerField(unique=True)
    max_groups_num = models.PositiveSmallIntegerField(default=5)
    min_groups_num = models.PositiveSmallIntegerField(default=0)
    max_students_per_group = models.PositiveSmallIntegerField(
        default=2, validators=[
            validators.MinValueValidator(1),
        ])
    supervisor_mark_percentage = models.PositiveIntegerField(
        default=50,
        validators=[
            validators.MaxValueValidator(100),
            validators.MinValueValidator(0),
        ])
    internal_mark_percentage = models.PositiveIntegerField(
        default=30,
        validators=[
            validators.MaxValueValidator(100),
            validators.MinValueValidator(0),
        ])
    external_mark_percentage = models.PositiveIntegerField(
        default=20,
        validators=[
            validators.MaxValueValidator(100),
            validators.MinValueValidator(0),
        ])

    def clean(self):
        if sum([
                self.supervisor_mark_percentage, self.internal_mark_percentage,
                self.external_mark_percentage
        ]) != 100:
            error_message = 'Sum of these must be 100'
            raise ValidationError({
                "supervisor_mark_percentage": error_message,
                "internal_mark_percentage": error_message,
                "external_mark_percentage": error_message,
            })

    class Meta:
        verbose_name_plural = 'batches'

    def __str__(self):
        return f'Batch {self.number}'
Esempio n. 19
0
class Game(models.Model):
    name = models.CharField(max_length = 30)
    losses = models.IntegerField(default = 0, editable = False)
    won = models.IntegerField(default = 0, editable = False)
    difficulty = models.IntegerField(validators = [validators.MinValueValidator(1), validators.MaxValueValidator(5)])

    time = models.IntegerField(validators = [validators.MinValueValidator(30), validators.MaxValueValidator(600)])
    strikes = models.IntegerField(validators = [validators.MinValueValidator(1), validators.MaxValueValidator(99)])

    amount_batteries = models.IntegerField(validators = [validators.MinValueValidator(1), validators.MaxValueValidator(9)])
    lit = models.ForeignKey(Lit, on_delete = models.CASCADE)
    serial_number = models.ForeignKey(SerialNumber, on_delete = models.CASCADE)

    wires_module = models.ForeignKey(Wires, blank = True, null = True, on_delete = models.CASCADE)
    morse_code_module = models.ForeignKey(MorseCode, blank = True, null = True, on_delete = models.CASCADE)
    password_module = models.ForeignKey(Password, blank = True, null = True, on_delete = models.CASCADE)
    the_button_module = models.ForeignKey(TheButton, blank = True, null = True, on_delete = models.CASCADE)
    simon_says_module = models.ForeignKey(SimonSays, blank = True, null = True, on_delete = models.CASCADE)

    def clean(self):
        i = 5
        if self.wires_module is None:
            i = i - 1
        if self.morse_code_module is None:
            i = i - 1
        if self.password_module is None:
            i = i - 1
        if self.the_button_module is None:
            i = i - 1
        if self.simon_says_module is None:
            i = i - 1
        if i < 4:
            raise exceptions.ValidationError('They have to be exactly 5 modules.')
        super(Game, self).clean()

    @property
    def str_difficulty(self):
        t = self.won + self.losses
        if t != 0:
            return '{0}%'.format(int((self.won*100)/t))
        return '{0}%'.format(int(100/self.difficulty))

    def __str__(self):
        return '{0} - {1}'.format(self.name, self.difficulty)
Esempio n. 20
0
class Months(models.Model):
    month = models.IntegerField(primary_key=True,
                                validators=[
                                    validators.MinValueValidator(1),
                                    validators.MaxValueValidator(12)
                                ])
    name = models.CharField(max_length=9)

    def __str__(self):
        return self.name
Esempio n. 21
0
class DayOfMonth(models.Model):
    "Day of the month."
    day = models.IntegerField(primary_key=True,
                              validators=[
                                  validators.MinValueValidator(1),
                                  validators.MaxValueValidator(31)
                              ])

    def __str__(self):
        return str(self.day)
Esempio n. 22
0
class JobData(forms.Form):
    Job_Name = forms.CharField(
        max_length=30,
        required=True,
        validators=[
            RegexValidator(
                regex='^[a-zA-Z0-9_]*$',
                message='Please enter a proper aplhanumeric job name!',
                code='invalid_username'),
        ])
    #Queue = forms.CharField(widget=forms.Select(choices=QUEUE))
    Number_of_Nodes = forms.IntegerField(
        label='No. of nodes:',
        required=True,
        validators=[validators.MaxValueValidator(3)])
    No_of_cores_per_node = forms.IntegerField(
        label='No. of cores per node:',
        required=True,
        validators=[validators.MaxValueValidator(4)])
Esempio n. 23
0
class Walker_Appointment(models.Model):
    walker = models.ForeignKey(Walker, on_delete=models.CASCADE)
    appointment = models.DateTimeField(default=timezone.now,
                                       auto_now=False,
                                       auto_now_add=False)
    slots = models.IntegerField(default=0,
                                validators=[
                                    validators.MaxValueValidator(
                                        5, "I can only take 5 dogs at a time")
                                ])
Esempio n. 24
0
class Book(models.Model):
    """文章"""
    title = models.CharField(max_length=100)
    page = models.IntegerField()
    price = models.FloatField(
        validators=[validators.MaxValueValidator(limit_value=1000)])

    class Meta:
        db_table = 'book'
        verbose_name = '图书'
Esempio n. 25
0
 def __init__(self, request, *args, **kwargs):
     super(RandomBindForm, self).__init__(request, *args, **kwargs)
     max_value = self.initial['chouqurenshu']
     if max_value:
         f = self.fields['chouqurenshu']
         f.max_value = max_value
         extra_attrs = f.widget_attrs(f.widget)
         f.widget.attrs.update(extra_attrs)
         self.fields['chouqurenshu'].validators.append(
             django_validators.MaxValueValidator(max_value))
Esempio n. 26
0
class WorkSchedule(BaseModel):
    # Defines the workschedule for a user
    """Work schedule model."""

    label = models.CharField(unique=True, max_length=255)
    monday = models.DecimalField(max_digits=4,
                                 decimal_places=2,
                                 default=0.00,
                                 validators=[
                                     validators.MinValueValidator(0),
                                     validators.MaxValueValidator(24),
                                 ])
    tuesday = models.DecimalField(max_digits=4,
                                  decimal_places=2,
                                  default=0.00,
                                  validators=[
                                      validators.MinValueValidator(0),
                                      validators.MaxValueValidator(24),
                                  ])
    wednesday = models.DecimalField(max_digits=4,
                                    decimal_places=2,
                                    default=0.00,
                                    validators=[
                                        validators.MinValueValidator(0),
                                        validators.MaxValueValidator(24),
                                    ])
    thursday = models.DecimalField(max_digits=4,
                                   decimal_places=2,
                                   default=0.00,
                                   validators=[
                                       validators.MinValueValidator(0),
                                       validators.MaxValueValidator(24),
                                   ])
    friday = models.DecimalField(max_digits=4,
                                 decimal_places=2,
                                 default=0.00,
                                 validators=[
                                     validators.MinValueValidator(0),
                                     validators.MaxValueValidator(24),
                                 ])
    saturday = models.DecimalField(max_digits=4,
                                   decimal_places=2,
                                   default=0.00,
                                   validators=[
                                       validators.MinValueValidator(0),
                                       validators.MaxValueValidator(24),
                                   ])
    sunday = models.DecimalField(max_digits=4,
                                 decimal_places=2,
                                 default=0.00,
                                 validators=[
                                     validators.MinValueValidator(0),
                                     validators.MaxValueValidator(24),
                                 ])

    def __str__(self):
        """Return a string representation."""
        return self.label
Esempio n. 27
0
class Shipments(models.Model):

    mail = models.CharField(verbose_name='mail', max_length=200)
    product_name = models.CharField(verbose_name='product_name',
                                    max_length=200)
    price = models.IntegerField(verbose_name='price',
                                default=0,
                                validators=[
                                    validators.MinValueValidator(0),
                                    validators.MaxValueValidator(100)
                                ])
    sex = models.IntegerField(verbose_name='price',
                              default=0,
                              validators=[
                                  validators.MinValueValidator(0),
                                  validators.MaxValueValidator(100)
                              ])
    created_at = models.DateTimeField(verbose_name='registlation date',
                                      auto_now_add=True)
Esempio n. 28
0
class Course(models.Model):
    course_number = models.CharField(max_length=20, null=False, blank=False, unique=True)
    name = models.CharField(max_length=50, null=False, blank=False)
    units = models.IntegerField(validators=[
        validators.MinValueValidator(0, 'Course unit should larger than zero'),
        validators.MaxValueValidator(24, 'Course unit larger than 24 is not current supported')
    ])

    def __str__(self):
        return self.name
Esempio n. 29
0
class Employee(models.Model):
    ROLE = (('Senior Developer', 'Senior Developer'),
            ('Junior Developer', 'Junior Developer'), ('Software Tester',
                                                       'Software Tester'))

    def __str__(self):
        return self.name

    name = models.CharField(
        max_length=50,
        verbose_name='NAME',
        validators=[
            v.MinLengthValidator(3, 'Name should be 3 chars long'),
            v.MaxLengthValidator(50, 'Name shoild not be longer than 50 chars')
        ])
    email = models.CharField(
        max_length=50,
        verbose_name='EMAIL',
        unique=True,
        validators=[
            v.MinLengthValidator(5, 'Name should be 5 chars long'),
            v.MaxLengthValidator(50,
                                 'Name shoild not be longer than 50 chars'),
            v.EmailValidator("Invalid Email")
        ])
    age = models.IntegerField(
        verbose_name='AGE',
        validators=[
            v.MinValueValidator(20, 'Age should be above 20'),
            v.MaxValueValidator(70, 'Age should be below 70'),
        ])
    phone = models.BigIntegerField(
        verbose_name='PHONE',
        default=0,
        unique=True,
        validators=[
            v.MinValueValidator(6666666666, 'Invalid Phone Number'),
            v.MaxValueValidator(9999999999, 'Invalid Phone Number'),
        ])
    role = models.CharField(max_length=100, verbose_name='ROLE', choices=ROLE)
    address = models.CharField(max_length=255,
                               verbose_name='ADDRESS',
                               default=0)
Esempio n. 30
0
class Season(models.Model):
    start_year = models.PositiveIntegerField(
        unique=True,
        validators=[
            validators.MinValueValidator(1990),
            validators.MaxValueValidator(2050)
        ])

    def __str__(self):
        return '{}/{}'.format(self.start_year, self.start_year + 1)