Esempio n. 1
11
 def __init__(self):
   RegexValidator.__init__(self, '^[a-zA-Z]+$', _('Only latin characters'))
Esempio n. 2
0
class ScheduledScan(models.Model):
    """Model for a list of upcoming scans for a day."""

    SCAN_STATUS_CHOICES = (
        ("pending", "Pending"),
        ("started", "Started"),
        ("completed", "Completed"),
        ("error", "Error"),
    )

    id = models.AutoField(primary_key=True, verbose_name="Scheduled Scan ID")
    site_name = models.CharField(
        unique=False,
        max_length=255,
        validators=[
            RegexValidator(
                regex="^[a-zA-Z0-9/()_\- ]*$",  # Must escape -
                message=
                "Site name can only contain alphanumeric characters, /, (), -, _, or spaces",
            )
        ],
        verbose_name="Site Name",
    )
    start_time = models.TimeField(verbose_name="Scan start time")
    scan_agent = models.CharField(
        unique=False,
        max_length=255,
        validators=[
            RegexValidator(
                regex="^[a-zA-Z0-9/()_\- ]*$",  # Must escape -
                message=
                "Agent name can only contain alphanumeric characters, /, (), -, _, or spaces",
            )
        ],
        verbose_name="Agent Name",
    )
    start_datetime = models.DateTimeField(
        verbose_name="Scheduled scan start date and time")
    scan_binary = models.CharField(max_length=7,
                                   default="nmap",
                                   verbose_name="Scan binary")
    scan_command = models.TextField(unique=False, verbose_name="Scan command")
    targets = models.CharField(
        unique=False,
        max_length=1_048_576,  # 2^20 = 1048576
        validators=[
            RegexValidator(
                regex=
                "^[a-zA-Z0-9/\.\: ]*$",  # Characters to support IPv4, IPv6, and FQDNs only.  Space delimited.
                message=
                "Targets can only contain alphanumeric characters, /, ., :, and spaces",
            )
        ],
        verbose_name="Targets",
    )
    excluded_targets = models.CharField(
        unique=False,
        blank=True,
        max_length=1_048_576,  # 2^20 = 1048576
        validators=[
            RegexValidator(
                regex=
                "^[a-zA-Z0-9/\.\: ]*$",  # Characters to support IPv4, IPv6, and FQDNs only.  Space delimited.
                message=
                "Excluded targets can only contain alphanumeric characters, /, ., :, and spaces",
            )
        ],
        verbose_name="Excluded targets",
    )
    scan_status = models.CharField(max_length=9,
                                   choices=SCAN_STATUS_CHOICES,
                                   default="pending",
                                   verbose_name="Scan status")
    completed_time = models.DateTimeField(null=True,
                                          blank=True,
                                          verbose_name="Scan completion time")
    result_file_base_name = models.CharField(
        max_length=255, blank=False, verbose_name="Result file base name")

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

    class Meta:
        verbose_name_plural = "Scheduled Scans"
Esempio n. 3
0
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
import re

RESOURCE_VM_RE = "^([0-9a-zA-Z\-]){1,64}$"

def validate_discImage(value):
    from vt_plugin.models.VM import DISC_IMAGE_CHOICES
    if value not in [x[0] for x in DISC_IMAGE_CHOICES]:
        raise ValidationError("Invalid input: only test image available")

def validate_hdSetupType(value):
    from vt_plugin.models.VM import HD_SETUP_TYPE_CHOICES 
    if value not in [x[0] for x in HD_SETUP_TYPE_CHOICES]:
        raise ValidationError("Invalid input: only File Image supported")

def validate_memory(value):
    if value < 128:
        raise ValidationError("Invalid input: memory has to be higher than 128Mb")

def validate_virtualizationSetupType(value):
    from vt_plugin.models.VM import VIRTUALIZATION_SETUP_TYPE_CHOICES 
    if value not in [x[0] for x in VIRTUALIZATION_SETUP_TYPE_CHOICES]:
        raise ValidationError("Invalid input: only Paravirtualization supported")

resourceVMNameValidator = RegexValidator(re.compile(RESOURCE_VM_RE),
                        u"Please do not use accented characters, symbols, underscores or whitespaces.",
                        "invalid")

Esempio n. 4
0
 def __init__(self, **kwargs):
     kwargs["max_length"] = 9
     super(HexColorField, self).__init__(**kwargs)
     self.validators.append(RegexValidator("^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$", _("Invalid color")))
Esempio n. 5
0
#encoding:utf-8

import re
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

username_re = re.compile(r'([\w]{9}|[a-zA-Z]{1}[\w]+?)$')
username = RegexValidator(username_re, u'学生:学号,管理员:6-12位, 由字母数字或下划线组成,首字符为字母',
                          'invalid')

password_re = re.compile(r'^[\w]+?$')
password = RegexValidator(password_re, u'密码由字母数字下划线组成的字符串,最少为6位', 'invalid')

classid_re = re.compile(r'^[\w]{7}$')
classid = RegexValidator(classid_re, u'班号由7位数数字组成', 'invalid')

classname_re = re.compile(r'^[\u4e00-\u9fa5]{2,6}$')


