示例#1
0
class Boat(models.Model):
    boat_type = models.ForeignKey("BoatType",
                                  null=True,
                                  on_delete=models.SET_NULL,
                                  to_field="sid_bt")
    user = models.ForeignKey(User,
                             related_name="+",
                             null=True,
                             on_delete=models.CASCADE)
    city = models.ForeignKey("City", null=True, on_delete=models.SET_NULL)
    boat_amenities = models.ManyToManyField("BoatAmenities",
                                            blank=True,
                                            related_name="boatamen")
    images = models.ManyToManyField(BoatImages)
    fab_year = models.IntegerField(
        validators=[MinValueValidator(1900),
                    MaxValueValidator(2030)],
        blank=True,
        null=True)
    title = models.CharField(max_length=100)
    manufacturer = models.CharField(max_length=60, blank=True, null=True)
    size = models.IntegerField(default=0)
    capacity = models.IntegerField(
        validators=[MinValueValidator(1),
                    MaxValueValidator(999)], default=0)
    overnight_capacity = models.IntegerField(
        validators=[MinValueValidator(1),
                    MaxValueValidator(99)], default=0)
    bathrooms = models.IntegerField(
        validators=[MinValueValidator(0),
                    MaxValueValidator(99)], default=0)
    rooms = models.IntegerField(
        validators=[MinValueValidator(0),
                    MaxValueValidator(99)], default=0)
    animals = models.CharField(max_length=30, default="0")
    smoke = models.CharField(max_length=30, default="0")
    wheelchair = models.CharField(max_length=30, default="0")
    has_discount = models.CharField(max_length=30, default="0")
    postcode = models.CharField(max_length=100, blank=True, null=True)
    address = models.CharField(max_length=100, blank=True, null=True)
    additional = models.CharField(max_length=100, blank=True, null=True)
    description = models.CharField(max_length=3000, null=True, blank=True)
    price_overnight = models.DecimalField(max_digits=7,
                                          decimal_places=2,
                                          default=0)
    price_day = models.DecimalField(max_digits=7, decimal_places=2, default=0)
    price_half_day = models.DecimalField(max_digits=7,
                                         decimal_places=2,
                                         default=0)
    price_single = models.DecimalField(max_digits=7,
                                       decimal_places=2,
                                       default=0)
    p_single_includes = models.ManyToManyField(BoatPriceIncludes,
                                               related_name='ps_includes',
                                               blank=True)
    p_hday_includes = models.ManyToManyField(BoatPriceIncludes,
                                             related_name='phd_includes',
                                             blank=True)
    p_day_includes = models.ManyToManyField(BoatPriceIncludes,
                                            related_name='pd_includes',
                                            blank=True)
    p_overnight_includes = models.ManyToManyField(BoatPriceIncludes,
                                                  related_name='po_includes',
                                                  blank=True)
    fish_rules = models.CharField(null=True, blank=True, max_length=30)
    fish_species = models.ManyToManyField(BoatFishingSpecies, blank=True)
    fish_bait = models.CharField(null=True, blank=True, max_length=30)
    fish_places = models.CharField(null=True, blank=True, max_length=30)
    review_score = models.DecimalField(max_digits=2,
                                       decimal_places=1,
                                       default=0)
    reviews_count = models.IntegerField(default=0)
    log = models.IntegerField(default=0)
    BOAT_STATUS = (
        ('InReview', 'InReview'),
        ('Published', 'Published'),
        ('Paused', 'Paused'),
        ('Deleted', 'Deleted'),
    )
    status = models.CharField(choices=BOAT_STATUS,
                              max_length=30,
                              default=BOAT_STATUS[0])
    keywords = models.CharField(max_length=1000, null=True, blank=True)
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now_add=True)
    owner_price_overnight = models.DecimalField(max_digits=7,
                                                decimal_places=2,
                                                default=0)
    owner_price_day = models.DecimalField(max_digits=7,
                                          decimal_places=2,
                                          default=0)
    owner_price_half_day = models.DecimalField(max_digits=7,
                                               decimal_places=2,
                                               default=0)
    owner_price_single = models.DecimalField(max_digits=7,
                                             decimal_places=2,
                                             default=0)

    def __str__(self):
        return str(self.title) + " - " + str(self.user.first_name)
示例#2
0
class CharacterChoice(models.Model):
    race = models.ForeignKey(
        'Creed', null=True, blank=False, on_delete=models.SET_NULL)
    name = models.CharField(max_length=50, null=False, blank=False)
    strength = models.PositiveIntegerField(validators=[MaxValueValidator(999)])
    image = models.ImageField(null=True, blank=True)
示例#3
0
class Motor(DimMassModelMixin):

    MOTOR_TYPE = (
        ("AS", "Асинхронный"),
        ("SY", "Синхронный"),
        ("LI", "Линейный"),
        ("ST", "Шаговый"),
        ("SE", "Серводвигатель"),
    )

    MOTOR_EFF_CLASS = (
        ("IE1", "IE1 - Стандартный класс"),
        ("IE2", "IE2 - Высокий класс"),
        ("IE3", "IE3 - Сверхвысокий класс"),
        ("IE4", "IE4 - Максимально высокий класс"),
    )

    MOTOR_INSULATION_CLASS = (
        ("A", "A (105 \xb0C)"),
        ("E", "E (120 \xb0C)"),
        ("B", "B (130 \xb0C)"),
        ("F", "F (155 \xb0C)"),
        ("H", "H (180 \xb0C)"),
    )

    MOTOR_DUTY_TYPE = (
        ("S1", "S1 - Продолжительный режим"),
        ("S2", "S2 - Кратковременный режим"),
        ("S3", "S3 - Повторно-кратковременный режим"),
        ("S4",
         "S4 - Повторно-кратковременный режим с влиянием пусковых процессов"),
        ("S5",
         "S5 - Повторно-кратковременный режим с электрическим торможением"),
        ("S6", "S6 - Перемежающийся режим"),
        ("S7",
         "S7 - Перемежающийся режим с электрическим торможением и влиянием пусковых процессов"
         ),
        ("S8",
         "S8 - Перемежающийся режим с разными частотами вращения (2 или более)"
         ),
    )

    MOTOR_POLES = (
        (1, "1"),
        (2, "2"),
        (3, "3"),
    )

    MOTOR_PHASES = (
        (1, "1"),
        (2, "2"),
        (3, "3"),
    )

    manufacturer = models.ForeignKey(
        Manufacturer,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name=Manufacturer._meta.verbose_name)
    motor_type = models.CharField("тип",
                                  max_length=2,
                                  choices=MOTOR_TYPE,
                                  default="AS")
    motor_code = models.CharField("артикул", max_length=50)
    phases = models.PositiveSmallIntegerField("количество фаз",
                                              choices=MOTOR_PHASES,
                                              default=3,
                                              null=True,
                                              blank=True)
    poles = models.PositiveSmallIntegerField("число пар полюсов",
                                             choices=MOTOR_POLES,
                                             default=1,
                                             null=True,
                                             blank=True)
    eff_100 = models.FloatField(
        "КПД, %",
        validators=[MinValueValidator(0.0),
                    MaxValueValidator(100.0)])
    eff_75 = models.FloatField(
        "КПД (нагрузка - 75%), %",
        validators=[MinValueValidator(0.0),
                    MaxValueValidator(100.0)])
    eff_50 = models.FloatField(
        "КПД (нагрузка - 50%), %",
        validators=[MinValueValidator(0.0),
                    MaxValueValidator(100.0)])
    eff_class = models.CharField("класс энергоэффективности",
                                 max_length=3,
                                 choices=MOTOR_EFF_CLASS,
                                 default="IE2")
    duty_type = models.CharField("режим работы",
                                 max_length=2,
                                 choices=MOTOR_DUTY_TYPE,
                                 default="S1")
    ip_code = models.CharField("степень защиты IP",
                               max_length=4,
                               choices=IP_CODE_CHOICES,
                               default="IP54")
    insulation_class = models.CharField("класс изоляции",
                                        max_length=1,
                                        choices=MOTOR_INSULATION_CLASS,
                                        default="F")

    def __str__(self):
        return '%s (%s)' % (self.motor_code,
                            self.manufacturer.manufacturer_code)

    class Meta:
        verbose_name = "Электродвигатель"
        verbose_name_plural = "Электродвигатели"
        db_table = "catalog_motor"

    def get_absolute_url(self):
        return reverse('motor-detail', args=[str(self.id)])
示例#4
0
文件: models.py 项目: cageyv/otus_web
def max_value_current_year(value):
    return MaxValueValidator(current_year())(value)
示例#5
0
class Quiz(models.Model):

    title = models.CharField(verbose_name=_("Title"),
                             max_length=60,
                             blank=False)

    description = models.TextField(verbose_name=_("Description"),
                                   blank=True,
                                   help_text=_("a description of the quiz"))

    url = models.SlugField(max_length=60,
                           blank=False,
                           help_text=_("a user friendly url"),
                           verbose_name=_("user friendly url"))

    category = models.ForeignKey(Category,
                                 null=True,
                                 blank=True,
                                 verbose_name=_("Category"),
                                 on_delete=models.CASCADE)

    random_order = models.BooleanField(blank=False,
                                       default=False,
                                       verbose_name=_("Random Order"),
                                       help_text=_("Display the questions in "
                                                   "a random order or as they "
                                                   "are set?"))

    max_questions = models.PositiveIntegerField(
        blank=True,
        null=True,
        verbose_name=_("Max Questions"),
        help_text=_("Number of questions to be answered on each attempt."))

    answers_at_end = models.BooleanField(
        blank=False,
        default=False,
        help_text=_("Correct answer is NOT shown after question."
                    " Answers displayed at the end."),
        verbose_name=_("Answers at end"))

    exam_paper = models.BooleanField(blank=False,
                                     default=False,
                                     help_text=_(
                                         "If yes, the result of each"
                                         " attempt by a user will be"
                                         " stored. Necessary for marking."),
                                     verbose_name=_("Exam Paper"))

    single_attempt = models.BooleanField(
        blank=False,
        default=False,
        help_text=_("If yes, only one attempt by"
                    " a user will be permitted."
                    " Non users cannot sit this exam."),
        verbose_name=_("Single Attempt"))

    pass_mark = models.SmallIntegerField(
        blank=True,
        default=0,
        verbose_name=_("Pass Mark"),
        help_text=_("Percentage required to pass exam."),
        validators=[MaxValueValidator(100)])

    success_text = models.TextField(blank=True,
                                    help_text=_("Displayed if user passes."),
                                    verbose_name=_("Success Text"))

    fail_text = models.TextField(verbose_name=_("Fail Text"),
                                 blank=True,
                                 help_text=_("Displayed if user fails."))

    draft = models.BooleanField(blank=True,
                                default=False,
                                verbose_name=_("Draft"),
                                help_text=_("If yes, the quiz is not displayed"
                                            " in the quiz list and can only be"
                                            " taken by users who can edit"
                                            " quizzes."))

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        self.url = re.sub('\s+', '-', self.url).lower()

        self.url = ''.join(letter for letter in self.url
                           if letter.isalnum() or letter == '-')

        if self.single_attempt is True:
            self.exam_paper = True

        if self.pass_mark > 100:
            raise ValidationError('%s is above 100' % self.pass_mark)

        super(Quiz, self).save(force_insert, force_update, *args, **kwargs)

    class Meta:
        verbose_name = _("Quiz")
        verbose_name_plural = _("Quizzes")

    def __str__(self):
        return self.title

    def get_questions(self):
        return self.question_set.all().select_subclasses()

    @property
    def get_max_score(self):
        return self.get_questions().count()

    def anon_score_id(self):
        return str(self.id) + "_score"

    def anon_q_list(self):
        return str(self.id) + "_q_list"

    def anon_q_data(self):
        return str(self.id) + "_data"