class ClassnameValidator(object):
    message = u'班级姓名必须是2-6个汉字'
    code = 'invalid'

    def __init__(self, message=None, code=None):
        if message is not None:
            self.message = message
        if code is not None:
            self.code = code

    def __call__(self, value):
        if not all([
Esempio n. 6
0
from django.core.validators import RegexValidator, slug_re
from django.utils.translation import gettext_lazy as _

validate_short_url = RegexValidator(
    slug_re,
    _('Enter a valid “Short URL” consisting of letters, numbers, underscores or hyphens.'
      ), 'invalid')
Esempio n. 7
0
class SignUpSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField(
        help_text='Required. 30 characters or fewer. Alphanumerics only.',
        max_length=30,
        validators=[
            RegexValidator(
                regex='^[a-zA-Z0-9_-]{3,31}$',
                message='No Special Symbols/Spaces allowed.Alphanumerics only',
                code='invalid'),
            UniqueValidator(queryset=MyUser.objects.all())
        ])
    password = serializers.CharField(max_length=128,
                                     style={'input_type': 'password'},
                                     write_only=True)
    email = serializers.EmailField(
        label='Email address',
        max_length=254,
        required=True,
        validators=[
            UniqueValidator(
                queryset=MyUser.objects.all(),
                message='This email has been taken.Please choose another one.')
        ])
    first_name = serializers.CharField(allow_blank=True,
                                       max_length=30,
                                       required=False)
    last_name = serializers.CharField(allow_blank=True,
                                      max_length=30,
                                      required=False)
    dob = serializers.DateField(required=True)
    gender = serializers.CharField(
        max_length=2,
        required=True,
        validators=[
            RegexValidator(
                regex='^([M|m]|[F|f])$',
                message='Please input M or F only. M for Male, F for Female',
                code='invalid')
        ])
    auth_token = TokenSerializer(read_only=True)

    class Meta:
        model = MyUser
        fields = (
            'id',
            'username',
            'password',
            'email',
            'first_name',
            'last_name',
            'dob',
            'gender',
            'auth_token',
        )

    def create(self, validated_data):
        user = MyUser.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        Token.objects.get_or_create(user=user)
        return user

    def update(self, instance, validated_data):
        instance.username = validated_data.get('username', instance.username)
        instance.email = validated_data.get('email', instance.email)
        instance.first_name = validated_data.get('first_name',
                                                 instance.first_name)
        instance.last_name = validated_data.get('last_name',
                                                instance.last_name)
        instance.dob = validated_data.get('dob', instance.dob)
        instance.gender = validated_data.get('gender', instance.gender)
        token_data = validated_data.pop('auth_token')
        auth_token = instance.auth_token
        # Unless the application properly enforces that this field is
        # always set, the follow could raise a `DoesNotExist`, which
        # would need to be handled.
        instance.auth_token = validated_data.get('auth_token',
                                                 instance.auth_token)
        auth_token.key = token_data.get('key', auth_token.key)
        auth_token.created = token_data.get('created', auth_token.created)
        instance.save()
        return instance
Esempio n. 8
0
def validate_captcha(value):
    """Validate Captcha"""
    regexObj = re.compile('^\w{6}$')
    obj = RegexValidator(regexObj, _('Validation error. Captcha text expected.'))
    obj.__call__(value)
Esempio n. 9
0
class UserProfile(models.Model):
    """Definition of UserProfile Model."""
    user = models.OneToOneField(User)
    registration_complete = models.BooleanField(default=False)
    date_joined_program = models.DateField(blank=True)
    date_left_program = models.DateField(blank=True, null=True)
    local_name = models.CharField(max_length=100, blank=True, default='')
    birth_date = models.DateField(validators=[_validate_birth_date],
                                  blank=True, null=True)
    city = models.CharField(max_length=50, blank=False, default='')
    region = models.CharField(max_length=50, blank=False, default='')
    country = models.CharField(max_length=50, blank=False, default='')
    lon = models.FloatField(blank=False, null=True)
    lat = models.FloatField(blank=False, null=True)
    display_name = models.CharField(
        max_length=DISPLAY_NAME_MAX_LENGTH, blank=True, default='',
        unique=True,
        validators=[
            RegexValidator(regex=r'("")|(^[A-Za-z0-9_]+$)',
                           message='Please only A-Z characters, numbers and '
                                   'underscores.')])
    private_email = models.EmailField(blank=False, null=True, default='')
    mozillians_profile_url = models.URLField(
        validators=[
            RegexValidator(regex=r'^http(s)?://(www\.)?mozillians.org/',
                           message='Please provide a valid Mozillians url.')])
    twitter_account = models.CharField(
        max_length=16, default='', blank=True,
        validators=[
            RegexValidator(regex=r'("^$")|(^[A-Za-z0-9_]+$)',
                           message='Please provide a valid Twitter handle.')])
    jabber_id = models.CharField(max_length=50, blank=True, default='')
    irc_name = models.CharField(max_length=50, blank=False, default='')
    irc_channels = models.TextField(blank=True, default='')
    linkedin_url = models.URLField(
        blank=True, null=False, default='',
        validators=[
            RegexValidator(regex=r'("^$")|(^http(s)?://(.*?)linkedin.com/)',
                           message='Please provide a valid LinkedIn url.')])
    facebook_url = models.URLField(
        blank=True, null=False, default='',
        validators=[
            RegexValidator(regex=r'("^$")|(^http(s)?://(.*?)facebook.com/)',
                           message='Please provide a valid Facebook url.')])
    diaspora_url = models.URLField(blank=True, null=False, default='')
    personal_website_url = models.URLField(blank=True, null=False, default='')
    personal_blog_feed = models.URLField(blank=True, null=False, default='')
    wiki_profile_url = models.URLField(
        blank=True, null=False, default='',
        validators=[
            RegexValidator(regex=r'^http(s)?://wiki.mozilla.org/User:'******'Please provide a valid wiki url.')])
    added_by = models.ForeignKey(User, null=True, blank=True,
                                 related_name='users_added')
    bio = models.TextField(blank=True, default='')
    gender = models.NullBooleanField(choices=((None, 'Gender'),
                                              (True, 'Female'),
                                              (False, 'Male')),
                                     default=None)
    mentor = models.ForeignKey(User, null=True, blank=True,
                               related_name='mentees',
                               validators=[_validate_mentor],
                               on_delete=models.SET_NULL)
    functional_areas = models.ManyToManyField(
        FunctionalArea, related_name='users_matching')
    mobilising_skills = models.ManyToManyField(
        MobilisingSkill, related_name='users_matching_skills',
        blank=True)
    mobilising_interests = models.ManyToManyField(
        MobilisingInterest, related_name='users_matching_interests',
        blank=True)
    tracked_functional_areas = models.ManyToManyField(
        FunctionalArea, related_name='users_tracking')
    receive_email_on_add_comment = models.BooleanField(null=False,
                                                       blank=True,
                                                       default=True)
    receive_email_on_add_event_comment = models.BooleanField(null=False,
                                                             blank=True,
                                                             default=True)
    receive_email_on_add_voting_comment = models.BooleanField(null=False,
                                                              blank=True,
                                                              default=True)
    mozillian_username = models.CharField(blank=True, default='',
                                          max_length=40)
    current_streak_start = models.DateField(null=True, blank=True)
    longest_streak_start = models.DateField(null=True, blank=True)
    longest_streak_end = models.DateField(null=True, blank=True)
    first_report_notification = models.DateField(null=True, blank=True)
    second_report_notification = models.DateField(null=True, blank=True)
    timezone = models.CharField(max_length=100, blank=True, default='')
    unavailability_task_id = models.CharField(max_length=256, blank=True,
                                              null=True, editable=False,
                                              default='')
    is_rotm_nominee = models.BooleanField(default=False)
    rotm_nominated_by = models.ForeignKey(User, null=True, blank=True,
                                          related_name='rotm_nominations',
                                          validators=[_validate_mentor],
                                          on_delete=models.SET_NULL)
    action_items = generic.GenericRelation('dashboard.ActionItem')

    class Meta:
        permissions = (('create_user', 'Can create new user'),
                       ('can_edit_profiles', 'Can edit profiles'),
                       ('can_delete_profiles', 'Can delete profiles'),
                       ('can_change_mentor', 'Can change mentors'))

    def get_absolute_url(self):
        return reverse('remo.profiles.views.view_profile',
                       kwargs={'display_name': self.display_name})

    @property
    def get_age(self):
        """Return the age of the user as an integer.

        Age gets calculated from birth_date variable.
        Snippet from http://djangosnippets.org/snippets/557/

        """
        d = timezone.now().date()
        age = ((d.year - self.birth_date.year)
               - int((d.month, d.day)
                     < (self.birth_date.month, self.birth_date.day)))
        return age

    def clean(self, *args, **kwargs):
        """Ensure that added_by variable does not have the same value as
        user variable.

        """
        if self.added_by == self.user:
            raise ValidationError('Field added_by cannot be the same as user.')

        return super(UserProfile, self).clean(*args, **kwargs)

    def get_action_items(self):
        """Return a list of Action Items relevant to this model."""

        today = timezone.now().date()
        due_date = datetime.date(today.year, today.month, NOMINATION_END_DAY)
        name = u'{0} {1}'.format(NOMINATION_ACTION_ITEM, today.strftime('%B'))
        priority = ActionItem.NORMAL
        action_item = Item(name, self.user, priority, due_date)

        return [action_item]
Esempio n. 10
0
class Tag(MetricsModelMixin("tag"), models.Model):
    TAG_VALIDATOR = RegexValidator(r"^[- _'\w]{1,50}$")
    value = models.CharField(max_length=50, validators=[TAG_VALIDATOR])

    def __str__(self):
        return self.value
Esempio n. 11
0
from django.core.validators import RegexValidator
from django.db import models
from django import forms
from django.utils.translation import ugettext_lazy as _


class UnboundedCharField(models.TextField):
    """Unlimited text, on a single line.

    Shows an ``<input type="text">`` in HTML but is stored as a TEXT
    column in Postgres (like ``TextField``).

    Like the standard :class:`~django.db.models.fields.CharField` widget,
    a ``select`` widget is automatically used if the field defines ``choices``.
    """
    def formfield(self, **kwargs):
        kwargs['widget'] = None if self.choices else forms.TextInput
        return super(UnboundedCharField, self).formfield(**kwargs)


validate_dotted_slug = RegexValidator(
    re.compile(r'^[-a-zA-Z0-9_.]+\Z'),
    _("Enter a valid 'slug' consisting of letters, numbers, underscores, dots or hyphens."
      ), 'invalid')


class DottedSlugField(models.CharField):
    """Slug field which allows dot"""
    default_validators = [validate_dotted_slug]
Esempio n. 12
0
class Request(models.Model):
    district = models.CharField(max_length=15,
                                choices=districts,
                                verbose_name='District - ജില്ല')
    location = models.CharField(max_length=500,
                                verbose_name='Location - സ്ഥലം')
    requestee = models.CharField(max_length=100,
                                 verbose_name='Requestee - അപേക്ഷകന്റെ പേര്')

    phone_number_regex = RegexValidator(
        regex='^((\+91|91|0)[\- ]{0,1})?[456789]\d{9}$',
        message=
        'Please Enter 10/11 digit mobile number or landline as 0<std code><phone number>',
        code='invalid_mobile')
    requestee_phone = models.CharField(
        max_length=14,
        verbose_name='Requestee Phone - അപേക്ഷകന്റെ ഫോണ്‍ നമ്പര്‍',
        validators=[phone_number_regex])

    latlng = models.CharField(
        max_length=100,
        verbose_name='GPS Coordinates - GPS നിർദ്ദേശാങ്കങ്ങൾ ',
        blank=True)
    latlng_accuracy = models.CharField(
        max_length=100, verbose_name='GPS Accuracy - GPS കൃത്യത ', blank=True)
    #  If it is enabled no need to consider lat and lng
    is_request_for_others = models.BooleanField(
        verbose_name=
        'Requesting for others - മറ്റൊരാൾക്ക് വേണ്ടി അപേക്ഷിക്കുന്നു ',
        default=False)

    needwater = models.BooleanField(verbose_name='Water - വെള്ളം')
    needfood = models.BooleanField(verbose_name='Food - ഭക്ഷണം')
    needcloth = models.BooleanField(verbose_name='Clothing - വസ്ത്രം')
    needmed = models.BooleanField(verbose_name='Medicine - മരുന്നുകള്‍')
    needtoilet = models.BooleanField(
        verbose_name='Toiletries - ശുചീകരണ സാമഗ്രികള്‍ ')
    needkit_util = models.BooleanField(
        verbose_name='Kitchen utensil - അടുക്കള സാമഗ്രികള്‍')
    needrescue = models.BooleanField(
        verbose_name='Need rescue - രക്ഷാപ്രവർത്തനം ആവശ്യമുണ്ട്')

    detailwater = models.CharField(
        max_length=250,
        verbose_name=
        'Details for required water - ആവശ്യമായ വെള്ളത്തിന്റെ വിവരങ്ങള്‍',
        blank=True)
    detailfood = models.CharField(
        max_length=250,
        verbose_name=
        'Details for required food - ആവശ്യമായ ഭക്ഷണത്തിന്റെ വിവരങ്ങള്‍',
        blank=True)
    detailcloth = models.CharField(
        max_length=250,
        verbose_name=
        'Details for required clothing - ആവശ്യമായ വസ്ത്രത്തിന്റെ വിവരങ്ങള്‍',
        blank=True)
    detailmed = models.CharField(
        max_length=250,
        verbose_name=
        'Details for required medicine - ആവശ്യമായ മരുന്നിന്റെ  വിവരങ്ങള്‍',
        blank=True)
    detailtoilet = models.CharField(
        max_length=250,
        verbose_name=
        'Details for required toiletries - ആവശ്യമായ  ശുചീകരണ സാമഗ്രികള്‍',
        blank=True)
    detailkit_util = models.CharField(
        max_length=250,
        verbose_name=
        'Details for required kitchen utensil - ആവശ്യമായ അടുക്കള സാമഗ്രികള്‍',
        blank=True)
    detailrescue = models.CharField(
        max_length=250,
        verbose_name='Details for rescue action - രക്ഷാപ്രവർത്തനം വിവരങ്ങള്',
        blank=True)

    needothers = models.CharField(
        max_length=500,
        verbose_name="Other needs - മറ്റു ആവശ്യങ്ങള്‍",
        blank=True)
    status = models.CharField(max_length=10,
                              choices=status_types,
                              default='new')
    supply_details = models.CharField(max_length=100, blank=True)
    dateadded = models.DateTimeField(auto_now_add=True)

    def summarise(self):
        out = ""
        if (self.needwater):
            out += "Water Requirements :\n {}".format(self.detailwater)
        if (self.needfood):
            out += "\nFood Requirements :\n {}".format(self.detailfood)
        if (self.needcloth):
            out += "\nCloth Requirements :\n {}".format(self.detailcloth)
        if (self.needmed):
            out += "\nMedicine Requirements :\n {}".format(self.detailmed)
        if (self.needtoilet):
            out += "\nToilet Requirements :\n {}".format(self.detailtoilet)
        if (self.needkit_util):
            out += "\nKit Requirements :\n {}".format(self.detailkit_util)
        if (self.needrescue):
            out += "\nRescue Action :\n {}".format(self.detailrescue)
        if (len(self.needothers.strip()) != 0):
            out += "\nOther Needs :\n {}".format(self.needothers)
        return out

    class Meta:
        verbose_name = 'Rescue: Request'
        verbose_name_plural = 'Rescue:Requests'

    def __str__(self):
        return '#' + str(
            self.id) + ' ' + self.get_district_display() + ' ' + self.location

    def is_old(self):
        return self.dateadded < (timezone.now() - timezone.timedelta(days=2))
Esempio n. 13
0
class Transaction(models.Model):
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        verbose_name='Vytovril',
    )
    date_created = models.DateTimeField(auto_now=True, )
    state = models.CharField(
        max_length=15,
        choices=STATES,
        verbose_name='stav',
        default='created',
    )
    ammount = models.DecimalField(
        verbose_name='suma',
        max_digits=8,
        decimal_places=2,
    )
    section = models.CharField(
        max_length=15,
        choices=SECTIONS,
        verbose_name='sekcia',
    )
    description = models.TextField(verbose_name='popis', )
    iban = models.CharField(max_length=31, )
    provider = models.CharField(
        max_length=255,
        verbose_name='Názov poskytovateľa',
    )
    business_id = models.CharField(
        max_length=15,
        verbose_name='IČO/Business ID',
        validators=[RegexValidator(regex='[0-9]{8,}')],
    )
    invoice_number = models.CharField(
        max_length=63,
        verbose_name='číslo faktúry',
    )
    invoice = models.FileField(
        verbose_name='faktúra',
        upload_to='invoices/%Y/%m/',
        validators=[validate_file_extension],
    )

    class Meta:
        verbose_name = 'transakcia'
        verbose_name_plural = 'transakcie'

    def __str__(self):
        return 'Transakcia {} - {}'.format(self.pk, self.date_created.date())

    def approve(self):
        self.state = 'approved'
        self.save()

        i = Item.objects.create(transaction=self, approval=self.approval)
        i.send_reminder()

        SendMail([self.created_by.email],
                 'Informácia o schválení transakcie ' +
                 str(self.pk)).change_state(
                     'schválená finančným manažérom sekcie', self)

    def pay(self):
        self.state = 'public'
        self.save()

        SendMail([self.created_by.email],
                 'Informácia o zaplatení transakcie ' +
                 str(self.pk)).change_state('zaplatená', self)

    def disapprove(self, by_who):
        self.state = 'disapproved'
        self.save()

        SendMail([self.created_by.email],
                 'Informácia o zamietnutí transakcie ' +
                 str(self.pk)).change_state('zamietnutá ' + by_who, self)
Esempio n. 14
0
class PhotoSize(models.Model):
    """About the Photosize name: it's used to create get_PHOTOSIZE_url() methods,
    so the name has to follow the same restrictions as any Python method name, 
    e.g. no spaces or non-ascii characters."""

    name = models.CharField(
        _('name'),
        max_length=40,
        unique=True,
        help_text=
        _(u'Photo size name should contain only letters, numbers and underscores. Examples: "thumbnail", "display", "small", "main_page_widget".'
          ),
        validators=[
            RegexValidator(
                regex='^[a-z0-9_]+$',
                message=
                u'Use only plain lowercase letters (ASCII), numbers and underscores.'
            )
        ])
    width = models.PositiveIntegerField(
        _('width'),
        default=0,
        help_text=
        _(u'If width is set to "0" the image will be scaled to the supplied height.'
          ))
    height = models.PositiveIntegerField(
        _('height'),
        default=0,
        help_text=
        _(u'If height is set to "0" the image will be scaled to the supplied width'
          ))
    quality = models.PositiveIntegerField(_('quality'),
                                          choices=JPEG_QUALITY_CHOICES,
                                          default=70,
                                          help_text=_('JPEG image quality.'))
    upscale = models.BooleanField(
        _('upscale images?'),
        default=False,
        help_text=
        _(u'If selected the image will be scaled up if necessary to fit the supplied dimensions. Cropped sizes will be upscaled regardless of this setting.'
          ))
    crop = models.BooleanField(
        _('crop to fit?'),
        default=False,
        help_text=
        _(u'If selected the image will be scaled and cropped to fit the supplied dimensions.'
          ))
    pre_cache = models.BooleanField(
        _('pre-cache?'),
        default=False,
        help_text=
        _(u'If selected this photo size will be pre-cached as photos are added.'
          ))
    increment_count = models.BooleanField(
        _('increment view count?'),
        default=False,
        help_text=
        _(u'If selected the image\'s "view_count" will be incremented when this photo size is displayed.'
          ))
    effect = models.ForeignKey('PhotoEffect',
                               null=True,
                               blank=True,
                               related_name='photo_sizes',
                               verbose_name=_('photo effect'))
    watermark = models.ForeignKey('Watermark',
                                  null=True,
                                  blank=True,
                                  related_name='photo_sizes',
                                  verbose_name=_('watermark image'))

    class Meta:
        ordering = ['width', 'height']
        verbose_name = _('photo size')
        verbose_name_plural = _('photo sizes')

    def __str__(self):
        return self.name

    def clear_cache(self):
        for cls in ImageModel.__subclasses__():
            for obj in cls.objects.all():
                obj.remove_size(self)
                if self.pre_cache:
                    obj.create_size(self)
        PhotoSizeCache().reset()

    def clean(self):
        if self.crop is True:
            if self.width == 0 or self.height == 0:
                raise ValidationError(
                    _(u"Can only crop photos if both width and height dimensions are set."
                      ))

    def save(self, *args, **kwargs):
        super(PhotoSize, self).save(*args, **kwargs)
        PhotoSizeCache().reset()
        self.clear_cache()

    def delete(self):
        assert self._get_pk_val(
        ) is not None, "%s object can't be deleted because its %s attribute is set to None." % (
            self._meta.object_name, self._meta.pk.attname)
        self.clear_cache()
        super(PhotoSize, self).delete()

    def _get_size(self):
        return (self.width, self.height)

    def _set_size(self, value):
        self.width, self.height = value

    size = property(_get_size, _set_size)
Esempio n. 15
0
class Instance(models.Model):
    """
    Each "Tree Map" is a single instance
    """
    name = models.CharField(max_length=255, unique=True)

    url_name = models.CharField(
        max_length=255,
        unique=True,
        validators=[
            reserved_name_validator,
            RegexValidator(
                r'^%s$' % URL_NAME_PATTERN,
                trans('Must start with a letter and may only contain '
                      'letters, numbers, or dashes ("-")'),
                trans('Invalid URL name'))
        ])
    """
    Basemap type     Basemap data
    ------------     -----------------
    Google           Google_API_Key
    Bing             Bing_API_Key
    TMS              TMS URL with {x},{y},{z}
    """
    basemap_type = models.CharField(max_length=255,
                                    choices=(("google", "Google"), ("bing",
                                                                    "Bing"),
                                             ("tms", "Tile Map Service")),
                                    default="google")
    basemap_data = models.CharField(max_length=255, null=True, blank=True)
    """
    The current database revision for the instance

    This revision is used to determine if tiles should be cached.
    In particular, the revision has *no* effect on the actual
    data.

    Generally we make tile requests like:
    http://tileserver/tile/{layer}/{rev}/{Z}/{Y}/{X}

    There is a database trigger that updates the
    revision whenever an edit to a geometry field is made
    so you don't have to worry about it.

    You should *not* edit this field.
    """
    geo_rev = models.IntegerField(default=1)

    eco_benefits_conversion = models.ForeignKey('BenefitCurrencyConversion',
                                                null=True,
                                                blank=True)
    """ Center of the map when loading the instance """
    bounds = models.MultiPolygonField(srid=3857)
    """
    Override the center location (which is, by default,
    the centroid of "bounds"
    """
    center_override = models.PointField(srid=3857, null=True, blank=True)

    default_role = models.ForeignKey('Role', related_name='default_role')

    users = models.ManyToManyField('User',
                                   through='InstanceUser',
                                   null=True,
                                   blank=True)

    boundaries = models.ManyToManyField('Boundary', null=True, blank=True)
    """
    Config contains a bunch of config variables for a given instance
    these can be accessed via per-config properties such as
    `advanced_search_fields`. Note that it is a DotDict, and so supports
    get() with a dotted key and a default, e.g.
        instance.config.get('fruit.apple.type', 'delicious')
    as well as creating dotted keys when no keys in the path exist yet, e.g.
        instance.config = DotDict({})
        instance.config.fruit.apple.type = 'macoun'
    """
    config = JSONField(blank=True)

    is_public = models.BooleanField(default=False)

    logo = models.ImageField(upload_to='logos', null=True, blank=True)

    itree_region_default = models.CharField(max_length=20,
                                            null=True,
                                            blank=True,
                                            choices=ITREE_REGION_CHOICES)

    # Monotonically increasing number used to invalidate my InstanceAdjuncts
    adjuncts_timestamp = models.BigIntegerField(default=0)

    objects = models.GeoManager()

    def __unicode__(self):
        return self.name

    def _make_config_property(prop, default=None):
        def get_config(self):
            return self.config.get(prop, default)

        def set_config(self, value):
            self.config[prop] = value

        return property(get_config, set_config)

    date_format = _make_config_property('date_format', settings.DATE_FORMAT)

    short_date_format = _make_config_property('short_date_format',
                                              settings.SHORT_DATE_FORMAT)

    scss_variables = _make_config_property('scss_variables')

    map_feature_types = _make_config_property('map_feature_types', ['Plot'])

    mobile_search_fields = _make_config_property('mobile_search_fields',
                                                 DEFAULT_MOBILE_SEARCH_FIELDS)

    mobile_api_fields = _make_config_property('mobile_api_fields',
                                              DEFAULT_MOBILE_API_FIELDS)

    non_admins_can_export = models.BooleanField(default=True)

    @property
    def advanced_search_fields(self):
        # TODO pull from the config once users have a way to set search fields

        if not self.feature_enabled('advanced_search_filters'):
            return {
                'standard': [],
                'missing': [],
                'display': [],
                'udfc': self._get_udfc_search_fields()
            }

        from treemap.models import MapFeature  # prevent circular import

        fields = {
            'standard': [{
                'identifier': 'tree.diameter',
                'search_type': 'RANGE'
            }, {
                'identifier': 'tree.date_planted',
                'search_type': 'RANGE'
            }, {
                'identifier': 'mapFeature.updated_at',
                'search_type': 'RANGE'
            }],
            'display': [{
                'model': 'Tree',
                'label': 'Show trees'
            }, {
                'model': 'EmptyPlot',
                'label': 'Show empty planting sites'
            }],
            'missing': [{
                'identifier': 'species.id',
                'label': 'Show missing species',
                'search_type': 'ISNULL',
                'value': 'true'
            }, {
                'identifier': 'tree.diameter',
                'label': 'Show missing trunk diameter',
                'search_type': 'ISNULL',
                'value': 'true'
            }, {
                'identifier': 'mapFeaturePhoto.id',
                'label': 'Show missing photos',
                'search_type': 'ISNULL',
                'value': 'true'
            }],
        }

        def make_display_filter(feature_name):
            Feature = MapFeature.get_subclass(feature_name)
            if hasattr(Feature, 'display_name_plural'):
                plural = Feature.display_name_plural
            else:
                plural = Feature.display_name + 's'
            return {'label': 'Show %s' % plural.lower(), 'model': feature_name}

        fields['display'] += [
            make_display_filter(feature_name)
            for feature_name in self.map_feature_types
            if feature_name != 'Plot'
        ]

        # It makes styling easier if every field has an identifier
        num = 0
        for filters in fields.itervalues():
            for field in filters:
                field['id'] = "%s_%s" % (field.get('identifier', ''), num)
                num += 1

        fields['udfc'] = self._get_udfc_search_fields()

        return fields

    def _get_udfc_search_fields(self):
        from treemap.util import to_object_name

        empty_udfc = {
            to_object_name(n_k): {
                to_object_name(m_k): {
                    'fields': [],
                    'udfd': None
                }
                for m_k in UDFC_MODELS
            }
            for n_k in UDFC_NAMES
        }

        udfds = []
        for model_name in UDFC_MODELS:
            for udfd in udf_defs(self, model_name):
                if udfd.name in UDFC_NAMES:
                    udfds.append(udfd)

        udfc = deepcopy(empty_udfc)

        for udfd in udfds:
            udfd_info = {
                'udfd': udfd,
                'fields': udfd.datatype_dict[0]['choices']
            }
            name_dict = udfc[to_object_name(udfd.name)]
            name_dict[to_object_name(udfd.model_type)] = udfd_info

        return udfc

    @property
    def supports_resources(self):
        """
        Determine whether this instance has multiple map feature
        types (plots + "resources") or not.
        """
        n = len(self.map_feature_types)
        return n > 1

    @property
    def extent_as_json(self):
        boundary = self.bounds.boundary
        xmin, ymin, xmax, ymax = boundary.extent

        return json.dumps({
            'xmin': xmin,
            'ymin': ymin,
            'xmax': xmax,
            'ymax': ymax
        })

    @property
    def bounds_as_geojson(self):
        boundary = self.bounds
        boundary.transform(4326)
        return boundary.json

    @property
    def center(self):
        return self.center_override or self.bounds.centroid

    @property
    def geo_rev_hash(self):
        return hashlib.md5(str(self.geo_rev)).hexdigest()

    @property
    def center_lat_lng(self):
        return self.center.transform(4326, clone=True)

    @property
    def factor_conversions(self):
        """
        Returns a dict for use in eco.py Benefits from eco_benefits_conversion
        """
        benefits_conversion = self.eco_benefits_conversion
        if benefits_conversion:
            return benefits_conversion.get_factor_conversions_config()
        else:
            return None

    @property
    def scss_query_string(self):
        scss_vars = ({k: val
                      for k, val in self.scss_variables.items()
                      if val} if self.scss_variables else {})
        return urlencode(scss_vars)

    @property
    def static_page_names(self):
        from treemap.models import StaticPage  # prevent circular import

        built_in_names = StaticPage.built_in_names()

        custom_names = [
            page.name for page in StaticPage.objects.filter(
                instance=self).exclude(name__in=built_in_names)
        ]

        names = built_in_names + custom_names

        return names

    def update_geo_rev(self):
        qs = Instance.objects.filter(pk=self.id)

        # Use SQL increment in case self.geo_rev is stale
        qs.update(geo_rev=F('geo_rev') + 1)

        # Fetch updated value so callers will have it
        self.geo_rev = qs[0].geo_rev

    def itree_region_codes(self):
        from treemap.models import ITreeRegion

        if self.itree_region_default:
            region_codes = [self.itree_region_default]
        else:
            region_codes = ITreeRegion.objects \
                .filter(geometry__intersects=self.bounds) \
                .values_list('code', flat=True)

        return region_codes

    def itree_regions(self):
        from treemap.models import ITreeRegion  # prevent circular import
        if self.itree_region_default:
            codes = [self.itree_region_default]
        else:
            codes = (ITreeRegion.objects.filter(
                geometry__intersects=self.bounds).values_list('code',
                                                              flat=True))

        return [(code, ITREE_REGIONS.get(code, {}).get('name'))
                for code in codes]

    def has_itree_region(self):
        return bool(self.itree_regions())

    def is_accessible_by(self, user):
        try:
            if self.is_public:
                return True

            # Extension point
            if hasattr(user, 'is_super_admin') and user.is_super_admin():
                return True

            # If a user is not logged in, trying to check
            # user=user raises a type error so I am checking
            # pk instead
            self.instanceuser_set.get(user__pk=user.pk)
            return True
        except ObjectDoesNotExist:
            return False

    def scope_model(self, model):
        qs = model.objects.filter(instance=self)
        return qs

    def feature_enabled(self, feature):
        # Delayed import to prevent circular imports
        from treemap.plugin import feature_enabled
        return feature_enabled(self, feature)

    def seed_with_dummy_default_role(self):
        """
        Instances need roles and roles needs instances... crazy stuff
        we're going to create the needed role below however, we'll temporarily
        use a 'dummy role'. The dummy role has no instance.
        """
        from treemap.audit import Role
        dummy_roles = Role.objects.filter(instance__isnull=True)
        if len(dummy_roles) == 0:
            dummy_role = Role.objects.create(name='empty', rep_thresh=0)
        else:
            dummy_role = dummy_roles[0]

        self.default_role = dummy_role

    def clean(self):
        # We need to work around a bit of a chicken/egg problem here
        # The default API fields reference Stewardship, but the Stewardship
        # UDFs won't exist when the instance is first created.
        # To work around this, we only validate when there is something in the
        # 'config' object, which ignores the default api fields
        if 'mobile_api_fields' in self.config:
            self._validate_mobile_api_fields()

    def _validate_mobile_api_fields(self):
        # Validate that:
        # 1) overall structure is correct
        # 2) each individual group has a header and collection or normal fields
        # 3) Collection UDF groups only contain collection UDFs
        # 4) Collection UDF groups have a 'sort_key', which is present on all
        #    fields for that group
        # 5) no field is referenced more than once
        # 6) all fields referenced exist

        # delayed import to avoid circular references
        from treemap.models import Plot, Tree

        def _truthy_of_type(item, types):
            return item and isinstance(item, types)

        field_groups = self.mobile_api_fields
        errors = set()

        scalar_udfs = {
            udef.full_name: udef
            for udef in udf_defs(self) if not udef.iscollection
        }
        collection_udfs = {
            udef.full_name: udef
            for udef in udf_defs(self) if udef.iscollection
        }

        if not _truthy_of_type(field_groups, (list, tuple)):
            raise ValidationError(
                {'mobile_api_fields': [API_FIELD_ERRORS['no_field_groups']]})

        for group in field_groups:
            if not _truthy_of_type(group.get('header'), basestring):
                errors.add(API_FIELD_ERRORS['group_has_no_header'])

            if ((not _truthy_of_type(group.get('collection_udf_keys'), list)
                 and not _truthy_of_type(group.get('field_keys'), list))):
                errors.add(API_FIELD_ERRORS['group_has_no_keys'])

            elif 'collection_udf_keys' in group and 'field_keys' in group:
                errors.add(API_FIELD_ERRORS['group_has_both_keys'])

            if 'collection_udf_keys' in group:
                sort_key = group.get('sort_key')
                if not sort_key:
                    errors.add(API_FIELD_ERRORS['group_has_no_sort_key'])

                for key in group['collection_udf_keys']:
                    udef = collection_udfs.get(key)
                    if udef is None:
                        errors.add(API_FIELD_ERRORS['group_has_missing_cudf'])
                    elif sort_key not in udef.datatype_by_field:
                        errors.add(
                            API_FIELD_ERRORS['group_has_invalid_sort_key'])

        scalar_fields = [
            key for group in field_groups
            for key in group.get('field_keys', [])
        ]
        collection_fields = [
            key for group in field_groups
            for key in group.get('collection_udf_keys', [])
        ]

        all_fields = scalar_fields + collection_fields

        if len(all_fields) != len(set(all_fields)):
            errors.add(API_FIELD_ERRORS['duplicate_fields'])

        for field in scalar_fields:
            if not re.match(r'(?:plot|tree)[.].*', field):
                errors.add(API_FIELD_ERRORS['invalid_field'] %
                           {'field': field})
                continue

            model_name, name = field.split('.', 1)  # maxsplit of 1
            Model = Plot if model_name == 'plot' else Tree
            standard_fields = Model._meta.get_all_field_names()

            if ((name not in standard_fields and field not in scalar_udfs)):
                errors.add(API_FIELD_ERRORS['missing_field'])

        if errors:
            raise ValidationError({'mobile_api_fields': errors})

    def save(self, *args, **kwargs):
        self.full_clean()

        self.url_name = self.url_name.lower()

        super(Instance, self).save(*args, **kwargs)
Esempio n. 16
0
def validate_currency(value):
    """Validate currency"""
    regexObj = re.compile('^[0-9]*\.?|\,?[0-9]{0,2}$')
    obj = RegexValidator(regexObj, _('Validation error. Currency expected.'))
    obj.__call__(value)
Esempio n. 17
0
def validate_user_id(value):
    """Validate User Id"""
    #regexObj = re.compile('^[a-zA-Z0-9_.@-+]+')
    regexObj = re.compile('^[a-zA-Z0-9_]+')
    obj = RegexValidator(regexObj, _('Validation error. UserId expected.'))
    obj.__call__(value)
Esempio n. 18
0
class NodeForm(SerializerForm):
    """
    Update compute node settings.
    """
    _api_call = node_define

    hostname = forms.CharField(label=_('Hostname'),
                               widget=forms.TextInput(attrs={'class': 'input-transparent narrow uneditable-input',
                                                             'disabled': 'disabled'}))
    owner = forms.ChoiceField(label=_('Owner'),
                              widget=forms.Select(attrs={'class': 'narrow input-select2'}))
    status = forms.TypedChoiceField(label=_('Status'), choices=Node.STATUS, coerce=int,
                                    widget=forms.Select(attrs={'class': 'narrow input-select2'}))
    is_compute = forms.BooleanField(label=_('Compute?'), required=False,
                                    widget=forms.CheckboxInput(attrs={'class': 'normal-check'}))
    is_backup = forms.BooleanField(label=_('Backup?'), required=False,
                                   widget=forms.CheckboxInput(attrs={'class': 'normal-check'}))
    note = forms.CharField(label=_('Note'), help_text=_('Custom text information about this compute node, with markdown'
                                                        ' support.'),
                           required=False,
                           widget=forms.Textarea(attrs={
                               'class': 'input-transparent small',
                               'rows': 5})
                           )

    address = forms.ChoiceField(label=_('IP address'),
                                help_text=_('IP address used for communication between compute nodes '
                                            '(e.g., VM backups, VM replication, internal VM and node monitoring).'),
                                widget=forms.Select(attrs={'class': 'narrow input-select2'}))

    cpu_coef = forms.DecimalField(label=_('CPUs coefficient'), max_digits=4, decimal_places=2,
                                  help_text=_('Coefficient for calculating the the total number of virtual CPUs.'),
                                  widget=forms.TextInput(attrs={'class': 'input-transparent narrow',
                                                                'required': 'required'}))
    ram_coef = forms.DecimalField(label=_('RAM coefficient'), max_digits=4, decimal_places=2,
                                  help_text=_('Coefficient for calculating the maximum amount of memory '
                                              'for virtual machines.'),
                                  widget=forms.TextInput(attrs={'class': 'input-transparent narrow',
                                                                'required': 'required'}))

    monitoring_templates = ArrayField(label=_('Monitoring templates'), required=False, tags=True,
                                      help_text=_('Comma-separated list of custom monitoring templates.'),
                                      widget=ArrayWidget(tags=True, escape_space=False,
                                                         attrs={'class': 'tags-select2 narrow',
                                                                'data-tags-type': 'mon_templates',
                                                                'data-tags-api-call': 'mon_node_template_list'}))
    monitoring_hostgroups = ArrayField(label=_('Monitoring hostgroups'), required=False, tags=True,
                                       help_text=_('Comma-separated list of custom monitoring hostgroups.'),
                                       validators=[
                                           RegexValidator(regex=MonitoringBackend.RE_MONITORING_HOSTGROUPS)],
                                       widget=ArrayWidget(tags=True, escape_space=False,
                                                          attrs={'class': 'tags-select2 narrow',
                                                                 'data-tags-type': 'mon_hostgroups',
                                                                 'data-tags-api-call': 'mon_node_hostgroup_list'}))

    def __init__(self, request, node, *args, **kwargs):
        super(NodeForm, self).__init__(request, node, *args, **kwargs)
        self.fields['owner'].choices = get_owners(request).values_list('username', 'username')
        self.fields['address'].choices = [(ip, ip) for ip in node.ips]
        dc1_settings = get_dc1_settings(request)

        if dc1_settings.MON_ZABBIX_HOSTGROUPS_NODE:
            self.fields['monitoring_hostgroups'].help_text += _(' Automatically added hostgroups: ') \
                                                              + ', '.join(dc1_settings.MON_ZABBIX_HOSTGROUPS_NODE)

        if node.is_unlicensed():
            self.fields['status'].choices = Node.STATUS_DB
            self.fields['status'].widget.attrs['disabled'] = 'disabled'
        elif node.is_unreachable():
            self.fields['status'].choices = Node.STATUS_DB[:-1]
            self.fields['status'].widget.attrs['disabled'] = 'disabled'

    def _initial_data(self, request, obj):
        return obj.web_data
Esempio n. 19
0
def validate_str(value):
    """Validate any string value"""
    regexObj = re.compile('\w+', re.L)
    obj = RegexValidator(regexObj, _('Validation error. Text expected.'))
    obj.__call__(value)
Esempio n. 20
0
from django import forms
from django.contrib.auth.hashers import make_password
from django.core.validators import RegexValidator

from DjangoAuthServer.authapp.models import User

username_validator = RegexValidator(
    r'^[\w\d_\-]+$',
    "Username should contain only letters, digits, underscores, and dashes")


class UserForm(forms.ModelForm):
    username = forms.CharField(widget=forms.TextInput,
                               max_length=120,
                               min_length=3,
                               validators=[username_validator])
    email = forms.EmailField(widget=forms.EmailInput)
    password = forms.CharField(widget=forms.PasswordInput)
    password_again = forms.CharField(widget=forms.PasswordInput)
    avatar = forms.ImageField(widget=forms.FileInput)

    class Meta:
        model = User
        fields = ('username', 'email', 'password', 'password_again')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if self.fields.get('username', None):
            self.fields['username'].widget.attrs.update({
                'placeholder':
Esempio n. 21
0
class Client(models.Model):
    """访问请求的客户端"""

    # client 的名称
    name = models.CharField(unique=True, max_length=128)
    # client 的标识,client 发起请求时,使用 access_key 来标识自己,而不是 name
    access_key = models.CharField(unique=True,
                                  max_length=128,
                                  validators=[
                                      RegexValidator(regex=r'^[_0-9a-zA-Z]+$',
                                                     message='仅使用字母数字和下划线')
                                  ])
    # 密钥
    secret_key = models.CharField(max_length=128,
                                  validators=[
                                      RegexValidator(regex=r'^[_0-9a-zA-Z]+$',
                                                     message='仅使用字母数字和下划线')
                                  ])
    # 是否启用
    enable = models.BooleanField(default=True)
    # 去哪里验证登陆信息
    login_auth_url = models.URLField(max_length=512, default='', blank=True)
    # access_token 在多少秒后过期
    access_token_ex = models.IntegerField(
        default=DEFAULT_ACCESS_TOKEN_EXPIRE_SECONDS)
    # refresh_token 在多少秒后过期
    refresh_token_ex = models.IntegerField(
        default=DEFAULT_REFRESH_TOKEN_EXPIRE_SECONDS)
    # 备注
    memo = models.CharField(blank=True, max_length=512)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        app_label = 'dashboard'
        ordering = ['name']

    def to_json_dict(self, skip_id=False):
        d = {
            'name': self.name,
            'access_key': self.access_key,
            'secret_key': self.secret_key,
            'login_auth_url': self.login_auth_url,
            'access_token_ex': self.access_token_ex,
            'refresh_token_ex': self.refresh_token_ex,
            'enable': self.enable,
            'memo': self.memo
        }

        # 是否要过滤id
        if not skip_id:
            d['id'] = self.id

        if hasattr(self, 'endpoints'):
            d['endpoints'] = [
                t.to_json_dict(skip_id) if isinstance(t, Endpoint) else t
                for t in self.endpoints
            ]

        return d

    def __unicode__(self):
        return self.name

    @classmethod
    def get_all_in_json(cls):
        data = Client.objects.all()
        return [t.to_json_dict() for t in data]

    @classmethod
    def get_client(cls, client_id):
        try:
            return Client.objects.get(id=client_id)
        except Exception as e:
            logger.debug(e)
            return None
Esempio n. 22
0
class Recipients(BaseTable):
    """ Message recepients

    A master list of all our recepients. Messages will only be sent to recepients in this list
    """
    names_validator = RegexValidator(
        regex="^[a-zA-Z']*$", message='A name should only contain letters')
    nick_name_validator = RegexValidator(
        regex='^[a-zA-Z_]*$',
        message='A nick name should only contain letters and/or an underscore')
    other_names_validator = RegexValidator(
        regex="^[a-zA-Z\s'\.]*$",
        message='A name should only contain letters and/or a space')
    phone_validator = RegexValidator(
        regex='^\+\d+$',
        message=
        'The phone number should be in the format +1xxxxxxxxxxx with no spaces'
    )

    salutation = models.CharField(
        max_length=10,
        null=True,
        blank=True,
        validators=[
            MaxLengthValidator(
                10, message='The salutation must be less than 10 characters')
        ])
    first_name = models.CharField(
        max_length=30,
        null=True,
        blank=True,
        validators=[
            MaxLengthValidator(
                30, message='The first name must be less than 30 characters'),
            names_validator
        ])
    other_names = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        validators=[
            MaxLengthValidator(
                100,
                message='The other names must be less than 100 characters'),
            other_names_validator
        ])
    # this is the unique identifier used in the ODK forms
    nick_name = models.CharField(
        max_length=200,
        null=False,
        blank=False,
        unique=True,
        validators=[
            MaxLengthValidator(
                200,
                message='The nick names must be less than 100 characters'),
            nick_name_validator
        ])
    designation = models.CharField(
        max_length=100,
        validators=[
            MaxLengthValidator(
                100,
                message=
                'The recepient designation must be less than 100 characters'),
            nick_name_validator
        ])
    cell_no = models.CharField(
        max_length=15,
        blank=True,
        null=True,
        unique=True,
        validators=[
            MaxLengthValidator(
                15,
                message=
                'The recepient phone number must not be more than 15 characters long'
            ), phone_validator
        ])
    alternative_cell_no = models.CharField(
        max_length=15,
        blank=True,
        null=True,
        validators=[
            MaxLengthValidator(
                15,
                message=
                'The recepient alternative phone number must not be more than 15 characters long'
            ), phone_validator
        ])
    recipient_email = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        validators=[
            MaxLengthValidator(
                100,
                message=
                'The recepient email must not be more than 100 characters')
        ])
    is_active = models.BooleanField(default=True)

    # the following will store the location association to the recepient
    # For a CDR this will be the village/ward
    # A SCVO will be a sub county
    # A SC worker will be a ward... maybe
    # The CDVS and ICT officer, the location association will be blank since they are associated at the county level
    village = models.ForeignKey(Village,
                                on_delete=models.PROTECT,
                                blank=True,
                                null=True)
    ward = models.ForeignKey(Ward,
                             on_delete=models.PROTECT,
                             blank=True,
                             null=True)
    sub_county = models.ForeignKey(SubCounty,
                                   on_delete=models.PROTECT,
                                   blank=True,
                                   null=True)

    class Meta:
        db_table = 'recipients'
Esempio n. 23
0
import requests

from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.utils.translation import ugettext_lazy as _

isetsyvalidator = RegexValidator(
    regex="^http(s)?://(www\.)?etsy\.com/uk/listing/[0-9]+(/[a-z-]+)?$",
    message="Must be an Etsy item listing link",
    code="Invalid key")


def validate_link_exists(value):
    if requests.head(value).status_code != 200:
        raise ValidationError(
            _('%(value)s is not an existing link'),
            params={'value': value},
        )
Esempio n. 24
0
class Report(models.Model):
    PRIMARY_COMPLAINT_DEPENDENT_FIELDS = {
        'workplace': ['public_or_private_employer', 'employer_size'],
        'education': ['public_or_private_school'],
        'police':
        ['inside_correctional_facility', 'correctional_facility_type'],
        'commercial_or_public':
        ['commercial_or_public_place', 'other_commercial_or_public_place']
    }

    # Contact
    contact_first_name = models.CharField(max_length=225,
                                          null=True,
                                          blank=True)
    contact_last_name = models.CharField(max_length=225, null=True, blank=True)
    contact_email = models.EmailField(null=True, blank=True)
    contact_phone = models.CharField(validators=[
        RegexValidator(phone_validation_regex,
                       message=CONTACT_PHONE_INVALID_MESSAGE)
    ],
                                     max_length=225,
                                     null=True,
                                     blank=True)
    contact_address_line_1 = models.CharField(max_length=225,
                                              null=True,
                                              blank=True)
    contact_address_line_2 = models.CharField(max_length=225,
                                              null=True,
                                              blank=True)
    contact_city = models.CharField(max_length=700, null=True, blank=True)
    contact_state = models.CharField(max_length=100,
                                     null=True,
                                     blank=True,
                                     choices=STATES_AND_TERRITORIES)
    contact_zip = models.CharField(max_length=10, null=True, blank=True)

    servicemember = models.CharField(max_length=4,
                                     null=True,
                                     blank=True,
                                     choices=SERVICEMEMBER_CHOICES)

    # Primary Issue
    primary_complaint = models.CharField(max_length=100,
                                         choices=PRIMARY_COMPLAINT_CHOICES,
                                         default='',
                                         blank=False)

    hate_crime = models.CharField(max_length=4,
                                  null=True,
                                  blank=True,
                                  choices=HATE_CRIME_CHOICES)

    # Protected Class
    # See docs for notes on updating these values:
    # docs/maintenance_or_infrequent_tasks.md#change-protected-class-options
    protected_class = models.ManyToManyField(ProtectedClass, blank=True)
    other_class = models.CharField(max_length=150, null=True, blank=True)

    # Details Summary
    violation_summary = models.TextField(max_length=7000,
                                         null=True,
                                         blank=True)
    status = models.TextField(choices=STATUS_CHOICES, default='new')
    assigned_section = models.TextField(choices=SECTION_CHOICES, default='ADM')

    # Incident location
    location_name = models.CharField(max_length=225, null=True, blank=True)
    location_address_line_1 = models.CharField(max_length=225,
                                               null=True,
                                               blank=True)
    location_address_line_2 = models.CharField(max_length=225,
                                               null=True,
                                               blank=True)
    location_city_town = models.CharField(max_length=700,
                                          null=True,
                                          blank=True)
    location_state = models.CharField(max_length=100,
                                      null=True,
                                      blank=True,
                                      choices=STATES_AND_TERRITORIES)

    # Incident location routing-specific fields
    election_details = models.CharField(max_length=225,
                                        null=True,
                                        blank=True,
                                        default=None,
                                        choices=ELECTION_CHOICES)
    public_or_private_employer = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        default=None,
        choices=PUBLIC_OR_PRIVATE_EMPLOYER_CHOICES)
    employer_size = models.CharField(max_length=100,
                                     null=True,
                                     blank=True,
                                     default=None,
                                     choices=EMPLOYER_SIZE_CHOICES)

    # By law
    inside_correctional_facility = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        default=None,
        choices=CORRECTIONAL_FACILITY_LOCATION_CHOICES)
    correctional_facility_type = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        default=None,
        choices=CORRECTIONAL_FACILITY_LOCATION_TYPE_CHOICES)

    # Commercial or public space
    commercial_or_public_place = models.CharField(
        max_length=225,
        choices=COMMERCIAL_OR_PUBLIC_PLACE_CHOICES,
        null=True,
        blank=True,
        default=None)
    other_commercial_or_public_place = models.CharField(max_length=150,
                                                        blank=True,
                                                        null=True,
                                                        default=None)

    # Education location
    public_or_private_school = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        choices=PUBLIC_OR_PRIVATE_SCHOOL_CHOICES,
        default=None)

    # Incident date
    last_incident_year = models.PositiveIntegerField(MaxValueValidator(
        datetime.now().year, message=DATE_ERRORS['no_future']),
                                                     null=True,
                                                     blank=True)
    last_incident_day = models.PositiveIntegerField(MaxValueValidator(
        31, message=DATE_ERRORS['day_invalid']),
                                                    null=True,
                                                    blank=True)
    last_incident_month = models.PositiveIntegerField(
        MaxValueValidator(12, message=DATE_ERRORS['month_invalid']),
        null=True,
        blank=True,
    )

    # Internal comments
    internal_comments = models.ManyToManyField(CommentAndSummary)
    # Internal codes
    district = models.CharField(max_length=7,
                                null=True,
                                blank=True,
                                choices=DISTRICT_CHOICES)
    primary_statute = models.CharField(max_length=7,
                                       null=True,
                                       blank=True,
                                       choices=STATUTE_CHOICES)

    # Metadata
    public_id = models.CharField(max_length=100, null=False, blank=False)
    create_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)
    crt_reciept_year = models.PositiveIntegerField(MaxValueValidator(
        datetime.now().year),
                                                   null=True,
                                                   blank=True)
    crt_reciept_day = models.PositiveIntegerField(MaxValueValidator(31),
                                                  null=True,
                                                  blank=True)
    crt_reciept_month = models.PositiveIntegerField(MaxValueValidator(12),
                                                    null=True,
                                                    blank=True)
    intake_format = models.CharField(max_length=100,
                                     null=True,
                                     default=None,
                                     choices=INTAKE_FORMAT_CHOICES)
    author = models.CharField(max_length=1000, null=True, blank=True)
    assigned_to = models.ForeignKey(User,
                                    blank=True,
                                    null=True,
                                    related_name="assigned_complaints",
                                    on_delete=models.CASCADE)
    closed_date = models.DateTimeField(
        blank=True,
        null=True,
        help_text=
        "The Date this report's status was most recently set to \"Closed\"")

    # Not in use- but need to preserving historical data
    hatecrimes_trafficking = models.ManyToManyField(HateCrimesandTrafficking,
                                                    blank=True)

    @cached_property
    def last_incident_date(self):
        try:
            day = self.last_incident_day or 1
            date = datetime(self.last_incident_year, self.last_incident_month,
                            day)
        except ValueError:
            date = None
        return date

    @cached_property
    def crt_reciept_date(self):
        day = self.crt_reciept_day or 1
        try:
            date = datetime(self.crt_reciept_year, self.crt_reciept_month, day)
        except ValueError:
            date = None
        return date

    def __str__(self):
        return f'{self.create_date} {self.violation_summary}'

    def __has_immigration_protected_classes(self, pcs):
        immigration_classes = ['immigration', 'national_origin', 'language']
        is_not_included = set(pcs).isdisjoint(set(immigration_classes))

        if is_not_included:
            return False

        return True

    def __is_not_disabled(self, pcs):
        return 'disability' not in pcs

    def assign_section(self):
        """See the SectionAssignmentTests for expected behaviors"""
        protected_classes = [pc.value for pc in self.protected_class.all()]

        if self.hate_crime == 'yes':
            return 'CRM'

        elif self.primary_complaint == 'voting':
            if self.__is_not_disabled(protected_classes):
                return 'VOT'
            else:
                return 'DRS'

        elif self.primary_complaint == 'workplace':
            if self.__has_immigration_protected_classes(protected_classes):
                return 'IER'
            else:
                return 'ELS'

        elif self.primary_complaint == 'commercial_or_public':
            if not self.__is_not_disabled(protected_classes):
                return 'DRS'
            elif self.commercial_or_public_place == 'healthcare':
                return 'SPL'
            else:
                return 'HCE'

        elif self.primary_complaint == 'housing':
            return 'HCE'

        elif self.primary_complaint == 'education':
            if self.public_or_private_school == 'public' or self.public_or_private_school == 'not_sure':
                return 'EOS'
            elif self.__is_not_disabled(protected_classes):
                return 'EOS'
            elif self.public_or_private_school == 'private' and not self.__is_not_disabled(
                    protected_classes):
                return 'DRS'

        elif self.primary_complaint == 'police':
            if self.__is_not_disabled(
                    protected_classes
            ) and self.inside_correctional_facility == 'inside':
                return 'SPL'
            elif self.__is_not_disabled(
                    protected_classes
            ) and self.inside_correctional_facility == 'outside':
                return 'CRM'
            else:
                return 'DRS'

        elif self.primary_complaint == 'something_else' and not self.__is_not_disabled(
                protected_classes):
            return 'DRS'

        return 'ADM'

    def assign_district(self):
        if self.location_city_town and self.location_state:
            city = self.location_city_town.upper().strip()
            district_query = JudicialDistrict.objects.filter(
                city=city, state=self.location_state)
            if len(district_query) > 0:
                return district_query[0].district

        return None

    @property
    def get_summary(self):
        """Return most recent summary provided by an intake specialist"""
        return self.internal_comments.filter(
            is_summary=True).order_by('-modified_date').first()

    @property
    def addressee(self):
        if self.contact_first_name:
            salutation = 'Dear'
            if self.contact_last_name:
                return f"{salutation} {self.contact_first_name} {self.contact_last_name}"
            return f"{salutation} {self.contact_first_name}"
        return "Thank you for your report"

    @property
    def addressee_es(self):
        if self.contact_first_name:
            salutation = 'Estimado/a'
            if self.contact_last_name:
                return f"{salutation} {self.contact_first_name} {self.contact_last_name}"
            return f"{salutation} {self.contact_first_name}"
        return "Gracias por su informe"

    def get_absolute_url(self):
        return reverse('crt_forms:crt-forms-show', kwargs={"id": self.id})

    @cached_property
    def closed(self):
        return self.status == CLOSED_STATUS

    def closeout_report(self):
        """
        Remove assignee and record date of call
        """
        self.assigned_to = None
        self.closed_date = datetime.now()

    def status_assignee_reset(self):
        """
        Remove assignee and update status to new
        """
        self.assigned_to = None
        self.status = 'new'
Esempio n. 25
0
import babel
import six
from django import forms
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.core.validators import RegexValidator
from django.db import models
from django.db.models import BLANK_CHOICE_DASH
from django.forms.widgets import NumberInput
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from jsonfield.fields import JSONField

from E-Commerce.core.fields.tagged_json import tag_registry, TaggedJSONEncoder
from E-Commerce.utils.i18n import get_current_babel_locale, remove_extinct_languages

IdentifierValidator = RegexValidator("[a-z][a-z_]+")

MONEY_FIELD_DECIMAL_PLACES = 9
FORMATTED_DECIMAL_FIELD_DECIMAL_PLACES = 9
FORMATTED_DECIMAL_FIELD_MAX_DIGITS = 36


class InternalIdentifierField(models.CharField):

    def __init__(self, **kwargs):
        if "unique" not in kwargs:
            raise ValueError("You must explicitly set the `unique` flag for `InternalIdentifierField`s.")
        kwargs.setdefault("max_length", 64)
        kwargs.setdefault("blank", True)
        kwargs.setdefault("null", bool(kwargs.get("blank")))  # If it's allowed to be blank, it should be null
        kwargs.setdefault("verbose_name", _("internal identifier"))
Esempio n. 26
0
            connection=get_connection(lane=lanes[reason],
                                      debug={
                                          'user': self.pk,
                                          'reason': reason
                                      })).send()
        metrics.get('desecapi_messages_queued').labels(
            reason, self.pk, lanes[reason]).observe(num_queued)
        return num_queued