示例#6
0
class Settings(Model):
    stg_guiprotocol = models.CharField(
        max_length=120,
        choices=choices.PROTOCOL_CHOICES,
        default="http",
        verbose_name=_("Protocol")
    )
    stg_guicertificate = models.ForeignKey(
        "Certificate",
        verbose_name=_("Certificate"),
        limit_choices_to={'cert_type__in': [CERT_TYPE_EXISTING, CERT_TYPE_INTERNAL]},
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
    stg_guiaddress = models.CharField(
        max_length=120,
        blank=True,
        default='0.0.0.0',
        verbose_name=_("WebGUI IPv4 Address")
    )
    stg_guiv6address = models.CharField(
        max_length=120,
        blank=True,
        default='::',
        verbose_name=_("WebGUI IPv6 Address")
    )
    stg_guiport = models.IntegerField(
        verbose_name=_("WebGUI HTTP Port"),
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
        default=80,
    )
    stg_guihttpsport = models.IntegerField(
        verbose_name=_("WebGUI HTTPS Port"),
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
        default=443,
    )
    stg_guihttpsredirect = models.BooleanField(
        verbose_name=_('WebGUI HTTP -> HTTPS Redirect'),
        default=True,
        help_text=_(
            'Redirect HTTP (port 80) to HTTPS when only the HTTPS protocol is '
            'enabled'
        ),
    )
    stg_language = models.CharField(
        max_length=120,
        choices=settings.LANGUAGES,
        default="en",
        verbose_name=_("Language")
    )
    stg_kbdmap = models.CharField(
        max_length=120,
        choices=choices.KBDMAP_CHOICES(),
        verbose_name=_("Console Keyboard Map"),
        blank=True,
    )
    stg_timezone = models.CharField(
        max_length=120,
        choices=choices.TimeZoneChoices(),
        default="America/Los_Angeles",
        verbose_name=_("Timezone")
    )
    stg_sysloglevel = models.CharField(
        max_length=120,
        choices=choices.SYS_LOG_LEVEL,
        default="f_info",
        verbose_name=_("Syslog level"),
        help_text=_("Specifies which messages will be logged by "
                    "server. INFO and VERBOSE log transactions that "
                    "server performs on behalf of the client. "
                    "f_is_debug specify higher levels of debugging output. "
                    "The default is f_info."),
    )
    stg_syslogserver = models.CharField(
        default='',
        blank=True,
        max_length=120,
        verbose_name=_("Syslog server"),
        help_text=_("Specifies the server and port syslog messages "
                    "will be sent to.  The accepted format is hostname:port "
                    "or ip:port, if :port is not specified it will default to "
                    "port 514 (this field currently only takes IPv4 addresses)"),
    )
    stg_wizardshown = models.BooleanField(
        editable=False,
        default=False,
    )
    stg_pwenc_check = models.CharField(
        max_length=100,
        editable=False,
    )

    class Meta:
        verbose_name = _("General")
示例#7
0
class User(AbstractBaseUser):
    phone_regex = RegexValidator(
        regex=r"^\+?1?\d{9,14}$",
        message=
        "Phone number must be entered in the format: '+999999999'. Up to 14 digits "
        "allowed. ")
    phone = models.CharField(validators=[phone_regex],
                             max_length=15,
                             unique=True)
    name = models.CharField(max_length=40, blank=True, null=True)
    email = models.EmailField(unique=True)
    surname = models.CharField(max_length=40, blank=True, null=True)
    is_subscribe = models.BooleanField(default=False)
    subscribe_days_count = models.IntegerField(default=0)
    subscribe_hours_count = models.IntegerField(
        default=0, validators=[MinValueValidator(0),
                               MaxValueValidator(24)])
    watched_list = models.ManyToManyField(HouseModel,
                                          related_name='watched_list',
                                          blank=True)
    fav_list = models.ManyToManyField(HouseModel,
                                      related_name='fav_list',
                                      blank=True)
    ignore_list = models.ManyToManyField(HouseModel,
                                         related_name='ignore_list',
                                         blank=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    is_partner = models.BooleanField(default=False)
    referral_code = models.IntegerField(default=0, null=True)
    parent_referral = models.ForeignKey('self',
                                        blank=True,
                                        null=True,
                                        on_delete=SET_NULL)
    all_discount_count = models.IntegerField(
        default=0, validators=[MinValueValidator(0),
                               MaxValueValidator(100)])
    commission_percentage = models.IntegerField(
        default=0, validators=[MinValueValidator(0),
                               MaxValueValidator(100)])
    commission_surcharge = models.IntegerField(default=0)
    USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = ['email']
    objects = MyUserManager()

    def __str__(self):
        return self.email + self.phone

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.admin
示例#8
0
class EntityFormset(forms.Form):
    """Used as base for formset on Intents tab"""

    def __init__(self, *args, **kwargs):
        """Get initial choices for the form"""

        entities = kwargs.pop('entities', [])

        super(EntityFormset, self).__init__(*args, **kwargs)

        self.fields['entity_name'].choices = [
            (entity['entity_name'], entity['entity_name']) for entity in entities
        ]

        # ”The formset is smart enough to ignore extra forms that were not
        # changed.” Make them dummy again and enable requirement checks.
        self.empty_permitted = False

    required = forms.BooleanField(
        label=_('Required'),
        initial=True,
        required=False,
    )

    clear_on_entry = forms.BooleanField(
        label=_('Clear on entry'),
        initial=True,
        required=False,
    )

    entity_name = forms.ChoiceField(
        label=_('Entity name'),
        widget=forms.Select()
    )

    n_prompts = forms.IntegerField(
        initial=3,
        label=_('N prompts'),
        validators=[
            MaxValueValidator(16),
            MinValueValidator(1)
        ],
        widget=forms.NumberInput(attrs={
            'max': 16,
            'min': 1,
            'required': True,
            'placeholder': _('ex. 3'),
        })
    )

    label = forms.CharField(
        label=_('Label'),
        validators=[RegexValidator(regex=SLUG_PATTERN)],
        widget=forms.TextInput(attrs={
            'pattern': SLUG_PATTERN,
            'maxlength': 250,
            'required': True,
            'placeholder': _('Unique label'),
            'title': _('Enter a valid “Label” consisting of letters, numbers, '
                       'underscores or hyphens.')
        })
    )

    lifetime_turns = forms.IntegerField(
        label=_('Lifetime <small class="fa fa-info-circle" data-toggle="tooltip"'
                ' title="This determines how many conversation turns this entity'
                ' will be stored in memory for.  Leave this empty if you would '
                'like it to stored indefinitely."></small>'),
        validators=[
            MaxValueValidator(LIFETIME_TURNS_MAX_LIMIT),
            MinValueValidator(LIFETIME_TURNS_MIN_LIMIT)
        ],
        required=False,
        widget=forms.NumberInput(attrs={
            'max': LIFETIME_TURNS_MAX_LIMIT,
            'min': LIFETIME_TURNS_MIN_LIMIT,
            'placeholder': _('∞'),
        })
    )

    prompts = forms.CharField(
        label=_('Prompts'),
        widget=forms.TextInput(attrs={
            'data-min-length': 1,
            'data-max-length': INTENT_TOKEN_CHARACTERS_LIMIT,
            'data-delimiter': settings.TOKENFIELD_DELIMITER,
            'data-tokenfield': True,
            'required': True,
            'placeholder': _('Add a user prompt'),
        })
    )

    def clean_lifetime_turns(self):
        """If field is empty treat it as -1 for limitless lifetime"""
        turns = self.cleaned_data['lifetime_turns']
        return -1 if turns == '' else turns

    def clean_prompts(self):
        """Split prompts"""
        prompts = self.cleaned_data['prompts'].split(
            settings.TOKENFIELD_DELIMITER
        )
        stripped_list = [item.strip() for item in prompts]
        return stripped_list
示例#9
0
class Employee(md.Model):
    '''
    Сотрудник компании
    '''
    class Meta():
        verbose_name = 'сотрудник'
        verbose_name_plural = 'сотрудники'
        ordering = ('last_name', 'first_name')

    class Manager(md.Manager):
        # поиск сотрудника по объекту пользователя
        def by_user(self, user):
            return self.filter(user__exact=user).first()

    class WorkingManager(Manager):
        def get_queryset(self):
            return super().get_queryset().exclude(fire_date__lt=today())

    # замена менеджера по умолчанию
    objects = Manager()
    working = WorkingManager()

    last_name = md.CharField('Фамилия', max_length=200, db_index=True)
    first_name = md.CharField('Имя', max_length=200)
    sur_name = md.CharField('Отчество', max_length=200, blank=True)
    user = md.OneToOneField(User,
                            null=True,
                            blank=True,
                            on_delete=md.SET_NULL,
                            verbose_name='Логин пользователя')
    division = md.ForeignKey(Division,
                             null=True,
                             on_delete=md.CASCADE,
                             verbose_name='Подразделение')
    position = md.ForeignKey(Position,
                             null=True,
                             on_delete=md.PROTECT,
                             verbose_name='Занимаемая должность')
    hire_date = md.DateField('Дата приема на работу')
    # если fire_date == None -- значит сейчас работает
    fire_date = md.DateField('Дата увольнения',
                             null=True,
                             blank=True,
                             default=None)
    is_3d = md.BooleanField('Участник системы 3D ?', default=False)
    business_k = md.FloatField(
        'Коэффициент участия в бизнесе',
        default=0.5,
        validators=[MinValueValidator(0),
                    MaxValueValidator(1)])
    birthday = md.DateField('День рождения',
                            null=True,
                            blank=True,
                            default=None)
    local_phone = md.CharField('Внутренний номер', max_length=10, blank=True)
    work_phone = PhoneNumberField('Телефон корпоративный', blank=True)
    mobile_phone = PhoneNumberField('Телефон мобильный', blank=True)

    def full_name(self):
        return f'{self.last_name} {self.first_name} {self.sur_name}'.rstrip()

    full_name.admin_order_field = 'last_name'
    full_name.short_description = 'ФИО'

    def salary(self):
        try:
            s = self.salary_set.latest().amount
        except Salary.DoesNotExist:
            s = None
        return s

    salary.short_description = 'Текущий оклад'

    def headed_division(self):
        return Division.objects.filter(head__exact=self).first()

    headed_division.short_description = 'Возглавляемое подразделение'

    def subordinates(self):
        hd_div = self.headed_division()
        # кроме уволенных
        return Employee.working.filter(
            division__exact=hd_div) if hd_div else ()

    subordinates.short_description = 'Подчиненные'

    def is_fired(self):
        return self.fire_date < today()

    def __str__(self):
        return self.full_name()

    def clean(self):
        self._validate_position()
        self._validate_fire_date()
        self._validate_birthday()

    def _validate_position(self):
        if self.position is None or self.division is None:
            return
        try:
            table_position = StaffingTable.objects.get(division=self.division,
                                                       position=self.position)
            # vacant positions + employee already in the same position > 0
            if table_position.vacant() + Employee.objects.filter(
                    id=self.id, division=self.division,
                    position=self.position).count() > 0:
                return
            raise ValidationError(
                f'Для подразделения {self.division} все должности {self.position} уже заняты в штатном расписании.'
            )
        except StaffingTable.DoesNotExist:
            raise ValidationError(
                f'Для подразделения {self.division} нет должности {self.position} в штатном расписании.'
            )

    def _validate_fire_date(self):
        try:
            if self.fire_date < self.hire_date:
                raise ValidationError(
                    f'Дата увольнения {self.fire_date:%d.%m.%Y} не может быть ранее \
                даты приема на работу {self.hire_date:%d.%m.%Y}')
        except TypeError:
            pass

    def _validate_birthday(self):
        try:
            if self.birthday > self.fire_date:
                raise ValidationError(
                    f'Дата рождения {self.birthday:%d.%m.%Y} не может быть позднее \
                даты увольнения {self.fire_date:%d.%m.%Y}')
        except TypeError:
            pass
        try:
            if self.birthday > self.hire_date:
                raise ValidationError(
                    f'Дата рождения {self.birthday:%d.%m.%Y} не может быть позднее \
                даты приема на работу {self.hire_date:%d.%m.%Y}, нельзя родиться на работе ;)'
                )
        except TypeError:
            pass
示例#10
0
class bsdUsers(Model):

    USERNAME_FIELD = 'bsdusr_username'
    REQUIRED_FIELDS = []

    bsdusr_uid = models.IntegerField(
        verbose_name=_("User ID"),
        validators=[MinValueValidator(0),
                    MaxValueValidator(4294967295)],
    )
    bsdusr_username = models.CharField(max_length=16,
                                       unique=True,
                                       default=_('User &'),
                                       verbose_name=_("Username"))
    bsdusr_unixhash = models.CharField(max_length=128,
                                       blank=True,
                                       default='*',
                                       verbose_name=_("Hashed UNIX password"))
    bsdusr_smbhash = models.CharField(max_length=128,
                                      blank=True,
                                      default='*',
                                      verbose_name=_("Hashed SMB password"))
    bsdusr_group = models.ForeignKey(bsdGroups,
                                     on_delete=models.SET(get_sentinel_group),
                                     verbose_name=_("Primary Group ID"))
    bsdusr_home = PathField(
        default="/nonexistent",
        verbose_name=_("Home Directory"),
        includes=["/root", "/nonexistent"],
    )
    bsdusr_shell = models.CharField(
        max_length=120,
        default='/bin/csh',
        verbose_name=_("Shell"),
        choices=choices.SHELL_CHOICES(),
    )
    bsdusr_full_name = models.CharField(max_length=120,
                                        verbose_name=_("Full Name"))
    bsdusr_builtin = models.BooleanField(
        default=False,
        editable=False,
        verbose_name=_("Built-in User"),
    )
    bsdusr_email = models.EmailField(verbose_name=_("E-mail"), blank=True)
    bsdusr_password_disabled = models.BooleanField(
        verbose_name=_("Disable password login"),
        default=False,
        help_text=_(
            'This disables all forms of password login, including for sharing.'
        ),
    )
    bsdusr_locked = models.BooleanField(
        verbose_name=_("Lock user"),
        default=False,
    )
    bsdusr_sudo = models.BooleanField(
        verbose_name=_("Permit Sudo"),
        default=False,
    )
    bsdusr_microsoft_account = models.BooleanField(
        verbose_name=_("Microsoft Account"), default=False)
    bsdusr_attributes = DictField(
        default=None,
        editable=False,
    )

    is_active = True
    is_staff = True
    objects = UserManager()

    @classmethod
    def has_root_password(cls):
        qs = cls.objects.filter(bsdusr_uid=0).exclude(bsdusr_unixhash='*')
        return qs.exists()

    @property
    def bsdusr_sshpubkey(self):
        keysfile = '%s/.ssh/authorized_keys' % self.bsdusr_home
        if not os.path.exists(keysfile):
            return ''
        try:
            with open(keysfile, 'r') as f:
                keys = f.read()
            return keys
        except:
            return ''

    class Meta:
        verbose_name = _("User")
        verbose_name_plural = _("Users")
        ordering = ['bsdusr_builtin', 'bsdusr_username']

    def __str__(self):
        return self.bsdusr_username

    def get_username(self):
        "Return the identifying username for this User"
        return getattr(self, self.USERNAME_FIELD)

    def natural_key(self):
        return (self.get_username(), )

    @property
    def is_anonymous(self):
        """
        Always returns False. This is a way of comparing User objects to
        anonymous users.
        """
        return False

    @property
    def is_authenticated(self):
        """
        Always return True. This is a way to tell if the user has been
        authenticated in templates.
        """
        return True

    def set_password(self, password):
        # Django auth backend calls set_password even if user doesnt exist
        if not self.bsdusr_username or not self.id:
            time.sleep(0.1)
            return
        unixhash, smbhash = notifier().user_changepassword(
            username=self.bsdusr_username,
            password=password,
        )
        self.bsdusr_unixhash = unixhash
        self.bsdusr_smbhash = smbhash

    def check_password(self, raw_password):
        # Only allow uid 0 for now
        if self.bsdusr_uid != 0:
            return False
        if self.bsdusr_unixhash:
            if self.bsdusr_unixhash == 'x' or self.bsdusr_unixhash == '*':
                return False
            if isinstance(raw_password, bytes):
                raw_password = raw_password.decode('utf-8')
            return crypt.crypt(raw_password, str(self.bsdusr_unixhash)) == str(
                self.bsdusr_unixhash)

    def delete(self, using=None, reload=True, delete_group=True):
        from freenasUI.services.models import CIFS
        if self.bsdusr_builtin is True:
            raise ValueError(
                _("User %s is built-in and can not be deleted!") %
                (self.bsdusr_username))
        notifier().user_deleteuser(self.bsdusr_username)
        if domaincontroller_enabled():
            Samba4().user_delete(self.bsdusr_username)
        try:
            gobj = self.bsdusr_group
            count = bsdGroupMembership.objects.filter(
                bsdgrpmember_group=gobj).count()
            count2 = bsdUsers.objects.filter(bsdusr_group=gobj).exclude(
                id=self.id).count()
            if delete_group and not gobj.bsdgrp_builtin and count == 0 and count2 == 0:
                gobj.delete(reload=False, pwdelete=False)
        except:
            log.warn('Failed to delete primary group of %s',
                     self,
                     exc_info=True)
        cifs = CIFS.objects.latest('id')
        if cifs:
            if cifs.cifs_srv_guest == self.bsdusr_username:
                cifs.cifs_srv_guest = 'nobody'
                cifs.save()
        super(bsdUsers, self).delete(using)
        if reload:
            notifier().reload("user")

    def save(self, *args, **kwargs):
        # TODO: Add last_login field
        if ('update_fields' in kwargs
                and 'last_login' in kwargs['update_fields']):
            kwargs['update_fields'].remove('last_login')
        super(bsdUsers, self).save(*args, **kwargs)
class StatusType(GeldigheidMixin, models.Model):
    """
    Generieke aanduiding van de aard van een STATUS

    Toelichting objecttype
    Zaken van eenzelfde zaaktype doorlopen alle dezelfde statussen, tenzij de zaak voortijdig
    beeëindigd wordt. Met STATUSTYPE worden deze statussen benoemd bij het desbetreffende
    zaaktype. De attribuutsoort ‘Doorlooptijd status’ is niet bedoeld om daarmee voor een
    individuele zaak de statussen te plannen maar om geïnteresseerden informatie te verschaffen
    over de termijn waarop normaliter een volgende status bereikt wordt.
    """
    statustype_omschrijving = models.CharField(
        _('omschrijving'),
        max_length=80,
        help_text=
        _('Een korte, voor de initiator van de zaak relevante, omschrijving van de aard van de STATUS van zaken van een ZAAKTYPE.'
          ))
    statustype_omschrijving_generiek = models.CharField(
        _('omschrijving generiek'),
        max_length=80,
        blank=True,
        null=True,
        help_text=
        _('Algemeen gehanteerde omschrijving van de aard van STATUSsen van het STATUSTYPE'
          ))
    # waardenverzameling is 0001 - 9999, omdat int('0001') == 1 als PositiveSmallIntegerField
    statustypevolgnummer = models.PositiveSmallIntegerField(
        _('statustypevolgnummer'),
        validators=[MinValueValidator(1),
                    MaxValueValidator(9999)],
        help_text=_(
            'Een volgnummer voor statussen van het STATUSTYPE binnen een zaak.'
        ))
    doorlooptijd_status = models.PositiveSmallIntegerField(
        _('doorlooptijd status'),
        blank=True,
        null=True,
        validators=[MinValueValidator(1),
                    MaxValueValidator(999)],
        help_text=
        _('De door de zaakbehandelende organisatie(s) gestelde norm voor de doorlooptijd voor het bereiken '
          'van statussen van dit STATUSTYPE bij het desbetreffende ZAAKTYPE, vanaf het bereiken van de voorafgaande status'
          ))
    checklistitem = models.ManyToManyField(
        'datamodel.CheckListItem',
        verbose_name=_('checklistitem'),
        blank=True,
        help_text=
        _('Te controleren aandachtspunt voorafgaand aan het bereiken van een status van het STATUSTYPE.'
          ))
    informeren = models.CharField(
        _('informeren'),
        max_length=1,
        choices=JaNee.choices,
        help_text=
        _('Aanduiding die aangeeft of na het zetten van een STATUS van dit STATUSTYPE de Initiator moet worden geïnformeerd over de statusovergang.'
          ))
    statustekst = models.CharField(
        _('statustekst'),
        max_length=1000,
        blank=True,
        null=True,
        help_text=
        _('De tekst die wordt gebruikt om de Initiator te informeren over het bereiken van een STATUS van dit STATUSTYPE bij het desbetreffende ZAAKTYPE.'
          ))
    toelichting = models.CharField(
        _('toelichting'),
        max_length=1000,
        blank=True,
        null=True,
        help_text=_('Een eventuele toelichting op dit STATUSTYPE.'))

    # TODO: deze relatie is gedefinieerd op RolType en heeft de volgende regel:
    #  De relatiesoort ontstaat en eindigt alleen (materiële historie) op een datum die gelijk is resp. een dag
    # ligt voor een Versiedatum van het gerelateerd zaaktype.er is een regel voor deze relatie
    roltypen = models.ManyToManyField(
        'datamodel.RolType',
        verbose_name=_('roltypen'),
        related_name='mag_zetten',
        help_text=
        _('De STATUSTYPEn die een betrokkene in een rol van dit ROLTYPE mag zetten.'
          ))
    is_van = models.ForeignKey(
        'datamodel.ZaakType',
        verbose_name=_('is van'),
        help_text=
        _('Het ZAAKTYPE van ZAAKen waarin STATUSsen van dit STATUSTYPE bereikt kunnen worden.'
          ))

    class Meta:
        mnemonic = 'STT'
        unique_together = ('is_van', 'statustypevolgnummer')
        verbose_name = _('Statustype')
        verbose_name_plural = _('Statustypen')
        ordering = unique_together

        filter_fields = (
            'is_van',
            'informeren',
        )
        ordering_fields = filter_fields
        search_fields = (
            'statustype_omschrijving',
            'statustype_omschrijving_generiek',
            'statustypevolgnummer',
        )

    def clean(self):
        """
        datum_begin_geldigheid:
        - De datum is gelijk aan een Versiedatum van het gerelateerde zaaktype.

        datum_einde_geldigheid:
        - De datum is gelijk aan of gelegen na de datum zoals opgenomen onder 'Datum begin geldigheid statusType’.
        - De datum is gelijk aan de dag voor een Versiedatum van het gerelateerde zaaktype.
        """
        datum_begin = self.datum_begin_geldigheid_date
        versiedatum = self.is_van.versiedatum_date

        if datum_begin != versiedatum:
            raise ValidationError(
                _("De datum_begin_geldigheid moet gelijk zijn aan een Versiedatum van het gerelateerde zaaktype."
                  ))

        if self.datum_einde_geldigheid:
            datum_einde = self.datum_einde_geldigheid_date

            if datum_einde < datum_begin:
                raise ValidationError(
                    _("'Datum einde geldigheid' moet gelijk zijn aan of gelegen na de datum zoals opgenomen onder 'Datum begin geldigheid’"
                      ))

            if datum_einde + timedelta(days=1) != versiedatum:
                raise ValidationError(
                    _("'Datum einde geldigheid' moet gelijk zijn aan de dag voor een Versiedatum van het gerelateerde zaaktype."
                      ))

    def __str__(self):
        return '{} - {}'.format(self.is_van, self.statustypevolgnummer)
示例#12
0
class LDAPRepository(BaseRepository):
    """ Class used to represent LDAP repository object

    ldap_host: IP Address used to contact LDAP server
    ldap_port: Port used to contact LDAP server
    ldap_protocol: LDAP protocol version
    ldap_encryption_scheme: Encryption scheme used by LDAP Server
    ldap_connection_dn: DN of LDAP service account
    ldap_password: password of LDAP service account
    ldap_base_dn: Base DN of LDAP filter
    ldap_user_scope: User LDAP search scope
    ldap_user_dn: User DN of LDAP filter (concatenated with Base DN)
    ldap_user_attr: Attribute which identify user (ex: SamAccountName)
    ldap_user_filter: User search filter
    ldap_user_account_locked_attr: Filter which permit to identify a locked
    account
    ldap_user_change_password_attr: Filter which permit to identify an expired
    password
    ldap_user_groups_attr: LDAP Attribute with list of group membership
    ldap_user_mobile_attr: LDAP attribute with user phone number
    ldap_user_email_attr: LDAP attribute with user email address
    ldap_group_scope: Group LDAP search scope
    ldap_group_dn: Group DN of LDAP filter (concatenated with Base DN)
    ldap_group_attr: Attribute which identify group
    ldap_group_filter: Group search filter
    ldap_group_member_attr: LDAP Attribute with list of users
    """
    """ * Connection related attributes * """
    host = models.TextField(
        verbose_name=_('Host'),
        help_text=_('IP Address of LDAP server')
    )
    port = models.PositiveIntegerField(
        verbose_name=_('Port'),
        default=389,
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
        help_text=_('Listening port of LDAP server')
    )
    protocol = models.PositiveIntegerField(
        verbose_name=_('Protocol'),
        default=LDAP_SCOPES_CHOICES[0][0],
        choices=LDAP_PROTO_CHOICES,
        help_text=_('Version of your LDAP protocol')
    )
    encryption_scheme = models.TextField(
        verbose_name=_("Encryption scheme"),
        default=LDAP_ENC_SCHEMES_CHOICES[0][0],
        choices=LDAP_ENC_SCHEMES_CHOICES,
        help_text=_('LDAP encryption scheme')
    )
    connection_dn = models.TextField(
        verbose_name=_("Service account DN"),
        help_text=_('DN used by Vulture to perform LDAP query')
    )
    dn_password = models.TextField(
        verbose_name=_("Service account password"),
        help_text=_('Password of service account')
    )
    base_dn = models.TextField(
        verbose_name=_("Base DN"),
        help_text=_('Location in the directory from  which the LDAP search begins')
    )
    """ * User search related attributes * """
    user_scope = models.PositiveIntegerField(
        verbose_name=_("User search scope"),
        default=LDAP_SCOPES_CHOICES[0][0],
        choices=LDAP_SCOPES_CHOICES,
        help_text=_('Deep of search operation')
    )
    user_dn = models.TextField(
        verbose_name=_("User DN"),
        help_text=_('Location in the directory from which the user LDAP search begins')
    )
    user_attr = models.TextField(
        verbose_name=_("User attribute"),
        default="uid",
        help_text=_('Attribute which identify user')
    )
    user_filter = models.TextField(
        verbose_name=_("User search filter"),
        default='(objectclass=person)',
        help_text=_('Filter used to found user. Ex: (objectClass=person)')
    )
    user_account_locked_attr = models.TextField(
        verbose_name=_("Account locked filter"),
        help_text=_('Filter used to identify if an  account is locked.  Ex: (lockoutTime>=1)')
    )
    user_change_password_attr = models.TextField(
        verbose_name=_("Need change password  filter"),
        help_text=_('Filter used to identify if an  account need to change its password. Ex:  (pwdLastSet=0)')
    )
    user_groups_attr = models.TextField(
        verbose_name=_("Group attribute"),
        help_text=_("Attribute which contains user's group list")
    )
    user_mobile_attr = models.TextField(
        verbose_name=_("Mobile attribute"),
        help_text=_("Attribute which contains user's mobile number")
    )
    user_email_attr = models.TextField(
        verbose_name=_("Email attribute"),
        help_text=_("Attribute which contains user's email address")
    )
    """ * Group search related attributes * """
    group_scope = models.PositiveIntegerField(
        verbose_name=_("Group search scope"),
        default=LDAP_SCOPES_CHOICES[0][0],
        choices=LDAP_SCOPES_CHOICES,
        help_text=_('Deep of search operation')
    )
    group_dn = models.TextField(
        verbose_name=_("Group DN"),
        help_text=_('Location in the directory from which the group LDAP search begins')
    )
    group_attr = models.TextField(
        default="cn",
        verbose_name=_("Group attribute"),
        help_text=_("Attribute which identify group")
    )
    group_filter = models.TextField(
        verbose_name=_("Group search filter"),
        default="(objectClass=groupOfNames)",
        help_text=_('Filter used to found group. Ex: (objectClass=group)')
    )
    group_member_attr = models.TextField(
        verbose_name=_("Members attribute"),
        default="member",
        help_text=_("Attribute which contains  list of group members")
    )

    @property
    def get_group_objectclass_value(self):
        regex = r"\(.*=(.*)\)"
        return re.findall(regex, self.group_filter)[0]

    @property
    def get_user_account_locked_attr(self):
        if self.user_account_locked_attr:
            regex = r"\((.*)=.*"
            return re.findall(regex, self.user_account_locked_attr)[0]
        return False

    @property
    def get_user_account_locked_value(self):
        if self.user_account_locked_attr:
            regex = r"\(.*=(.*)\)"
            return re.findall(regex, self.user_account_locked_attr)[0]
        return False

    @property
    def get_user_change_password_attr(self):
        if self.user_change_password_attr:
            regex = r"\((.*)=.*"
            return re.findall(regex, self.user_change_password_attr)[0]
        return False
    
    @property
    def get_user_change_password_value(self):
        if self.user_change_password_attr:
            regex = r"\(.*=(.*)\)"
            return re.findall(regex, self.user_change_password_attr)[0]
        return False

    def create_user_dn(self, user_name):
        return f"{self.user_attr}={user_name},{self.user_dn},{self.base_dn}"

    def create_group_dn(self, group_name):
        return f"{self.group_attr}={group_name},{self.group_dn},{self.base_dn}"

    def to_dict(self):
        return model_to_dict(self)

    def to_template(self):
        """  returns the attributes of the class """
        return {
            'id': str(self.id),
            'name': self.name
        }

    def to_html_template(self):
        """ Returns needed attributes for html rendering """
        return {
            'id': str(self.id),
            'name': self.name,
            'uri': "{}://{}:{}".format(self.encryption_scheme, self.host, self.port),
            'connection_dn': self.connection_dn,
            'base_dn': self.base_dn
        }

    # Do NOT forget this on all BaseRepository subclasses
    def save(self, *args, **kwargs):
        self.subtype = "LDAP"
        super().save(*args, **kwargs)

    def get_client(self):
        return LDAPClient(self)
示例#13
0
class CheckIn(CommonInfo):
    """CheckIn by teacher with student's family.

    In-school contact, phone call, or in-person visit.

    Three results:
    - a 1-10 score
    - text response of things learned
    - text response of ways to improve situation
    """
    date = models.DateTimeField(default=timezone.now,
                                help_text='Date of check-in.')

    teacher = models.ForeignKey(MyUser,
                                on_delete=models.CASCADE,
                                help_text='Person leading the check-in.')
    student = models.ForeignKey(
        Student,
        on_delete=models.CASCADE,
        help_text='Student that check-in is on behalf of.',
    )
    status = models.CharField(
        max_length=1,
        choices=(
            ('C', 'Completed'),
            ('U', 'Unreachable'),
            ('M', 'Left Message'),
        ),
        blank=False,
        help_text='Current status of check-in.',
    )
    mode = models.CharField(
        max_length=1,
        choices=(('P', 'Phone'), ('V', 'Visit'), ('I', 'In-Person'),
                 ('E', 'Email')),
        blank=False,
        help_text='Mode of communication for check-in.',
    )
    notify_school_admin = models.BooleanField(
        default=False,
        help_text='Should school administrator be notified?',
    )
    success_score = models.PositiveIntegerField(
        default=1,
        validators=[MaxValueValidator(10),
                    MinValueValidator(1)],
        help_text='Scale (1-10) of check-in success.',
    )
    info_learned = models.TextField(
        verbose_name='Information Gathered',
        null=True,
        blank=True,
        help_text=
        'Most important thing you learned about your mentee at your most recent mentoring check-in.',
    )
    info_better = models.TextField(
        verbose_name='Improvements for Future',
        null=True,
        blank=True,
        help_text='What could have made this mentor check-in better?',
    )

    @property
    def district(self):
        return self.student.district

    @property
    def school(self):
        return self.student.school

    @property
    def url(self):
        return reverse('checkin', args=[self.id])

    def __str__(self):
        return f'Check-in on {self.student} by {self.teacher} at {self.date}'
class ChildTannerStaging(ChildCrfModelMixin):

    """ A model completed by the user on tanner staging for infants 7 years or
        older at enrolment.
    """

    assessment_done = models.CharField(
        verbose_name='Was a tanner stage assessment performed?',
        max_length=3,
        choices=YES_NO)

    reasons_not_done = models.CharField(
        verbose_name='Why was tanner staging not performed?',
        max_length=25,
        null=True, blank=True)

    child_gender = models.CharField(
        verbose_name='Indicate participant gender',
        max_length=10,
        choices=GENDER_NA,
        default=NOT_APPLICABLE)

    breast_stage = models.CharField(
        verbose_name='What was the tanner stage for female breast',
        max_length=15,
        choices=TANNER_STAGES,
        default=NOT_APPLICABLE)

    pubic_hair_stage = models.CharField(
        verbose_name='What was the tanner stage for pubic hair',
        max_length=15,
        choices=TANNER_STAGES,
        default=NOT_APPLICABLE)

    manarche_dt_avail = models.CharField(
        verbose_name='Is the date of menarche available?',
        max_length=30,
        choices=MENARCHE_AVAIL,
        default=NOT_APPLICABLE)

    menarche_dt = models.DateField(
        verbose_name='Indicate the date of menarche',
        blank=True, null=True)

    menarche_dt_est = models.CharField(
        verbose_name='Is this date estimated',
        max_length=15,
        blank=True,
        null=True,
        choices=YES_NO_NA,
        default=NOT_APPLICABLE)

    male_gen_stage = models.CharField(
        verbose_name='What is the tanner stage for male genitalia',
        max_length=15,
        choices=TANNER_STAGES,
        default=NOT_APPLICABLE)

    testclr_vol_measrd = models.CharField(
        verbose_name='Was the testicular volume measured?',
        max_length=15,
        choices=YES_NO_NA,
        default=NOT_APPLICABLE)

    rgt_testclr_vol = models.DecimalField(
        verbose_name='Indicate the testicular volume of right testicle',
        null=True, blank=True,
        max_digits=4, decimal_places=2,
        validators=[MinValueValidator(1), MaxValueValidator(25)])

    lft_testclr_vol = models.DecimalField(
        verbose_name='Indicate the testicular volume of left testicle',
        null=True, blank=True,
        max_digits=4, decimal_places=2,
        validators=[MinValueValidator(1), MaxValueValidator(25)])

    class Meta(ChildCrfModelMixin.Meta):
        app_label = 'flourish_child'
        verbose_name = 'Child Tanner Staging'
        verbose_name_plural = 'Child Tanner Staging'
示例#15
0
class NTPServer(Model):
    ntp_address = models.CharField(
        verbose_name=_("Address"),
        max_length=120,
    )
    ntp_burst = models.BooleanField(
        verbose_name=_("Burst"),
        default=False,
        help_text=_(
            "When the server is reachable, send a burst of eight "
            "packets instead of the usual one. This is designed to improve"
            " timekeeping quality with the server command and s addresses."
        ),
    )
    ntp_iburst = models.BooleanField(
        verbose_name=_("IBurst"),
        default=True,
        help_text=_(
            "When the server is unreachable, send a burst of eight"
            " packets instead of the usual one. This is designed to speed "
            "the initial synchronization acquisition with the server "
            "command and s addresses."
        ),
    )
    ntp_prefer = models.BooleanField(
        verbose_name=_("Prefer"),
        default=False,
        help_text=_(
            "Marks the server as preferred. All other things being"
            " equal, this host will be chosen for synchronization among a "
            "set of correctly operating hosts."
        ),
    )
    ntp_minpoll = models.IntegerField(
        verbose_name=_("Min. Poll"),
        default=6,
        validators=[MinValueValidator(4)],
        help_text=_(
            "The minimum poll interval for NTP messages, as a "
            "power of 2 in seconds. Defaults to 6 (64 s), but can be "
            "decreased to a lower limit of 4 (16 s)"
        ),
    )
    ntp_maxpoll = models.IntegerField(
        verbose_name=_("Max. Poll"),
        default=10,
        validators=[MaxValueValidator(17)],
        help_text=_(
            "The maximum poll interval for NTP messages, as a "
            "power of 2 in seconds. Defaults to 10 (1,024 s), but can be "
            "increased to an upper limit of 17 (36.4 h)"
        ),
    )

    def __str__(self):
        return self.ntp_address

    def delete(self):
        super(NTPServer, self).delete()
        notifier().start("ix-ntpd")
        notifier().restart("ntpd")

    class Meta:
        verbose_name = _("NTP Server")
        verbose_name_plural = _("NTP Servers")
        ordering = ["ntp_address"]

    class FreeAdmin:
        icon_model = "NTPServerIcon"
        icon_object = "NTPServerIcon"
        icon_view = "ViewNTPServerIcon"
        icon_add = "AddNTPServerIcon"
示例#16
0
文件: models.py 项目: yuta2/netbox
class VLAN(ChangeLoggedModel, CustomFieldModel):
    """
    A VLAN is a distinct layer two forwarding domain identified by a 12-bit integer (1-4094). Each VLAN must be assigned
    to a Site, however VLAN IDs need not be unique within a Site. A VLAN may optionally be assigned to a VLANGroup,
    within which all VLAN IDs and names but be unique.

    Like Prefixes, each VLAN is assigned an operational status and optionally a user-defined Role. A VLAN can have zero
    or more Prefixes assigned to it.
    """
    site = models.ForeignKey(
        to='dcim.Site',
        on_delete=models.PROTECT,
        related_name='vlans',
        blank=True,
        null=True
    )
    group = models.ForeignKey(
        to='ipam.VLANGroup',
        on_delete=models.PROTECT,
        related_name='vlans',
        blank=True,
        null=True
    )
    vid = models.PositiveSmallIntegerField(
        verbose_name='ID',
        validators=[MinValueValidator(1), MaxValueValidator(4094)]
    )
    name = models.CharField(
        max_length=64
    )
    tenant = models.ForeignKey(
        to='tenancy.Tenant',
        on_delete=models.PROTECT,
        related_name='vlans',
        blank=True,
        null=True
    )
    status = models.CharField(
        max_length=50,
        choices=VLANStatusChoices,
        default=VLANStatusChoices.STATUS_ACTIVE
    )
    role = models.ForeignKey(
        to='ipam.Role',
        on_delete=models.SET_NULL,
        related_name='vlans',
        blank=True,
        null=True
    )
    description = models.CharField(
        max_length=100,
        blank=True
    )
    custom_field_values = GenericRelation(
        to='extras.CustomFieldValue',
        content_type_field='obj_type',
        object_id_field='obj_id'
    )

    tags = TaggableManager(through=TaggedItem)

    csv_headers = ['site', 'group_name', 'vid', 'name', 'tenant', 'status', 'role', 'description']
    clone_fields = [
        'site', 'group', 'tenant', 'status', 'role', 'description',
    ]

    STATUS_CLASS_MAP = {
        'active': 'primary',
        'reserved': 'info',
        'deprecated': 'danger',
    }

    class Meta:
        ordering = ('site', 'group', 'vid', 'pk')  # (site, group, vid) may be non-unique
        unique_together = [
            ['group', 'vid'],
            ['group', 'name'],
        ]
        verbose_name = 'VLAN'
        verbose_name_plural = 'VLANs'

    def __str__(self):
        return self.display_name or super().__str__()

    def get_absolute_url(self):
        return reverse('ipam:vlan', args=[self.pk])

    def clean(self):

        # Validate VLAN group
        if self.group and self.group.site != self.site:
            raise ValidationError({
                'group': "VLAN group must belong to the assigned site ({}).".format(self.site)
            })

    def to_csv(self):
        return (
            self.site.name if self.site else None,
            self.group.name if self.group else None,
            self.vid,
            self.name,
            self.tenant.name if self.tenant else None,
            self.get_status_display(),
            self.role.name if self.role else None,
            self.description,
        )

    @property
    def display_name(self):
        if self.vid and self.name:
            return "{} ({})".format(self.vid, self.name)
        return None

    def get_status_class(self):
        return self.STATUS_CLASS_MAP[self.status]

    def get_members(self):
        # Return all interfaces assigned to this VLAN
        return Interface.objects.filter(
            Q(untagged_vlan_id=self.pk) |
            Q(tagged_vlans=self.pk)
        ).distinct()
示例#17
0
class Email(Model):
    em_fromemail = models.CharField(
        max_length=120,
        verbose_name=_("From email"),
        help_text=_(
            "An email address that the system will use for the "
            "sending address for mail it sends, eg: [email protected]"
        ),
        default='',
    )
    em_outgoingserver = models.CharField(
        max_length=120,
        verbose_name=_("Outgoing mail server"),
        help_text=_(
            "A hostname or ip that will accept our mail, for "
            "instance mail.example.org, or 192.168.1.1"
        ),
        blank=True,
    )
    em_port = models.IntegerField(
        default=25,
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
        help_text=_(
            "An integer from 1 - 65535, generally will be 25, "
            "465, or 587"
        ),
        verbose_name=_("Port to connect to"),
    )
    em_security = models.CharField(
        max_length=120,
        choices=choices.SMTPAUTH_CHOICES,
        default="plain",
        help_text=_("encryption of the connection"),
        verbose_name=_("TLS/SSL")
    )
    em_smtp = models.BooleanField(
        verbose_name=_("Use SMTP Authentication"),
        default=False
    )
    em_user = models.CharField(
        blank=True,
        null=True,
        max_length=120,
        verbose_name=_("Username"),
        help_text=_("A username to authenticate to the remote server"),
    )
    em_pass = models.CharField(
        blank=True,
        null=True,
        max_length=120,
        verbose_name=_("Password"),
        help_text=_("A password to authenticate to the remote server"),
    )

    class Meta:
        verbose_name = _("Email")

    class FreeAdmin:
        deletable = False

    def __init__(self, *args, **kwargs):
        super(Email, self).__init__(*args, **kwargs)
        if self.em_pass:
            try:
                self.em_pass = notifier().pwenc_decrypt(self.em_pass)
            except:
                log.debug('Failed to decrypt email password', exc_info=True)
                self.em_pass = ''
        self._em_pass_encrypted = False

    def save(self, *args, **kwargs):
        if self.em_pass and not self._em_pass_encrypted:
            self.em_pass = notifier().pwenc_encrypt(self.em_pass)
            self._em_pass_encrypted = True
        return super(Email, self).save(*args, **kwargs)
示例#18
0
文件: models.py 项目: yuta2/netbox
class Service(ChangeLoggedModel, CustomFieldModel):
    """
    A Service represents a layer-four service (e.g. HTTP or SSH) running on a Device or VirtualMachine. A Service may
    optionally be tied to one or more specific IPAddresses belonging to its parent.
    """
    device = models.ForeignKey(
        to='dcim.Device',
        on_delete=models.CASCADE,
        related_name='services',
        verbose_name='device',
        null=True,
        blank=True
    )
    virtual_machine = models.ForeignKey(
        to='virtualization.VirtualMachine',
        on_delete=models.CASCADE,
        related_name='services',
        null=True,
        blank=True
    )
    name = models.CharField(
        max_length=30
    )
    protocol = models.CharField(
        max_length=50,
        choices=ServiceProtocolChoices
    )
    port = models.PositiveIntegerField(
        validators=[MinValueValidator(SERVICE_PORT_MIN), MaxValueValidator(SERVICE_PORT_MAX)],
        verbose_name='Port number'
    )
    ipaddresses = models.ManyToManyField(
        to='ipam.IPAddress',
        related_name='services',
        blank=True,
        verbose_name='IP addresses'
    )
    description = models.CharField(
        max_length=100,
        blank=True
    )
    custom_field_values = GenericRelation(
        to='extras.CustomFieldValue',
        content_type_field='obj_type',
        object_id_field='obj_id'
    )

    tags = TaggableManager(through=TaggedItem)

    csv_headers = ['device', 'virtual_machine', 'name', 'protocol', 'description']

    class Meta:
        ordering = ('protocol', 'port', 'pk')  # (protocol, port) may be non-unique

    def __str__(self):
        return '{} ({}/{})'.format(self.name, self.port, self.get_protocol_display())

    def get_absolute_url(self):
        return reverse('ipam:service', args=[self.pk])

    @property
    def parent(self):
        return self.device or self.virtual_machine

    def clean(self):

        # A Service must belong to a Device *or* to a VirtualMachine
        if self.device and self.virtual_machine:
            raise ValidationError("A service cannot be associated with both a device and a virtual machine.")
        if not self.device and not self.virtual_machine:
            raise ValidationError("A service must be associated with either a device or a virtual machine.")

    def to_csv(self):
        return (
            self.device.name if self.device else None,
            self.virtual_machine.name if self.virtual_machine else None,
            self.name,
            self.get_protocol_display(),
            self.port,
            self.description,
        )
示例#19
0
文件: oser.py 项目: nbeaver/FPbase
class OSERMeasurement(Authorable, TimeStampedModel):
    percent = models.FloatField(
        verbose_name="Percent Normal Cells",
        help_text="Percentage of 'normal' looking cells",
        blank=True,
        null=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)],
    )
    percent_stddev = models.FloatField(
        verbose_name="StdDev",
        help_text="Standard deviation of percent normal cells (if applicable)",
        blank=True,
        null=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)],
    )
    percent_ncells = models.IntegerField(
        blank=True,
        null=True,
        verbose_name="Number of cells for percent measurement",
        help_text="Number of cells analyzed in percent normal for this FP",
    )
    oserne = models.FloatField(
        verbose_name="OSER/NE ratio",
        help_text="Ratio of OSER to nuclear envelope (NE) fluorescence intensities",
        blank=True,
        null=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)],
    )
    oserne_stddev = models.FloatField(
        verbose_name="OSER/NE StdDev",
        help_text="Standard deviation of OSER/NE ratio (if applicable)",
        blank=True,
        null=True,
        validators=[MinValueValidator(0), MaxValueValidator(100)],
    )
    oserne_ncells = models.IntegerField(
        blank=True,
        null=True,
        verbose_name="Number of cells for OSER/NE measurement",
        help_text="Number of cells analyzed in OSER/NE this FP",
    )
    celltype = models.CharField(
        max_length=64,
        blank=True,
        verbose_name="Cell Type",
        help_text="e.g. COS-7, HeLa",
    )
    temp = models.FloatField(null=True, blank=True, verbose_name="Temperature")

    reference = models.ForeignKey(
        Reference,
        related_name="oser_measurements",
        verbose_name="Measurement Reference",
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        help_text="Reference where the measurement was made",
    )  # usually, the original paper that published the protein
    protein = models.ForeignKey(
        "Protein",
        related_name="oser_measurements",
        verbose_name="Protein",
        help_text="The protein on which this measurement was made",
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return "OSER: {} in {}".format(self.protein, self.reference.citation)

    class Meta:
        unique_together = (("protein", "reference"),)
示例#20
0
class Goal(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='assigned_goal')  #goal is assigned to a specific user
    organization = models.ForeignKey(
        Organization,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name="goal")  #goal is assigned to all users in an organization

    created_on = models.DateTimeField(default=timezone.now)
    created_by = models.ForeignKey(User,
                                   on_delete=models.SET_NULL,
                                   null=True,
                                   related_name='created_goal')

    title = models.CharField(max_length=75,
                             help_text="Does this goal have a specific name?",
                             default="")
    description = models.CharField(max_length=500,
                                   help_text="A short description of the goal",
                                   blank=True,
                                   null=True)

    hours = models.IntegerField(
        help_text="How many hours are wanted?",
        null=True,
        blank=True,
        validators=[MinValueValidator(1),
                    MaxValueValidator(100)])
    start = models.DateField(
        'Start date',
        help_text='Only hours after or on this date will count to this goal',
        blank=True,
        null=True)
    end = models.DateField(
        'End date',
        help_text='Only hours before or on this date will count to this goal',
        blank=True,
        null=True)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        if self.title:
            return self.title
        foo = ""
        if self.user:
            foo = str(self.user)
        elif self.organization:
            foo = str(self.organization)
        return "%s hour goal for %s" % (self.hours, foo)

    @property
    def logs(self):
        users = []
        if self.user:
            users = [self.user]
        elif self.organization:
            users = self.organization.member.all(
            ) | self.organization.moderator.all()

        logs = {}
        for u in users:
            log = u.log.all()
            if self.start:
                log = log.filter(start_date__gte=self.start)
            if self.end:
                log = log.filter(start_date__lte=self.end)
            logs[u] = log
        return logs

    @property
    def total(self):
        logs = self.logs
        total = {}
        for u in logs:
            t = datetime.timedelta(seconds=0)
            for i in [i.duration for i in logs[u]]:
                t += i
            total[u] = t
        return total

    @property
    def total_verified(self):
        logs = self.logs
        total = {}
        for u in logs:
            t = datetime.timedelta(seconds=0)
            for i in [
                    i.duration for i in logs[u].filter(verified__isnull=False)
            ]:
                t += i
            total[u] = t
        return total

    @property
    def completed_users(self):
        user_dict = self.total
        total = 0
        for time in user_dict.values():
            if time.total_seconds() / 60 / 60 > self.hours:
                total += 1
        return total

    @property
    def active(self):
        if (self.start and self.start > timezone.now().date()) or (
                self.end and self.end < timezone.now().date()):
            return False
        return True
示例#21
0
文件: models.py 项目: iZub1n/Chirrup
class Reaction(models.Model):
    user = models.ForeignKey(User, related_name='reactor', on_delete=models.CASCADE, null =True)
    post = models.ForeignKey(Post, related_name='posts', on_delete=models.CASCADE, null =True)
    type = models.IntegerField(validators=[MaxValueValidator(9), MinValueValidator(0)],default=0)
示例#22
0
class Book(models.Model):
    name = models.CharField(max_length=120)
    author = models.CharField(max_length=120)
    year_of_release = models.PositiveIntegerField(default=datetime.date.today().year, validators=[MinValueValidator(1100),MaxValueValidator(datetime.date.today().year)])
    isbn = ISBNField(clean_isbn=False)
    genre = models.CharField(max_length=100)
    borrowed = models.BooleanField(default=False)
    cover = models.ImageField(null=True, blank=True)
示例#23
0
def _min_max_validator(value, minvalue, maxvalue):
    validator_min = MinValueValidator(minvalue)
    validator_max = MaxValueValidator(maxvalue)
    validator_min(value)
    validator_max(value)
示例#24
0
class Player(models.Model):
    """
    Stores information about a player of a started game,
    related to :model `auth.User` and :model `Game`
    """
    COLOUR = [
        ('Yellow', 'Yellow'),
        ('Blue', 'Blue'),
        ('Green', 'Green'),
        ('Red', 'Red'),
    ]

    turn = models.IntegerField(
        validators=[MinValueValidator(1),
                    MaxValueValidator(4)])
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    colour = models.CharField(max_length=50, choices=COLOUR)
    victory_points = models.IntegerField(default=0,
                                         validators=[MinValueValidator(0)])

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['turn', 'game'],
                                    name='User with unique turn per game'),
            models.UniqueConstraint(fields=['colour', 'game'],
                                    name='User with unique colour per game'),
        ]

    def gain_resources(self, resource_name, amount):
        """
        A method for players to gain resources.
        Args:
        game: the game in which the owner is.
        owner: a player who will get the resources.
        resource_name: the type of resources to obtain.
        amount: the amount of resources to obtain.
        """
        for i in range(amount):
            Resource.objects.create(owner=self,
                                    game=self.game,
                                    name=resource_name,
                                    last_gained=True)

    def gain_resources_free(self, position):
        """
        """
        hexes = Hexe.objects.filter(board=self.game.board)
        for hexe in hexes:
            hexe_level = hexe.level
            hexe_index = hexe.index
            hexagon_neighbors = HexagonInfo(hexe_level, hexe_index)
            if position in hexagon_neighbors:
                if hexe.terrain != 'desert':
                    self.gain_resources(hexe.terrain, 1)

    def has_necessary_resources(self, action, gaven=''):
        """
        A method to check is the player has necessary resources for
        do the desired action.
        Args:
        @action: the action of the player
        @gave: optional, only used if the action is 'trade_bank'.
               It's the type of resource that the player want to get.
        """
        NECESSARY_RESOURCES = {
            'build_settlement': ['brick', 'lumber', 'wool', 'grain'],
            'build_road': ['brick', 'lumber'],
            'buy_card': ['ore', 'grain', 'wool']
        }
        if gaven:
            return Resource.objects.filter(owner=self, name=gaven).count() >= 4
        if action == 'upgrade_city':
            amount_ore = Resource.objects.filter(owner=self,
                                                 name='ore').count() >= 3
            amount_grain = Resource.objects.filter(owner=self,
                                                   name='grain').count() >= 2
            return amount_ore and amount_grain
        needed_resources = NECESSARY_RESOURCES[action]
        for resource in needed_resources:
            resource_exists = Resource.objects.filter(owner=self,
                                                      name=resource).exists()
            if (not resource_exists):
                return False
        return True

    def can_trade_bank(self):
        for resource in RESOURCE_TYPE:
            if self.has_necessary_resources('trade_bank', resource[0]):
                return True
        return False

    def delete_resources(self, action, gaven=''):
        """
        A method to delete the  necessary resources for
        do the desired action.
        Args:
        @action: the action of the player
        @gave: optional, only used if the action is 'trade_bank'.
               It's the type of resource that the player want to get.
        """
        if action == 'monopoly':
            count = Resource.objects.filter(owner=self, name=gaven).count()
            if count != 0:
                Resource.objects.filter(owner=self, name=gaven).delete()
            return count
        else:
            NECESSARY_RESOURCES = {
                'build_settlement': ['brick', 'lumber', 'wool', 'grain'],
                'upgrade_city': 3 * ['ore'] + 2 * ['grain'],
                'build_road': ['brick', 'lumber'],
                'trade_bank': [gaven for resource in range(4)],
                'buy_card': ['ore', 'grain', 'wool']
            }
            used_resources = NECESSARY_RESOURCES[action]
            for resource in used_resources:
                Resource.objects.filter(owner=self, name=resource)[0].delete()

    def check_my_road(self, level, index):
        """
        Returns True if there is one of the vertices of the player's paths
        matches the VertexPosition entered by it.
        """
        return Road.objects.filter(
            Q(owner=self, game=self.game, level_1=level, index_1=index)
            | Q(owner=self, game=self.game, level_2=level, index_2=index)
        ).exists()

    def check_roads_continuation(self, level1, index1, level2, index2):
        road_1 = Road.objects.filter(
            Q(owner=self, game=self.game, level_1=level1, index_1=index1)
            | Q(owner=self, game=self.game, level_2=level1, index_2=index1)
        ).exists()
        road_2 = Road.objects.filter(
            Q(owner=self, game=self.game, level_1=level2, index_1=index2)
            | Q(owner=self, game=self.game, level_2=level2, index_2=index2)
        ).exists()
        building_1 = Building.objects.filter(owner=self,
                                             game=self.game,
                                             level=level1,
                                             index=index1).exists()
        building_2 = Building.objects.filter(owner=self,
                                             game=self.game,
                                             level=level2,
                                             index=index2).exists()
        return road_1 or road_2 or building_1 or building_2

    def get_my_roads_and_buildings(self):
        """
        A function that obtains two set of vertex positions of
        the roads and buildings of a given player.
        Args:
        """
        roads = Road.objects.filter(owner=self)
        vertex_roads = set()
        for road in roads:
            vertex = (road.level_1, road.index_1)
            vertex_roads.add(vertex)
            vertex = (road.level_2, road.index_2)
            vertex_roads.add(vertex)
        buildings = Building.objects.filter(owner=self)
        vertex_buildings = set()
        for build in buildings:
            vertex = (build.level, build.index)
            vertex_buildings.add(vertex)
        return (vertex_roads, vertex_buildings)

    def posibles_settlements(self):
        """
        A function that obtains positions that a player might have
        available to build settlements on the board.
        Args:
        """
        (vertex_roads, vertex_buildings) = self.get_my_roads_and_buildings()
        # I get the vertices of my own roads that are not occupied by
        # my buildings
        available_vertex = vertex_roads - vertex_buildings
        potencial_buildings = list(available_vertex)
        potencial_buildings = [[pos[0], pos[1]] for pos in potencial_buildings]
        available_vertex = [[pos[0], pos[1]] for pos in available_vertex]
        # For each vertices check that their neighbors are not occupied,
        # if they are it can not be built (distance rule)
        for vertex in available_vertex:
            # Get the neighbors of a vertex position
            neighbors = VertexInfo(vertex[0], vertex[1])
            for neighbor in neighbors:
                # If there a building in one of the neighbors then
                # the vertex couldn't have a new building...
                if Building.objects.filter(level=neighbor[0],
                                           index=neighbor[1]).exists():
                    potencial_buildings.remove(vertex)
                    break
        return potencial_buildings

    def get_potencial_roads(self, available_vertex):
        """
        A function that receives a list of available vertices and
        returns a list of positions (ROAD_POSITIONS) in which roads
        can be constructed from the vertices given in the list
        Args:
        @avalaible_vertex: a list of vertex positions (objects)
        """
        potencial_roads = []
        for vertex in available_vertex:
            vertex = list(vertex)
            # Get the neighbors of a vertex
            neighbors = VertexInfo(vertex[0], vertex[1])
            for neighbor in neighbors:
                if not Road.objects.filter(
                        Q(level_1=vertex[0],
                          index_1=vertex[1],
                          level_2=neighbor[0],
                          index_2=neighbor[1])
                        | Q(level_2=vertex[0],
                            index_2=vertex[1],
                            level_1=neighbor[0],
                            index_1=neighbor[1])).exists():
                    new_road = [vertex, neighbor]
                    potencial_roads.append(new_road)
        return potencial_roads

    def has_settlements(self, level=None, index=None):
        if level and index:
            return Building.objects.filter(owner=self,
                                           name='settlement',
                                           game=self.game,
                                           level=level,
                                           index=index).exists()
        else:
            return Building.objects.filter(owner=self,
                                           name='settlement',
                                           game=self.game).exists()

    def posibles_upgrades(self):
        potencial_cities = []
        setllements = Building.objects.filter(owner=self,
                                              name='settlement',
                                              game=self.game)
        for settle in setllements:
            vertex = [settle.level, settle.index]
            potencial_cities.append(vertex)
        return potencial_cities

    def posible_roads(self):
        """
        A function that obtains positions that a player might have
        available to build roads on the board.
        Args:
        """
        (vertex_roads, vertex_buildings) = self.get_my_roads_and_buildings()
        available_vertex = vertex_buildings.union(vertex_roads)
        potencial_roads = self.get_potencial_roads(available_vertex)
        return potencial_roads

    def posibles_initial_roads(self):
        building = Building.objects.filter(owner=self).last()
        potencial_roads = []
        vertex = [building.level, building.index]
        neighbors = VertexInfo(vertex[0], vertex[1])
        for neighbor in neighbors:
            vertex_position = [neighbor[0], neighbor[1]]
            new_road = [vertex, vertex_position]
            potencial_roads.append(new_road)
        return potencial_roads

    def posibles_roads_card_road_building(self):
        """
        A function that obtains posistions that a player might have
        available to build the two roads using the Card road_building
        Args:
        @player: a player of a started game.
        """
        potencial_roads = self.posible_roads()
        new_positions = []
        for road in potencial_roads:
            new_positions.append(road[1])
        new_potencial_roads = self.get_potencial_roads(new_positions)
        total_roads = potencial_roads + new_potencial_roads
        # Remove the repeat road
        final_roads = total_roads
        for road in total_roads:
            invert_road = [road[1], road[0]]
            if invert_road in final_roads:
                final_roads.remove(invert_road)
        return final_roads

    def is_winner(self):
        points = self.victory_points
        card_vic_points = Card.objects.filter(game=self.game,
                                              owner=self,
                                              name='victory_point').count()
        total = points + card_vic_points
        if total < 10:
            return False
        user = User.objects.get(username=self.username)
        self.game.winner = user
        self.game.save()
        return True

    def gain_points(self, amount):
        self.victory_points += amount
        self.save()

    def select_card(self):
        available_cards = [('road_building', 'ROAD_BUILDING'),
                           ('victory_point', 'VICTORY_POINT'),
                           ('knight', 'KNIGHT')]
        deck = available_cards * 5
        shuffle(deck)
        card_name = choice(deck)
        new_card = Card(owner=self, game=self.game, name=card_name[0])
        new_card.save()

    def has_card(self, type_card):
        return Card.objects.filter(owner=self, name=type_card).exists()

    def get_players_to_steal(self, level, index):
        owners = set()
        neighbors = HexagonInfo(level, index)
        for neighbor in neighbors:
            if Building.objects.filter(level=neighbor[0],
                                       index=neighbor[1],
                                       game=self.game).exists():
                owner = Building.objects.get(level=neighbor[0],
                                             index=neighbor[1],
                                             game=self.game).owner
                if owner.username != self.username:
                    owners.add(owner.username.username)
        return list(owners)

    def use_card(self, card_type):
        Card.objects.filter(owner=self, name=card_type)[0].delete()

    def steal_to(self, choosen_player):
        user_to_steal = User.objects.get(username=choosen_player)
        player_to_steal = Player.objects.get(username=user_to_steal,
                                             game=self.game)
        resources_list = Resource.objects.filter(owner=player_to_steal)
        if len(resources_list) != 0:
            resource_to_steal = resources_list[randint(0,
                                                       len(resources_list) -
                                                       1)]
            resource_to_steal.owner = self
            resource_to_steal.last_gained = True
            resource_to_steal.save()

    def set_not_last_gained(self):
        """
        A method to remove resources as obtained in the last turn.
        Args:
        owner: the player who owns the resources.
        """
        # Get the last gained of the owner
        resources_last_gained = Resource.objects.filter(last_gained=True,
                                                        owner=self)
        # Set the resources to False in last_gained field
        if len(resources_last_gained) != 0:
            for resource in resources_last_gained:
                resource.last_gained = False
                resource.save()