validate_domain_name = [
    validate_lower,
    RegexValidator(
        regex=r'^(([a-z0-9_-]{1,63})\.)*[a-z0-9-]{1,63}$',
        message=
        'Domain names must be labels separated by dots. Labels may consist of up to 63 letters, digits, '
        'hyphens, and underscores. The last label may not contain an underscore.',
        code='invalid_domain_name',
        flags=re.IGNORECASE)
]


class Domain(ExportModelOperationsMixin('Domain'), models.Model):
    @staticmethod
    def _minimum_ttl_default():
        return settings.MINIMUM_TTL_DEFAULT

    class RenewalState(models.IntegerChoices):
        IMMORTAL = 0
        FRESH = 1
        NOTIFIED = 2
Esempio n. 27
0
# -*- encoding: utf-8 -*-
import re

from datetime import date

from django.core.validators import RegexValidator
from django.db import models

from base.model_utils import TimeStampedModel


username_validator = RegexValidator(
    re.compile('^[\w.@+-]+$'),
    'Enter a valid username.',
    'invalid'
)


class PasswordResetAuditManager(models.Manager):

    def audit(self, email):
        try:
            obj = self.model.objects.get(email__iexact=email)
            obj.count = obj.count + 1
            obj.save()
        except PasswordResetAudit.DoesNotExist:
            obj = self.model(email=email, request_date=date.today(), count=1)
            obj.save()
        return obj