示例#25
0
class Issue(models.Model):
    id = models.CharField(max_length=3, primary_key=True)
    name = models.CharField(max_length=50)
    fat = models.DecimalField(max_digits=7, decimal_places=4, validators=[validate_positive, MaxValueValidator(100)])
    snf = models.DecimalField(max_digits=7, decimal_places=4, validators=[validate_positive, MaxValueValidator(100)])
    type = models.CharField(max_length=1, choices=ISSUE_CHOICES)

    def __str__(self):
        return self.name
示例#26
0
class Current_Turn(models.Model):
    """
    Stores information about the state of a started game,
    the player who is playing at the moment, the dices values
    and if the robber has been moved. Related to :model `Game`
    and :model `auth.User`
    """
    GAME_STAGE = [('FIRST_CONSTRUCTION', 'FIRST_CONSTRUCTION'),
                  ('SECOND_CONSTRUCTION', 'SECOND_CONSTRUCTION'),
                  ('FULL_PLAY', 'FULL_PLAY')]
    ACTIONS = [('BUILD_SETTLEMENT', 'BUILD_SETTLEMENT'),
               ('BUILD_ROAD', 'BUILD_ROAD'),
               ('NON_BLOCKING_ACTION', 'NON_BLOCKING_ACTION')]
    game = models.OneToOneField(Game,
                                related_name='current_turn',
                                on_delete=models.CASCADE,
                                null=True)
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             related_name="user")
    game_stage = models.CharField(max_length=50,
                                  choices=GAME_STAGE,
                                  default='FULL_PLAY')
    last_action = models.CharField(max_length=50,
                                   choices=ACTIONS,
                                   default='NON_BLOCKING_ACTION')
    dices1 = models.IntegerField(
        null=True,
        validators=[MinValueValidator(1),
                    MaxValueValidator(6)],
        default=1)
    dices2 = models.IntegerField(
        null=True,
        validators=[MinValueValidator(1),
                    MaxValueValidator(6)],
        default=1)
    robber_moved = models.BooleanField(default=False)

    def throw_dice(self):
        """
        A function to generate a thow of dice
        (uniform discrete distribution).
        """
        return 1 * int(6 * random()) + 1

    def throw_two_dices(self, dice1=0, dice2=0):
        """
        A function to get the throw of two dices
        Params:
        @dice1: the value of the dice1 (used only for testing).
        @dice2: the value of the dice2 (used only for testing).
        """
        if (dice1 == 0) and (dice2 == 0):
            self.dices1 = self.throw_dice()
            self.dices2 = self.throw_dice()
            self.save()
            return self.get_dices()
        else:
            return (dice1, dice2)

    def get_dices(self):
        return (self.dices1, self.dices2)

    def set_new_turn(self):
        """
        A method to set a new player in turn on a given
        current turn of a started game.
        Args:
        @current_turn: a Current_Turn object of a started game.
        @ player: a player to set as new in the turn.
        """
        new_player = self.get_next_player()
        self.user = new_player.username
        self.last_action = 'NON_BLOCKING_ACTION'
        self.robber_moved = False
        self.save()

    def get_next_player(self):
        """
        A method to get the next player in the turn of a
        started game.
        Args:
        @current_turn: a Current_Turn object of a started game.
        @players: a queryset of the players of a started game.
        """
        player_in_turn = Player.objects.get(username=self.user, game=self.game)
        # Get the number of the actual turn
        actual_turn = player_in_turn.turn
        # Calculate the next turn in the game...
        # In the stage 'FIRST_CONSTRUCTION' and 'FULL_PLAY' the order
        # is the natural, and in the stage 'SECOND_CONSTRUCTION' the order
        # is the inverse
        game_stage = self.game_stage
        if game_stage == 'FIRST_CONSTRUCTION':
            if actual_turn != 4:
                next_turn = actual_turn + 1
            else:
                next_turn = actual_turn
                self.game_stage = 'SECOND_CONSTRUCTION'
                self.save()
        elif game_stage == 'SECOND_CONSTRUCTION':
            if actual_turn != 1:
                next_turn = actual_turn - 1
            else:
                next_turn = actual_turn
                self.game_stage = 'FULL_PLAY'
                self.game.throw_dices()
                self.save()
        else:
            if actual_turn == 4:
                next_turn = 1
            else:
                next_turn = actual_turn + 1
        # Get the player with the next turn
        next_player = Player.objects.get(turn=next_turn, game=self.game)
        return next_player
示例#27
0
class PlateSolvingSettings(models.Model):
    blind = models.BooleanField(
        default=True,
        null=False,
        verbose_name=_("Perform a blind solve"),
        help_text=
        _("Attempt to solve with no hints. In most cases this will work, but it will take longer."
          ),
    )

    scale_units = models.CharField(
        null=True,
        blank=True,
        max_length=16,
        choices=(
            ('degwidth', _("Width of the field in degrees")),
            ('arcminwidth', _("Width of the field in arcminutes")),
            ('arcsecperpix', _("Resolution of the field in arcseconds/pixel")),
        ),
        verbose_name=_("Field size units"),
        help_text=("The units for the min/max field size settings below."),
    )

    scale_min = models.DecimalField(
        null=True,
        blank=True,
        max_digits=8,
        decimal_places=3,
        verbose_name=_("Min field size"),
        help_text=_("Estimate the lower bound for the width of this field."),
    )

    scale_max = models.DecimalField(
        null=True,
        blank=True,
        max_digits=8,
        decimal_places=3,
        verbose_name=_("Max field size"),
        help_text=_("Estimate the upper bound for the width of this field."),
    )

    center_ra = models.DecimalField(
        null=True,
        blank=True,
        max_digits=7,
        decimal_places=3,
        validators=[MinValueValidator(0),
                    MaxValueValidator(360)],
        verbose_name=_("Center RA"),
        help_text=_("Center RA of the field in degrees, 0.000 to 360.000"),
    )

    center_dec = models.DecimalField(
        null=True,
        blank=True,
        max_digits=7,
        decimal_places=3,
        validators=[MinValueValidator(-90),
                    MaxValueValidator(90)],
        verbose_name=_("Center dec"),
        help_text=_("Center dec of the field in degrees, -90.000 to +90.000"),
    )

    radius = models.DecimalField(
        null=True,
        blank=True,
        max_digits=7,
        decimal_places=3,
        validators=[MinValueValidator(0),
                    MaxValueValidator(360)],
        verbose_name=_("Radius"),
        help_text=
        _("Tells the plate-solving engine to look within these many degrees of the given center RA and dec position."
          ),
    )