Esempio n. 28
0
class RRset(ExportModelOperationsMixin('RRset'), models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    touched = models.DateTimeField(auto_now=True)
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
    subname = models.CharField(
        max_length=178,
        blank=True,
        validators=[
            validate_lower,
            RegexValidator(
                regex=r'^([*]|(([*][.])?([a-z0-9_-]+[.])*[a-z0-9_-]+))$',
                message=
                'Subname can only use (lowercase) a-z, 0-9, ., -, and _, '
                'may start with a \'*.\', or just be \'*\'.',
                code='invalid_subname')
        ])
    type = models.CharField(
        max_length=10,
        validators=[
            validate_upper,
            RegexValidator(
                regex=r'^[A-Z][A-Z0-9]*$',
                message=
                'Type must be uppercase alphanumeric and start with a letter.',
                code='invalid_type')
        ])
    ttl = models.PositiveIntegerField()

    objects = RRsetManager()

    class Meta:
        constraints = [
            ExclusionConstraint(
                name='cname_exclusivity',
                expressions=[
                    ('domain', RangeOperators.EQUAL),
                    ('subname', RangeOperators.EQUAL),
                    (RawSQL("int4(type = 'CNAME')",
                            ()), RangeOperators.NOT_EQUAL),
                ],
            ),
        ]
        unique_together = (("domain", "subname", "type"), )

    @staticmethod
    def construct_name(subname, domain_name):
        return '.'.join(filter(None, [subname, domain_name])) + '.'

    @property
    def name(self):
        return self.construct_name(self.subname, self.domain.name)

    def save(self, *args, **kwargs):
        self.full_clean(validate_unique=False)
        super().save(*args, **kwargs)

    def clean_records(self, records_presentation_format):
        """
        Validates the records belonging to this set. Validation rules follow the DNS specification; some types may
        incur additional validation rules.

        Raises ValidationError if violation of DNS specification is found.

        Returns a set of records in canonical presentation format.

        :param records_presentation_format: iterable of records in presentation format
        """
        rdtype = rdatatype.from_text(self.type)
        errors = []

        if self.type == 'CNAME':
            if self.subname == '':
                errors.append('CNAME RRset cannot have empty subname.')
            if len(records_presentation_format) > 1:
                errors.append(
                    'RRset of type CNAME cannot have multiple records.')

        def _error_msg(record, detail):
            return f'Record content of {self.type} {self.name} invalid: \'{record}\': {detail}'

        records_canonical_format = set()
        for r in records_presentation_format:
            try:
                r_canonical_format = RR.canonical_presentation_format(
                    r, rdtype)
            except binascii.Error:
                # e.g., odd-length string
                errors.append(
                    _error_msg(
                        r,
                        'Cannot parse hexadecimal or base64 record contents'))
            except dns.exception.SyntaxError as e:
                # e.g., A/127.0.0.999
                if 'quote' in e.args[0]:
                    errors.append(
                        _error_msg(
                            r,
                            f'Data for {self.type} records must be given using quotation marks.'
                        ))
                else:
                    errors.append(
                        _error_msg(
                            r,
                            f'Record content malformed: {",".join(e.args)}'))
            except dns.name.NeedAbsoluteNameOrOrigin:
                errors.append(
                    _error_msg(
                        r,
                        'Hostname must be fully qualified (i.e., end in a dot: "example.com.")'
                    ))
            except ValueError:
                # e.g., string ("asdf") cannot be parsed into int on base 10
                errors.append(_error_msg(r, 'Cannot parse record contents'))
            except Exception as e:
                # TODO see what exceptions raise here for faulty input
                raise e
            else:
                if r_canonical_format in records_canonical_format:
                    errors.append(
                        _error_msg(
                            r,
                            f'Duplicate record content: this is identical to '
                            f'\'{r_canonical_format}\''))
                else:
                    records_canonical_format.add(r_canonical_format)

        if any(errors):
            raise ValidationError(errors)

        return records_canonical_format

    def save_records(self, records):
        """
        Updates this RR set's resource records, discarding any old values.

        Records are expected in presentation format and are converted to canonical
        presentation format (e.g., 127.00.0.1 will be converted to 127.0.0.1).
        Raises if a invalid set of records is provided.

        This method triggers the following database queries:
        - one DELETE query
        - one SELECT query for comparison of old with new records
        - one INSERT query, if one or more records were added

        Changes are saved to the database immediately.

        :param records: list of records in presentation format
        """
        new_records = self.clean_records(records)

        # Delete RRs that are not in the new record list from the DB
        self.records.exclude(content__in=new_records).delete()  # one DELETE

        # Retrieve all remaining RRs from the DB
        unchanged_records = set(r.content
                                for r in self.records.all())  # one SELECT

        # Save missing RRs from the new record list to the DB
        added_records = new_records - unchanged_records
        rrs = [RR(rrset=self, content=content) for content in added_records]
        RR.objects.bulk_create(rrs)  # One INSERT

    def __str__(self):
        return '<RRSet %s domain=%s type=%s subname=%s>' % (
            self.pk, self.domain.name, self.type, self.subname)
Esempio n. 29
0
from django.db import models
from django.utils import timezone
import markdown2
from pyquery import PyQuery as pq
from django.core.validators import RegexValidator
from django_extensions.db.fields import AutoSlugField
import re

valid_title_chars = r'^[a-zA-Z ,!?]+$'
title_validator = RegexValidator(valid_title_chars)

# The length of the summary -3 represents the space for the elipses
CONST_SUMMARY_LENGTH = 200 - 3 

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(
            unique=True,
            max_length=200
        )
    text = models.TextField()

    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True,
            null=True)
    slug = AutoSlugField( max_length=50,null=False,unique=True, populate_from=('title','author'))

    def publish(self):
        self.published_date = timezone.now()