示例#28
0
class Workshop(TimeAuditModel):
    no_of_participants = models.PositiveIntegerField(
        validators=[MaxValueValidator(1000)])
    expected_date = models.DateField()
    description = models.TextField()
    requester = models.ForeignKey(Organisation,
                                  related_name='workshop_requester')
    presenter = models.ManyToManyField(User, related_name='workshop_presenter')
    # location = models.ForeignKey(Location, related_name='workshop_location')
    workshop_level = models.PositiveSmallIntegerField(
        choices=WorkshopLevel.CHOICES, verbose_name="Workshop Level")
    workshop_section = models.ForeignKey(WorkshopSections)
    number_of_volunteers = models.PositiveSmallIntegerField(default=0,
                                                            null=True,
                                                            blank=True)
    volunteer = models.ManyToManyField(User, related_name='workshop_volunteer')
    is_active = models.BooleanField(default=True)
    status = models.PositiveSmallIntegerField(choices=WorkshopStatus.CHOICES,
                                              verbose_name="Current Status",
                                              default=WorkshopStatus.REQUESTED)
    travel_reimbursement = models.PositiveSmallIntegerField(
        choices=YesNO.CHOICES,
        verbose_name="Travel Reimbursement Support",
        default=YesNO.NO)
    hotel_reimbursement = models.PositiveSmallIntegerField(
        choices=YesNO.CHOICES,
        verbose_name="Stay Reimbursement Support",
        default=YesNO.NO)
    budget = models.CharField(max_length=5, null=True)
    reimbursement_mode = models.TextField(null=True)
    tutor_reimbursement_flag = models.PositiveSmallIntegerField(
        choices=YesNO.CHOICES,
        verbose_name=" Do you need Travel/Stay reimbursement ?",
        default=YesNO.NO)
    comments = models.TextField()

    class Meta:
        db_table = 'workshops'

    def __str__(self):
        return '{}-{}'.format(self.requester, self.workshop_section)

    def save(self, force_insert=False, force_update=False, using=None):
        """
        send mail to region interested member whenever new workshop
        is requested in respective region, therefore overriding
        pre save method so mails are only send when new object
        is created.
        :param force_insert: bool force_insert
        :param force_update: bool force_insert
        :param using: using
        :return: instance
        """
        from wye.profiles.models import Profile
        if not self.id:
            domain = Site.objects.get_current().domain
            # get region_interested_member email ids to notify them
            region_interested_member = Profile.objects.filter(
                interested_locations=self.requester.location,
                usertype__slug='tutor').values_list('user__email', flat=True)

            if self and self.id:
                context = {
                    'workshop': self,
                    'date': self.expected_date,
                    'workshop_url': domain + '/workshop/{}/'.format(self.id),
                    'workshop_topic': self.workshop_section.name
                }
                subject = '[PythonExpress] Workshop request status.'
                email_body = loader.get_template(
                    'email_messages/workshop/create_workshop/message.html'
                ).render(context)
                text_body = loader.get_template(
                    'email_messages/workshop/create_workshop/message.txt'
                ).render(context)
                for email_id in region_interested_member:
                    send_email_to_id(subject,
                                     body=email_body,
                                     email_id=email_id,
                                     text_body=text_body)

        super(Workshop, self).save(force_insert, force_update, using)

    def is_presenter(self, user):
        return self.presenter.filter(pk=user.pk).exists()

    def is_organiser(self, user):
        return self.requester.user.filter(pk=user.pk).exists()

    def manage_action(self, user, **kwargs):
        actions = {
            'accept': ("opt-in", self.assign_me),
            'reject': ("opt-out", self.assign_me),
            'decline': (WorkshopStatus.REQUESTED, self.set_status),
            'publish': (WorkshopStatus.REQUESTED, self.set_status),
            'hold': (WorkshopStatus.HOLD, self.set_status),
            'assign': "",
            'opt-in-as-volunteer': '',
            'opt-out-as-volunteer': ''
        }
        if kwargs.get('action') not in actions:
            return {'status': False, 'msg': 'Action not allowed'}

        action, func = actions.get(kwargs.get('action'))
        kwargs["action"] = action
        return func(user, **kwargs)

    def set_status(self, user, **kwargs):
        self.status = kwargs.get('action')
        presenter_list = self.presenter.all()
        for u in presenter_list:
            self.presenter.remove(u)
        if kwargs.get('action') == WorkshopStatus.DECLINED:
            self.is_active = False
        else:
            self.is_active = True
        self.save()
        return {'status': True, 'msg': 'Workshop successfully updated.'}

    # @validate_action_param(WorkshopAction.ACTIVE)
    def toggle_active(self, user, **kwargs):
        """
        Helper method to toggle is_active for the model.
        """

        action_map = {'active': True, 'deactive': False}
        action = kwargs.get('action')
        self.is_active = action_map.get(action)
        self.save()
        return {'status': True, 'msg': 'Workshop successfully updated.'}

    # @validate_action_param(WorkshopAction.ASSIGNME)
    # @validate_assignme_action
    def assign_me(self, user, **kwargs):
        """
        Method to assign workshop by presenter self.
        """

        action_map = {
            'opt-in': self.presenter.add,
            'opt-out': self.presenter.remove
        }
        message_map = {
            'opt-in': 'Assigned successfully.',
            'opt-out': 'Unassigned successfully.'
        }
        assigned = {'opt-in': True, 'opt-out': False}
        action = kwargs.get('action')
        if assigned[action] and self.presenter.filter(pk=user.pk).exists():
            # This save has been added as fail safe
            # once the logic is consolidated may be
            # it can be removed
            self.status = WorkshopStatus.ACCEPTED
            self.save()
            return {
                'status': False,
                'msg': 'Workshop has already been assigned.'
            }

        func = action_map.get(action)
        func(user)

        if action == 'opt-out':
            self.number_of_volunteers = 0
            self.volunteer.clear()

        if self.presenter.count() > 0:
            self.status = WorkshopStatus.ACCEPTED
        else:
            self.status = WorkshopStatus.REQUESTED
        self.save()

        return {
            'status': True,
            'assigned': assigned[action],
            'msg': message_map[action],
            'notify': True
        }

    def get_presenter_list(self):
        return [user.get_full_name() for user in self.presenter.all()]

    def get_tweet(self, context):
        workshop = self
        try:
            date = workshop.expected_date.strftime('%d-%m-%Y')
        except:
            date = workshop.expected_date

        topic = workshop.workshop_section
        organization = workshop.requester
        location = workshop.requester.location
        workshop_url = context.get('workshop_url', None)
        message = "{} workshop at {} on {} confirmed! Details: {}".format(
            topic, organization, date, workshop_url)
        if len(message) >= 140:
            message = "{} workshop at {} on {} confirmed! Details: {}".format(
                topic, location, date, workshop_url)
        if len(message) >= 140:
            message = "{} workshop on {} confirmed! Details :{}".format(
                topic, date, workshop_url)

        return message

        def opt_in_as_volunteer(self):
            pass

        def opt_out_as_volunteer(self):
            pass