Esempio n. 30
0
from django.db import models
from django.contrib.auth.models import User
from django.shortcuts import reverse
from django.core.validators import RegexValidator,MaxLengthValidator, MinLengthValidator,MaxValueValidator, MinValueValidator

alphabets = RegexValidator(r'^[a-zA-Z]*$', 'Only alphabets are allowed')


DEPARTMENT = (
    ('CE','Civil Engineering'),
    ('CSE','Computer Science',),
    ('ECE','Electronics and Communication'),
    ('IT','Information Technology'),
    ('ME','Mechanical Engineering'),
)

SECTION = (
    ('1',1),
    ('2',2),
    ('3',3),
    ('4',4)
)

YEAR = (
    ('3','THIRD'),
    ('4','FOURTH')
)

class FacultyInfo(models.Model):
    user = models.OneToOneField(User,on_delete = models.CASCADE)
    name = models.CharField(max_length = 100,validators=[alphabets])
Esempio n. 31
0
def validate_txt_field(value):
    """Validate a text field"""
    #regexObj = re.compile("^(\w*)\s?(\s?\w+)*$", re.L)
    regexObj = re.compile('\w+', re.L)
    obj = RegexValidator(regexObj, _('Validation error. Text field expected.'))
    obj.__call__(value)
Esempio n. 32
0
    def to_form_field(self,
                      set_initial=True,
                      enforce_required=True,
                      for_csv_import=False):
        """
        Return a form field suitable for setting a CustomField's value for an object.

        set_initial: Set initial date for the field. This should be False when generating a field for bulk editing.
        enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
        for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
        """
        initial = self.default if set_initial else None
        required = self.required if enforce_required else False

        # Integer
        if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
            field = forms.IntegerField(required=required,
                                       initial=initial,
                                       min_value=self.validation_minimum,
                                       max_value=self.validation_maximum)

        # Boolean
        elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
            choices = (
                (None, '---------'),
                (True, 'True'),
                (False, 'False'),
            )
            field = forms.NullBooleanField(
                required=required,
                initial=initial,
                widget=StaticSelect2(choices=choices))

        # Date
        elif self.type == CustomFieldTypeChoices.TYPE_DATE:
            field = forms.DateField(required=required,
                                    initial=initial,
                                    widget=DatePicker())

        # Select
        elif self.type == CustomFieldTypeChoices.TYPE_SELECT:
            choices = [(c, c) for c in self.choices]
            default_choice = self.default if self.default in self.choices else None

            if not required or default_choice is None:
                choices = add_blank_choice(choices)

            # Set the initial value to the first available choice (if any)
            if set_initial and default_choice:
                initial = default_choice

            field_class = CSVChoiceField if for_csv_import else forms.ChoiceField
            field = field_class(choices=choices,
                                required=required,
                                initial=initial,
                                widget=StaticSelect2())

        # URL
        elif self.type == CustomFieldTypeChoices.TYPE_URL:
            field = LaxURLField(required=required, initial=initial)

        # Text
        else:
            field = forms.CharField(max_length=255,
                                    required=required,
                                    initial=initial)
            if self.validation_regex:
                field.validators = [
                    RegexValidator(
                        regex=self.validation_regex,
                        message=mark_safe(
                            f"Values must match this regex: <code>{self.validation_regex}</code>"
                        ))
                ]

        field.model = self
        field.label = str(self)
        if self.description:
            field.help_text = self.description

        return field