示例#29
0
class Pump(DimMassModelMixin):
    class PumpType(models.TextChoices):
        CENTRIFUGAL = "CEN", _("Центробежный")
        IMPELLER = "IMP", _("Импеллерный (ламельный)")
        LAMELLAR = "LAM", _("Пластинчатый (шиберный)")
        WATER_RING = "WAT", _("Водокольцевой")
        GEAR = "GEA", _("Шестерённый")
        AXIAL_PLUNGER = "AXI", _("Аксиально-плунжерный")
        RADIAL_PLUNGER = "RAD", _("Радиально-плунжерный")
        DISK = "DIS", _("Центробежно-шнековый (дисковый, оседиагональный)")
        SCREW = "SCR", _("Винтовой (шнековый)")
        PISTON = "PIS", _("Поршневой")
        VORTEX = "VOR", _("Вихревой")
        ROTARY = "ROT", _("Роторный")
        JET = "JET", _("Струйный")
        SINUSOIDAL = "SIN", _("Синусоидальный")
        PERISTALTIC = "PER", _("Перистальтический")
        MEMBRANE = "MEM", _("Мембранный")
        ABSORPTION = "ABS", _("Абсорбционный")
        HYDRAULIC_RAM = "HYD", _("Гидротаранный")
        MAGNETIC_DISCHARGE = "MAG", _("Магниторазрядный")

    PUMP_ACCURACY = (
        ("1B", "1B"),
        ("1E", "1E"),
        ("1U", "1U"),
        ("2B", "2B"),
        ("2U", "2U"),
        ("3B", "3B"),
    )

    manufacturer = models.ForeignKey(
        Manufacturer,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name=Manufacturer._meta.verbose_name)
    pump_accuracy = models.CharField("класс точности",
                                     max_length=2,
                                     choices=PUMP_ACCURACY,
                                     null=True,
                                     blank=True,
                                     default="2B")
    pump_type = models.CharField("тип",
                                 max_length=3,
                                 choices=PumpType.choices,
                                 default=PumpType.CENTRIFUGAL)
    pump_name = models.CharField("название", max_length=100)
    pump_code = models.CharField("артикул", max_length=50)
    flow_min = models.FloatField("производительность (мин.), м3/ч",
                                 null=True,
                                 blank=True,
                                 validators=[MinValueValidator(0.0)])
    flow_max = models.FloatField("производительность (макс.), м3/ч",
                                 null=True,
                                 blank=True,
                                 validators=[MinValueValidator(0.0)])
    eff_bep = models.FloatField(
        "КПД (макс.), %",
        null=True,
        blank=True,
        validators=[MinValueValidator(0.0),
                    MaxValueValidator(100)])
    flow_bep = models.FloatField("производительность (макс. КПД), м3/ч",
                                 null=True,
                                 blank=True,
                                 validators=[MinValueValidator(0.0)])
    temp_max = models.PositiveSmallIntegerField(
        "температура (макс.), \xb0C",
        null=True,
        blank=True,
        validators=[MinValueValidator(0.0)])
    head_max = models.FloatField("напор (макс.), м",
                                 null=True,
                                 blank=True,
                                 validators=[MinValueValidator(0.0)])
    rpm = models.PositiveSmallIntegerField("об/мин", null=True, blank=True)
    impeller_dia = models.FloatField("диаметр рабочего колеса, м",
                                     null=True,
                                     blank=True,
                                     validators=[MinValueValidator(0.0)])
    ip_code = models.CharField("степень защиты IP",
                               max_length=4,
                               choices=IP_CODE_CHOICES,
                               default="IP20")

    def __str__(self):
        return self.pump_code

    class Meta:
        verbose_name = "Насос"
        verbose_name_plural = "Насосы"
        db_table = "catalog_pump"

    def get_absolute_url(self):
        return reverse('pump-detail', args=[str(self.id)])