Esempio n. 33
0
def validate_id(value):
    """Validate Id"""
    regexObj = re.compile('^[1-9]+[0-9]*$')
    obj = RegexValidator(regexObj, _('Validation error. Id expected.'))
    obj.__call__(value)
Esempio n. 34
0
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModel
from reversion.models import Version

from judge.models.contest import Contest
from judge.models.interface import BlogPost
from judge.models.problem import Problem
from judge.models.profile import Profile
from judge.utils.cachedict import CacheDict

__all__ = ['Comment', 'CommentLock', 'CommentVote']

comment_validator = RegexValidator(
    r'^[pcs]:[a-z0-9]+$|^b:\d+$',
    _(r'Page code must be ^[pcs]:[a-z0-9]+$|^b:\d+$'))


class VersionRelation(GenericRelation):
    def __init__(self):
        super(VersionRelation, self).__init__(Version,
                                              object_id_field='object_id')

    def get_extra_restriction(self, where_class, alias, remote_alias):
        cond = super(VersionRelation,
                     self).get_extra_restriction(where_class, alias,
                                                 remote_alias)
        field = self.remote_field.model._meta.get_field('db')
        lookup = field.get_lookup('exact')(field.get_col(remote_alias),
                                           'default')
Esempio n. 35
0
def validate_password(value):
    """Validate Password"""
    regexObj = re.compile('^[a-zA-Z0-9_.$%&]+')
    obj = RegexValidator(regexObj, _('Validation error. Password expected.'))
    obj.__call__(value)