示例#30
0
class Payment(models.Model):
    """A model that represents a single payment.

    This might be a transactable payment information such as credit card
    details, gift card information or a customer's authorization to charge
    their PayPal account.

    All payment process related pieces of information are stored
    at the gateway level, we are operating on the reusable token
    which is a unique identifier of the customer for given gateway.

    Several payment methods can be used within a single order. Each payment
    method may consist of multiple transactions.
    """

    gateway = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    charge_status = models.CharField(max_length=20,
                                     choices=ChargeStatus.CHOICES,
                                     default=ChargeStatus.NOT_CHARGED)
    token = models.CharField(max_length=128, blank=True, default='')
    total = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,
                                decimal_places=settings.DEFAULT_DECIMAL_PLACES,
                                default=Decimal('0.0'))
    captured_amount = models.DecimalField(
        max_digits=settings.DEFAULT_MAX_DIGITS,
        decimal_places=settings.DEFAULT_DECIMAL_PLACES,
        default=Decimal('0.0'))
    currency = models.CharField(max_length=10)  # FIXME: add ISO4217 validator

    checkout = models.ForeignKey(Cart,
                                 null=True,
                                 related_name='payments',
                                 on_delete=models.SET_NULL)
    order = models.ForeignKey(Order,
                              null=True,
                              related_name='payments',
                              on_delete=models.PROTECT)

    billing_email = models.EmailField(blank=True)
    billing_first_name = models.CharField(max_length=256, blank=True)
    billing_last_name = models.CharField(max_length=256, blank=True)
    billing_company_name = models.CharField(max_length=256, blank=True)
    billing_address_1 = models.CharField(max_length=256, blank=True)
    billing_address_2 = models.CharField(max_length=256, blank=True)
    billing_city = models.CharField(max_length=256, blank=True)
    billing_city_area = models.CharField(max_length=128, blank=True)
    billing_postal_code = models.CharField(max_length=256, blank=True)
    billing_country_code = models.CharField(max_length=2, blank=True)
    billing_country_area = models.CharField(max_length=256, blank=True)

    cc_first_digits = models.CharField(max_length=6, blank=True, default='')
    cc_last_digits = models.CharField(max_length=4, blank=True, default='')
    cc_brand = models.CharField(max_length=40, blank=True, default='')
    cc_exp_month = models.PositiveIntegerField(
        validators=[MinValueValidator(1),
                    MaxValueValidator(12)],
        null=True,
        blank=True)
    cc_exp_year = models.PositiveIntegerField(
        validators=[MinValueValidator(1000)], null=True, blank=True)

    customer_ip_address = models.GenericIPAddressField(blank=True, null=True)
    extra_data = models.TextField(blank=True, default='')

    class Meta:
        ordering = ('pk', )

    def __repr__(self):
        return 'Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)' % (
            self.gateway, self.is_active, self.created, self.charge_status)

    def get_last_transaction(self):
        return max(self.transactions.all(), default=None, key=attrgetter('pk'))

    def get_total(self):
        return Money(self.total, self.currency or settings.DEFAULT_CURRENCY)

    def get_authorized_amount(self):
        money = zero_money()

        # Query all the transactions which should be prefetched
        # to optimize db queries
        transactions = self.transactions.all()

        # There is no authorized amount anymore when capture is succeeded
        # since capture can only be made once, even it is a partial capture
        if any([
                txn.kind == TransactionKind.CAPTURE and txn.is_success
                for txn in transactions
        ]):
            return money

        # Filter the succeeded auth transactions
        authorized_txns = [
            txn for txn in transactions
            if txn.kind == TransactionKind.AUTH and txn.is_success
        ]

        # Calculate authorized amount from all succeeded auth transactions
        for txn in authorized_txns:
            money += Money(txn.amount, self.currency
                           or settings.DEFAULT_CURRENCY)

        # If multiple partial capture is supported later though it's unlikely,
        # the authorized amount should exclude the already captured amount here
        return money

    def get_captured_amount(self):
        return Money(self.captured_amount, self.currency
                     or settings.DEFAULT_CURRENCY)

    def get_charge_amount(self):
        """Retrieve the maximum capture possible."""
        return self.total - self.captured_amount

    @property
    def is_authorized(self):
        return any([
            txn.kind == TransactionKind.AUTH and txn.is_success
            for txn in self.transactions.all()
        ])

    @property
    def not_charged(self):
        return self.charge_status == ChargeStatus.NOT_CHARGED

    def can_authorize(self):
        return self.is_active and self.not_charged

    def can_capture(self):
        return self.is_active and self.not_charged and self.is_authorized

    def can_charge(self):
        not_fully_charged = (
            self.charge_status == ChargeStatus.PARTIALLY_CHARGED)
        return self.is_active and (self.not_charged or not_fully_charged)

    def can_void(self):
        return self.is_active and self.not_charged and self.is_authorized

    def can_refund(self):
        can_refund_charge_status = (ChargeStatus.PARTIALLY_CHARGED,
                                    ChargeStatus.FULLY_CHARGED,
                                    ChargeStatus.PARTIALLY_REFUNDED)
        return (self.is_active
                and self.charge_status in can_refund_charge_status
                and self.gateway != CustomPaymentChoices.MANUAL)