Esempio n. 36
0
class AbstractCommunicationEventType(models.Model):
    """
    A 'type' of communication.  Like an order confirmation email.
    """

    #: Code used for looking up this event programmatically.
    # e.g. PASSWORD_RESET. AutoSlugField uppercases the code for us because
    # it's a useful convention that's been enforced in previous Oscar versions
    code = AutoSlugField(
        _('Code'),
        max_length=128,
        unique=True,
        populate_from='name',
        separator="_",
        uppercase=True,
        editable=True,
        validators=[
            RegexValidator(
                regex=r'^[a-zA-Z_][0-9a-zA-Z_]*$',
                message=_(
                    "Code can only contain the letters a-z, A-Z, digits, "
                    "and underscores, and can't start with a digit."))
        ],
        help_text=_("Code used for looking up this event programmatically"))

    #: Name is the friendly description of an event for use in the admin
    name = models.CharField(
        _('Name'),
        max_length=255,
        help_text=_("This is just used for organisational purposes"))

    # We allow communication types to be categorised
    # For backwards-compatibility, the choice values are quite verbose
    ORDER_RELATED = 'Order related'
    USER_RELATED = 'User related'
    CATEGORY_CHOICES = ((ORDER_RELATED, _('Order related')),
                        (USER_RELATED, _('User related')))

    category = models.CharField(_('Category'),
                                max_length=255,
                                default=ORDER_RELATED,
                                choices=CATEGORY_CHOICES)

    # Template content for emails
    # NOTE: There's an intentional distinction between None and ''. None
    # instructs Oscar to look for a file-based template, '' is just an empty
    # template.
    email_subject_template = models.CharField(_('Email Subject Template'),
                                              max_length=255,
                                              blank=True,
                                              null=True)
    email_body_template = models.TextField(_('Email Body Template'),
                                           blank=True,
                                           null=True)
    email_body_html_template = models.TextField(_('Email Body HTML Template'),
                                                blank=True,
                                                null=True,
                                                help_text=_("HTML template"))

    # Template content for SMS messages
    sms_template = models.CharField(_('SMS Template'),
                                    max_length=170,
                                    blank=True,
                                    null=True,
                                    help_text=_("SMS template"))

    date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
    date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)

    objects = CommunicationTypeManager()

    # File templates
    email_subject_template_file = 'oscar/customer/emails/commtype_%s_subject.txt'
    email_body_template_file = 'oscar/customer/emails/commtype_%s_body.txt'
    email_body_html_template_file = 'oscar/customer/emails/commtype_%s_body.html'
    sms_template_file = 'oscar/customer/sms/commtype_%s_body.txt'

    class Meta:
        abstract = True
        app_label = 'customer'
        verbose_name = _("Communication event type")
        verbose_name_plural = _("Communication event types")

    def get_messages(self, ctx=None):
        """
        Return a dict of templates with the context merged in

        We look first at the field templates but fail over to
        a set of file templates that follow a conventional path.
        """
        code = self.code.lower()

        # Build a dict of message name to Template instances
        templates = {
            'subject': 'email_subject_template',
            'body': 'email_body_template',
            'html': 'email_body_html_template',
            'sms': 'sms_template'
        }
        for name, attr_name in templates.items():
            field = getattr(self, attr_name, None)
            if field is not None:
                # Template content is in a model field
                templates[name] = engines['django'].from_string(field)
            else:
                # Model field is empty - look for a file template
                template_name = getattr(self, "%s_file" % attr_name) % code
                try:
                    templates[name] = get_template(template_name)
                except TemplateDoesNotExist:
                    templates[name] = None

        # Pass base URL for serving images within HTML emails
        if ctx is None:
            ctx = {}
        ctx['static_base_url'] = getattr(settings, 'OSCAR_STATIC_BASE_URL',
                                         None)

        messages = {}
        for name, template in templates.items():
            messages[name] = template.render(ctx) if template else ''

        # Ensure the email subject doesn't contain any newlines
        messages['subject'] = messages['subject'].replace("\n", "")
        messages['subject'] = messages['subject'].replace("\r", "")

        return messages

    def __str__(self):
        return self.name

    def is_order_related(self):
        return self.category == self.ORDER_RELATED

    def is_user_related(self):
        return self.category == self.USER_RELATED
Esempio n. 37
0
def validate_email(value):
    """Validate Email"""
    regexObj = re.compile('^([\w.])+\@([a-z0-9]([-a-z0-9]*[a-z0-9])?\\.)+((a[cdefgilmnoqrstuwxz]|aero|arpa)|(b[abdefghijmnorstvwyz]|biz)|(c[acdfghiklmnorsuvxyz]|cat|com|coop)|d[ejkmoz]|(e[ceghrstu]|edu)|f[ijkmor]|(g[abdefghilmnpqrstuwy]|gov)|h[kmnrtu]|(i[delmnoqrst]|info|int)|(j[emop]|jobs)|k[eghimnprwyz]|l[abcikrstuvy]|(m[acdghklmnopqrstuvwxyz]|mil|mobi|museum)|(n[acefgilopruz]|name|net)|(om|org)|(p[aefghklmnrstwy]|pro)|qa|r[eouw]|s[abcdeghijklmnortvyz]|(t[cdfghjklmnoprtvwz]|travel)|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw])')
    obj = RegexValidator(regexObj, _('Validation error. Email expected.'))
    obj.__call__(value)
Esempio n. 38
0
class Order(models.Model):
    """
    The model class that represents an order

    Args:
        models ([class]): [description]

    Returns:
        [string]: [the string of user and date of creation]
    """

    PAYMENT_CHOICES = ((u'H', u'Наличными курьеру'),
                       (u'K', u'Оплата картой курьеру'),
                       (u'G', u'Оплатить с помощью Google Pay'),
                       (u'A', u'Оплатить с помощью Apple Pay'))
    ORDER_STATUSES = (
        (u'N', u'Новый'),
        (u'P', u'В Пути'),
        (u'D', u'Доставлен'),
    )

    user = models.ForeignKey(User,
                             related_name='orders',
                             on_delete=models.CASCADE,
                             verbose_name='Пользователь',
                             null=True,
                             blank=True)
    orderStatus = models.CharField(("Статус Заказа"),
                                   max_length=100,
                                   choices=ORDER_STATUSES,
                                   default='N')
    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{11,25}$',
        message=
        "Номер телефона должен быть в формате: '+999999999'.Разрешено до 20 символов."
    )
    phone = models.CharField(("Номер телефона"),
                             validators=[phone_regex],
                             max_length=25)
    total = models.DecimalField(("Итоговая сумма"),
                                max_digits=8,
                                decimal_places=0,
                                null=True,
                                blank=True)
    deliverTo = models.CharField(("Доставить к"), max_length=255)

    # order_items     = models.ManyToManyField(CartItem, verbose_name="Заказанные блюда")
    restaurant = models.CharField(max_length=200,
                                  verbose_name="Ресторан",
                                  default="нет")
    address = models.CharField(("Адрес"), max_length=255)

    comment = models.CharField(("Комментарий"),
                               max_length=255,
                               null=True,
                               blank=True)

    personsAmount = models.IntegerField(("Количество персон"), default=1)

    paymentMode = models.CharField(("Способ оплаты"),
                                   max_length=100,
                                   default='Наличными курьеру')

    created_at = models.DateTimeField(("Заказ создан"), auto_now_add=True)

    class Meta:
        verbose_name = "Заказ"
        verbose_name_plural = "Заказы"

    def __str__(self):
        return "%s заказал %s" % (self.user, self.created_at)
Esempio n. 39
0
class Endpoint(models.Model):
    """
    后端 API 的配置信息
    """
    # endpoint 的唯一名称, 可以使用中文, 由于可能存在多个相同的 name, 但是 url 或 uri 不一样
    # 因此需要有一个唯一的名称来区分
    unique_name = models.CharField(unique=True, max_length=128)
    # endpoint 名称, 需要使用在 url 上
    name = models.CharField(max_length=128,
                            validators=[
                                RegexValidator(regex=r'^[\-_0-9a-zA-Z]+$',
                                               message='仅使用字母数字和下划线')
                            ])

    version = models.CharField(max_length=128,
                               validators=[
                                   RegexValidator(regex=r'^[\-_0-9a-zA-Z]+$',
                                                  message='仅使用字母数字和下划线')
                               ])

    # 完整的URL,如 http://192.168.10.2:9090
    url = models.URLField(max_length=512, default='', blank=True)
    # 是否为内置的 endpoint, 如果是就可以不用输入 url
    is_builtin = models.BooleanField(default=False)
    # 是否启用访问控制列表
    enable_acl = models.BooleanField(default=False)
    # 是否启用 hmac 签名
    enable_hmac = models.BooleanField(default=True)
    # 配置超时时间,默认情况下 Tornado 是 20.0,避免有的网站很慢,需要很久才响应
    # Timeout for initial connection in seconds
    async_http_connect_timeout = models.IntegerField(
        default=DEFAULT_ASYNC_HTTP_CONNECT_TIMEOUT)
    # Timeout for entire request in seconds
    async_http_request_timeout = models.IntegerField(
        default=DEFAULT_ASYNC_HTTP_REQUEST_TIMEOUT)
    # 是否需要验证登陆
    require_login = models.BooleanField(default=False)

    # 备注
    memo = models.CharField(blank=True, max_length=512)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        app_label = 'dashboard'
        ordering = ['name', 'version']
        db_table = 'dashboard_endpoint'

    def to_json_dict(self, skip_id=False):
        if self.url is not None:
            try:
                url_parsed = urlparse(self.url)
                netloc = url_parsed.netloc
            except Exception as e:
                logger.error(e)
                netloc = None
        else:
            netloc = None

        d = {
            'unique_name': self.unique_name,
            'name': self.name,
            'url': self.url,
            'is_builtin': self.is_builtin,
            'netloc': netloc,
            'version': self.version,
            'enable_acl': self.enable_acl,
            'enable_hmac': self.enable_hmac,
            'require_login': self.require_login,
            'async_http_connect_timeout': self.async_http_connect_timeout,
            'async_http_request_timeout': self.async_http_request_timeout,
            'memo': self.memo,
        }

        if hasattr(self, 'enable'):
            d['enable'] = self.enable

        # 是否要过滤id
        if not skip_id:
            d['id'] = self.id

        if hasattr(self, 'acl_rules'):
            d['acl_rules'] = [t.to_json_dict(skip_id) for t in self.acl_rules]

        return d

    def __unicode__(self):
        return self.name

    @classmethod
    def get_all_in_json(cls):
        data = Endpoint.objects.filter()
        for t in data:
            t.acl_rules = ACLRule.get_rules(t.id)

        return [t.to_json_dict() for t in data]
Esempio n. 40
0
 def __init__(self, message=u'请输入合法的中国大陆手机号', code=None):
     RegexValidator.__init__(self, regex='^1[0-9]{10}$',
         message=message, code=code)