Esempio n. 1
0
from django.core.validators import RegexValidator
from django.utils.translation import gettext_lazy as _

PASS_NUMBER_VALIDATOR = RegexValidator(
    r'[A-Z]{2}\d{7}', message=_('Passport number format is: XX1234567'))

PASS_ID_NUMBER_VALIDATOR = RegexValidator(
    r'\d{7}[A-Z]\d{3}[A-Z]{2}\d', message=_('ID format is: 1234567X123XX1'))
Esempio n. 2
0
class UserSessionLog(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.SET(get_sentinel_user))
    user_email = models.EmailField()
    otp_used_for_pass_change = models.CharField(
        _('otp'),
        help_text="Please Enter valid OTP sent to your Email",
        max_length=6,
        validators=[
            RegexValidator(r'^\d{6}$',
                           message=_('OTP shoud be of 6 digits'),
                           code='invalid')
        ])

    otp_used_while_passlogin_create = models.CharField(
        _('otp'),
        help_text="Please Enter valid OTP sent to your Email",
        max_length=6,
        validators=[
            RegexValidator(r'^\d{6}$',
                           message=_('OTP shoud be of 6 digits'),
                           code='invalid')
        ])

    otp_used_for_otplogin = models.CharField(
        _('otp'),
        help_text="Please Enter valid OTP sent to your Email",
        max_length=6,
        validators=[
            RegexValidator(r'^\d{6}$',
                           message=_('OTP shoud be of 6 digits'),
                           code='invalid')
        ])

    device_type = models.CharField(max_length=255)
    ip_address = models.GenericIPAddressField()
    created_time = models.DateTimeField(default=timezone.now)
    action_type = models.ForeignKey(ActionTypeForUserSessionLog,
                                    on_delete=models.PROTECT)


#We have to pass initial data to ActionTypeForUserSessionLog model:
#https://docs.djangoproject.com/en/2.2/howto/initial-data/#providing-data-with-fixtures
#Create a fixtures folder in any app and then name it something then do
# manage.py loaddata something.

#You’ll store this data in a fixtures directory inside your app.

#Loading data is easy: just call manage.py loaddata <fixturename>, where
#<fixturename> is the name of the fixture file you’ve created. Each time you run
#loaddata, the data will be read from the fixture and re-loaded into the
#database. Note this means that if you change one of the rows created by a
#fixture and then run loaddata again, you’ll wipe out any changes you’ve made.

###    [
###      {
###        "model": "custom_user.ActionTypeForUserSessionLog",
###        "pk": 1,
###        "fields": {
###          "action": "pass_change",
###        }
###      },
###      {
###        "model": "custom_user.ActionTypeForUserSessionLog",
###        "pk": 2,
###        "fields": {
###          "action": "login_by_otp",
###        }
###      },
###      {
###        "model": "custom_user.ActionTypeForUserSessionLog",
###        "pk": 3,
###        "fields": {
###          "action": "login_by_pass",
###        }
###      },
###      {
###        "model": "custom_user.ActionTypeForUserSessionLog",
###        "pk": 4,
###        "fields": {
###          "action": "passlogin_email_validation",
###        }
###      }
###    ]
Esempio n. 3
0
class OrganizerSettingsForm(SettingsForm):

    organizer_info_text = I18nFormField(
        label=_('Info text'),
        required=False,
        widget=I18nTextarea,
        help_text=_('Not displayed anywhere by default, but if you want to, you can use this e.g. in ticket templates.')
    )

    event_team_provisioning = forms.BooleanField(
        label=_('Allow creating a new team during event creation'),
        help_text=_('Users that do not have access to all events under this organizer, must select one of their teams '
                    'to have access to the created event. This setting allows users to create an event-specified team'
                    ' on-the-fly, even when they do not have \"Can change teams and permissions\" permission.'),
        required=False,
    )

    primary_color = forms.CharField(
        label=_("Primary color"),
        required=False,
        validators=[
            RegexValidator(regex='^#[0-9a-fA-F]{6}$',
                           message=_('Please enter the hexadecimal code of a color, e.g. #990000.')),
        ],
        widget=forms.TextInput(attrs={'class': 'colorpickerfield'})
    )
    theme_color_success = forms.CharField(
        label=_("Accent color for success"),
        help_text=_("We strongly suggest to use a shade of green."),
        required=False,
        validators=[
            RegexValidator(regex='^#[0-9a-fA-F]{6}$',
                           message=_('Please enter the hexadecimal code of a color, e.g. #990000.')),
        ],
        widget=forms.TextInput(attrs={'class': 'colorpickerfield'})
    )
    theme_color_danger = forms.CharField(
        label=_("Accent color for errors"),
        help_text=_("We strongly suggest to use a shade of red."),
        required=False,
        validators=[
            RegexValidator(regex='^#[0-9a-fA-F]{6}$',
                           message=_('Please enter the hexadecimal code of a color, e.g. #990000.')),

        ],
        widget=forms.TextInput(attrs={'class': 'colorpickerfield'})
    )
    theme_color_background = forms.CharField(
        label=_("Page background color"),
        required=False,
        validators=[
            RegexValidator(regex='^#[0-9a-fA-F]{6}$',
                           message=_('Please enter the hexadecimal code of a color, e.g. #990000.')),

        ],
        widget=forms.TextInput(attrs={'class': 'colorpickerfield no-contrast'})
    )
    theme_round_borders = forms.BooleanField(
        label=_("Use round edges"),
        required=False,
    )
    organizer_homepage_text = I18nFormField(
        label=_('Homepage text'),
        required=False,
        widget=I18nTextarea,
        help_text=_('This will be displayed on the organizer homepage.')
    )
    organizer_logo_image = ExtFileField(
        label=_('Header image'),
        ext_whitelist=(".png", ".jpg", ".gif", ".jpeg"),
        required=False,
        help_text=_('If you provide a logo image, we will by default not show your organization name '
                    'in the page header. By default, we show your logo with a size of up to 1140x120 pixels. You '
                    'can increase the size with the setting below. We recommend not using small details on the picture '
                    'as it will be resized on smaller screens.')
    )
    organizer_logo_image_large = forms.BooleanField(
        label=_('Use header image in its full size'),
        help_text=_('We recommend to upload a picture at least 1170 pixels wide.'),
        required=False,
    )
    event_list_type = forms.ChoiceField(
        label=_('Default overview style'),
        choices=(
            ('list', _('List')),
            ('calendar', _('Calendar'))
        )
    )
    event_list_availability = forms.BooleanField(
        label=_('Show availability in event overviews'),
        help_text=_('If checked, the list of events will show if events are sold out. This might '
                    'make for longer page loading times if you have lots of events and the shown status might be out '
                    'of date for up to two minutes.'),
        required=False
    )
    organizer_link_back = forms.BooleanField(
        label=_('Link back to organizer overview on all event pages'),
        required=False
    )
    locales = forms.MultipleChoiceField(
        choices=settings.LANGUAGES,
        label=_("Use languages"),
        widget=MultipleLanguagesWidget,
        help_text=_('Choose all languages that your organizer homepage should be available in.')
    )
    primary_font = forms.ChoiceField(
        label=_('Font'),
        choices=[
            ('Open Sans', 'Open Sans')
        ],
        widget=FontSelect,
        help_text=_('Only respected by modern browsers.')
    )
    favicon = ExtFileField(
        label=_('Favicon'),
        ext_whitelist=(".ico", ".png", ".jpg", ".gif", ".jpeg"),
        required=False,
        help_text=_('If you provide a favicon, we will show it instead of the default pretix icon. '
                    'We recommend a size of at least 200x200px to accomodate most devices.')
    )
    giftcard_length = forms.IntegerField(
        label=_('Length of gift card codes'),
        help_text=_('The system generates by default {}-character long gift card codes. However, if a different length '
                    'is required, it can be set here.'.format(settings.ENTROPY['giftcard_secret'])),
        required=False
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['primary_font'].choices += [
            (a, {"title": a, "data": v}) for a, v in get_fonts().items()
        ]
Esempio n. 4
0
class RegistrationForm(UserCreationForm):
    password1 = forms.CharField(widget=forms.PasswordInput(
        attrs={'placeholder': 'Password'}))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}), validators=[RegexValidator(
        regex="^(?=.*[0-9]+.*)(?=.*[a-zA-Z]+.*)[0-9a-zA-Z]{6,}$",
        message="Password must contain at least one letter, at least one number, and be longer than six charaters.",
        code="Weak Password"
    )]
    )

    class Meta:
        model = Account
        fields = ['email', 'username', 'password1', 'password2']
        widgets = {
            'email': forms.EmailInput(attrs={'placeholder': 'Email-Address'}),
            'username': forms.TextInput(attrs={'placeholder': 'UserName'}),
        }
Esempio n. 5
0
from django.db import models
from django.core.validators import RegexValidator

ColorValidator = RegexValidator(
    regex=r'^[A-Fa-f0-9]{6}$',
    message="Entrez une couleur valide (pas de '#' et 6 caractères)",
)


class Category(models.Model):
    name = models.CharField(blank=False, max_length=255)
    color = models.CharField(blank=False,
                             max_length=6,
                             validators=[ColorValidator])

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"


class Subcategory(models.Model):
    name = models.CharField(blank=False, max_length=255)
    category = models.ForeignKey(Category, null=True)

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

    class Meta:
Esempio n. 6
0
File: forms.py Progetto: finceh/bac
class EmailTokenForm(forms.Form):
    token = forms.CharField(label='Токен',
                            validators=[RegexValidator(r'^[\w\d]{12}$')])
class Dialect(ModelWithName):
    color = models.CharField(max_length=7, validators=[
        RegexValidator('^#([0-9a-fA-F]{3})+$', 'Enter an RGB color code.'),
    ])
Esempio n. 8
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. 9
0
class ScholariumProfile(UserenaBaseProfile):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                unique=True,
                                verbose_name=_('user'),
                                related_name='my_profile')
    stufe_choices = [(0, 'Interessent'), (1, 'Gast'), (2, 'Teilnehmer'),
                     (3, 'Scholar'), (4, 'Partner'), (5, 'Beirat'),
                     (6, 'Patron')]
    stufe = models.IntegerField(choices=stufe_choices, default=0)
    anrede = models.CharField(max_length=4,
                              choices=[('Herr', 'Herr'), ('Frau', 'Frau')],
                              default='Herr',
                              null=True)
    tel = models.CharField(max_length=20, null=True, blank=True)
    firma = models.CharField(max_length=30, null=True, blank=True)
    strasse = models.CharField(max_length=30, null=True, blank=True)
    plz = models.CharField(max_length=5,
                           validators=[RegexValidator('^[0-9]+$')],
                           null=True,
                           blank=True)
    ort = models.CharField(max_length=30, null=True, blank=True)
    land = CountryField(blank_label='- Bitte Ihr Land auswählen -', null=True)
    guthaben = models.SmallIntegerField(default=0)
    titel = models.CharField(max_length=30, null=True, blank=True)
    anredename = models.CharField(max_length=30, null=True, blank=True)
    letzte_zahlung = models.DateField(null=True, blank=True)
    datum_ablauf = models.DateField(null=True, blank=True)
    alt_id = models.SmallIntegerField(default=0, editable=False)
    alt_notiz = models.CharField(max_length=255,
                                 null=True,
                                 default='',
                                 editable=False)
    alt_scholien = models.SmallIntegerField(default=0,
                                            null=True,
                                            editable=False)
    alt_mahnstufe = models.SmallIntegerField(default=0,
                                             null=True,
                                             editable=False)
    alt_auslaufend = models.SmallIntegerField(default=0,
                                              null=True,
                                              editable=False)
    alt_gave_credits = models.SmallIntegerField(default=0,
                                                null=True,
                                                editable=False)
    alt_registration_ip = models.GenericIPAddressField(editable=False,
                                                       null=True)

    def get_Status(self):
        status = [(0, "Kein Unterstützer"), (1, "Abgelaufen"),
                  (2, "30 Tage bis Ablauf"), (3, "Aktiv")]
        if self.datum_ablauf == None:
            return status[0]
        else:
            verbleibend = (self.datum_ablauf - datetime.now().date()).days
            if self.stufe == 0:
                return status[0]
            elif verbleibend < 0:
                return status[1]
            elif verbleibend < 30:
                return status[2]
            else:
                return status[3]

    def guthaben_aufladen(self, betrag):
        """ wird spaeter nuetzlich, wenn hier mehr als die eine Zeile^^ """
        self.guthaben += int(betrag)
        self.save()

    def adresse_ausgeben(self):
        return """%s
%s
%s %s
%s""" % (self.user.get_full_name(), self.strasse, self.plz, self.ort,
         self.land.name if self.land else '')

    class Meta():
        verbose_name = 'Nutzerprofil'
        verbose_name_plural = 'Nutzerprofile'
Esempio n. 10
0
'''
Created on Jan 14, 2013

@author: CarolinaFernandez
'''

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

RESOURCE_SR_RE = "^([0-9a-zA-Z\-]){1,64}$"
TEMPERATURE_SCALE_CHOICES = (
    ('C', 'Celsius'),
    ('F', 'Fahrenheit'),
    ('K', 'Kelvin'),
)


def validate_temperature_scale(scale):
    """
    Validates the chosen temperature scale against the set 'indices'.
    """
    if scale not in [t[0] for t in TEMPERATURE_SCALE_CHOICES]:
        raise ValidationError("Invalid scale: please choose one from the list")


validate_resource_name = RegexValidator(
    re.compile(RESOURCE_SR_RE),
    u"Please do not use accented characters, symbols, underscores or whitespaces.",
    "invalid")
Esempio n. 11
0
        super().save_user(user)
        obj = OrganizationUser(user=user,
                               organization=self.organization,
                               is_admin=False)
        obj.full_clean()
        obj.save()

    class Meta(AbstractRadiusBatch.Meta):
        abstract = False
        unique_together = ('name', 'organization')
        swappable = swappable_setting('openwisp_radius', 'RadiusBatch')


key_validator = RegexValidator(
    _lazy_re_compile('^[^\s/\.]+$'),
    message=_('Key must not contain spaces, dots or slashes.'),
    code='invalid',
)


def generate_token():
    return get_random_string(length=32)


class OrganizationRadiusSettings(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    organization = models.OneToOneField('openwisp_users.Organization',
                                        verbose_name=_('organization'),
                                        related_name='radius_settings',
                                        on_delete=models.CASCADE)
    token = models.CharField(max_length=32,
Esempio n. 12
0
class Order(models.Model):
    """
    Creates Order Model containing data on each order
    which also potentially contains multiple products
    """
    order_number = models.CharField(max_length=36, default=uuid.uuid4,
                                    editable=False)
    user_profile = models.ForeignKey(Profile, on_delete=models.SET_NULL,
                                     null=True, blank=True,
                                     related_name='user_orders')
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    full_name = models.CharField(max_length=70, editable=False,
                                 default='')
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="Enter phone number in a format: "
                                         "'+111111111' and no longer that "
                                         "15 digits.")
    phone_number = models.CharField(validators=[phone_regex], max_length=16,
                                    default=0)
    email = models.EmailField(max_length=254)
    address_line_1 = models.CharField(max_length=100,)
    address_line_2 = models.CharField(max_length=100, null=True, blank=True)
    city = models.CharField('city or town', max_length=85)
    region = models.CharField('region or county', max_length=85, null=True,
                              blank=True)
    country = CountryField(blank_label='Country *')
    postcode = models.CharField('post/zip code', max_length=10)
    order_date = models.DateTimeField(auto_now_add=True)
    dispatch_date = models.DateTimeField('order dispatched on',
                                         null=True, blank=True)
    est_dispatch_dte = models.DateTimeField('estimated order dispatch date',
                                            editable=False, null=True,
                                            blank=True)
    delivery_date = models.DateTimeField('order delivered on',
                                         null=True, blank=True)
    est_deliery_dte = models.DateTimeField('estimated order delivery date',
                                           editable=False, null=True,
                                           blank=True)
    delivery_type = models.ForeignKey(DeliveryType, on_delete=models.CASCADE)
    delivery_cost = models.DecimalField(max_digits=7, decimal_places=2,
                                        default=0)
    subtotal = models.DecimalField(max_digits=7, decimal_places=2, default=0)
    total = models.DecimalField(max_digits=7, decimal_places=2, default=0)
    original_cart = models.TextField(default='')
    stripe_pid = models.CharField(max_length=254, default='')

    def total_amount(self):
        """
        Calculate the subtotal, delivery cost and the total,
        depending on the delivery type selected and products
        in the order
        """
        self.subtotal = self.order_line.aggregate(
            Sum('line_total'))['line_total__sum'] or 0
        if self.subtotal < self.delivery_type.limit:
            self.delivery_cost = self.delivery_type.const
        else:
            self.delivery_cost = self.subtotal * Decimal(
                self.delivery_type.rate / 100)
        self.total = self.subtotal + self.delivery_cost
        self.save()

    def save(self, *args, **kwargs):
        """
        Calculate fields when Order is saved based
        on membership and delivery type
        """
        # Get delivery and dispatch dates
        date_now = timezone.now()
        dispatch_days = timezone.timedelta(
            days=self.delivery_type.dispatch_speed)
        delivery_days = timezone.timedelta(
            days=self.delivery_type.delivery_speed)
        self.est_dispatch_dte = date_now + dispatch_days
        self.est_deliery_dte = date_now + delivery_days
        # Order number in uppercase
        self.order_number = str(self.order_number).upper()
        # Full name
        self.full_name = f'{self.first_name} {self.last_name}'

        # If logged in user, calculate delivery amount and discount
        if self.user_profile and self.user_profile.membership:
            # Get order count for the user
            user_orders_count = Order.objects.filter(
                user_profile=self.user_profile).count()
            # If paid memebrship, apply free delivery
            if self.user_profile.membership.name != 'Basic':
                self.delivery_cost = 0
                # Discount for the first order
                if user_orders_count == 0:
                    discount = self.user_profile.membership.first_order_disc
                # Discount for all other orders
                else:
                    discount = self.user_profile.membership.overall_discount
            # Unpaid memebrship
            else:
                # Discount for the first order
                if user_orders_count == 0:
                    discount = self.user_profile.membership.first_order_disc
                # No overall discount
                else:
                    discount = 0

            # Calculate total with delivery and discount
            discount_price = round(self.subtotal * Decimal(discount / 100), 2)
            self.total = self.subtotal + self.delivery_cost - discount_price
        super().save(*args, **kwargs)

    def __str__(self):
        return self.order_number
Esempio n. 13
0
        else:
            # print(ord('a'), ord(s_), ord('z'), s_)
            raise ValidationError(
                u'В строке "%s" привутствуют запрещенные символы!' % string)


def validator_warranty(value):
    if value < 0:
        raise ValidationError(
            u'%i - не может быть верным гарантийным сроком ' % value)
    if value > 60:
        raise ValidationError(u'%i - слишком большой гарантийный срок' % value)


login = RegexValidator(
    r'^[\w.@+-]+$',
    message='Enter a valid username. '
    'This value may contain only letters, numbers and [@/./+/-] characters.')
numeric = RegexValidator(r'^[0-9]*$',
                         message=u'допустимы только цифровые символы.')
alpha_all = RegexValidator(r'^[a-zA-Zа-яА-Я]*$',
                           message=u'допустимы только буквенные символы.')
alpha_lat = RegexValidator(r'^[a-zA-Z]*$',
                           message=u'допустимы только латинские буквы.')
hexnumeric = RegexValidator(
    r'^[0-9a-fA-F]*$',
    message=u'должен указывается в шестнадцатиричной системе.')
alphanumeric = RegexValidator(
    r'^[0-9a-zA-Z]*$', message=u'только буквенноцифровые символы допустимы.')
phone = RegexValidator(
    regex=r'^\+?1?\d{11}$',
    message=
Esempio n. 14
0
     'Filho(a) ou Enteado(a), universitario(a) ou cursando escola técnica de 2º Grau'
     ),
    ('5',
     'Irmão(ã), Neto(a) ou Bisneto(a) sem arrimo dos pais, do(a) qual detenha a guarda judicial '
     ),
    ('6',
     'Irmão(ã), Neto(a) ou Bisneto(a) sem arrimo dos pais, universitário(a) ou cursando escola técnica de 2º Grau do(a) qual detenha Guarda Judicial'
     ), ('7', 'Pais, avós e bisavós'),
    ('8', 'Menor pobre do qual detenha guarda judicial'),
    ('9', 'A pessoa absolutamente incapaz, do qual seja tutor ou curador'),
    ('10', 'Ex-Cônjuge')
]

# Regex Validators
phoneRegex = RegexValidator(
    regex=r'^(\+\d{0,4})?(\(\d{0,3}\))?([0-9\-]{7,15})$',
    message="Entre Telefone no Formato: '(DDD)99999-9999'.")

# Models --------------------------------------------------------------------------------------------------------------------------------------------


# 1 - Basic Info
class BasicInfo(models.Model):

    id = models.BigAutoField(primary_key=True)

    nome = models.CharField(max_length=100,
                            null=True,
                            blank=True,
                            verbose_name="Nome")
    nome_responsavel = models.CharField(max_length=100,
Esempio n. 15
0
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.core.validators import RegexValidator

from tablemanager.models import Workspace
from borg_utils.borg_config import BorgConfiguration
from borg_utils.utils import file_md5
from borg_utils.transaction import TransactionMixin
from borg_utils.signals import refresh_select_choices, inherit_support_receiver
from borg_utils.resource_status import ResourceStatus, ResourceStatusMixin, ResourceAction
from borg_utils.hg_batch_push import try_set_push_owner, try_clear_push_owner, increase_committed_changes, try_push_to_repository

logger = logging.getLogger(__name__)

slug_re = re.compile(r'^[a-zA-Z0-9_\-]+$')
validate_slug = RegexValidator(
    slug_re,
    "Slug can only start with letters or underscore, and contain letters, numbers and underscore",
    "invalid")

getcapabilities_ns = {"xlink": "http://www.w3.org/1999/xlink"}

default_layer_geoserver_setting = {
    "create_cache_layer": True,
    "client_cache_expire": 0,
    "meta_tiling_factor": [1, 1],
    "server_cache_expire": 0,
    "gridsets": {
        "EPSG:3857": {
            "enabled": True
        },
        "internal.fms.wa.gov.au/apps/sss": {
            "enabled": True
Esempio n. 16
0
from django.core.validators import RegexValidator, validate_email
from django import forms

# These are used for image manipulation
from PIL import Image
from io import BytesIO
from django.core.files import File

alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$',
                              'Only alphanumeric characters are allowed.')


# Used for the Login Page
#---------------------------------------
class LoginForm(forms.Form):
    """Login Form to validate the login credentials"""

    cdinput = forms.CharField(max_length=128,
                              min_length=3,
                              required=True,
                              help_text="Used to check the username/email",
                              error_messages={
                                  "required":
                                  "Username/E-mail is required to login.",
                                  "max_length":
                                  "Username/E-mail is too long...",
                                  "min_length":
                                  "Username/E-mail is too short...",
                                  "invalid": "Username/E-mail is invalid!"
                              })
Esempio n. 17
0
class Step(HashIdMixin, TranslatableModel):
    Kind = Choices(
        ("metadata", _("Metadata")),
        ("onetime", _("One Time Apex")),
        ("managed", _("Managed Package")),
        ("data", _("Data")),
        ("other", _("Other")),
    )

    translations = TranslatedFields(
        name=models.CharField(max_length=1024,
                              help_text="Customer facing label"),
        description=models.TextField(blank=True),
    )

    plan = models.ForeignKey(Plan,
                             on_delete=models.CASCADE,
                             related_name="steps")
    is_required = models.BooleanField(default=True)
    is_recommended = models.BooleanField(default=True)
    kind = models.CharField(choices=Kind, default=Kind.metadata, max_length=64)
    path = models.CharField(max_length=2048,
                            help_text="dotted path e.g. flow1.flow2.task_name")
    step_num = models.CharField(
        max_length=64,
        help_text="dotted step number for CCI task",
        validators=[RegexValidator(regex=STEP_NUM)],
    )
    task_class = models.CharField(
        max_length=2048,
        help_text="dotted module path to BaseTask implementation")
    task_config = JSONField(default=dict, blank=True)
    source = JSONField(blank=True, null=True)

    class Meta:
        ordering = (DottedArray(F("step_num")), )

    @property
    def kind_icon(self):
        if self.kind == self.Kind.metadata:
            return "package"
        if self.kind == self.Kind.onetime:
            return "apex"
        if self.kind == self.Kind.managed:
            return "archive"
        if self.kind == self.Kind.data:
            return "paste"
        return None

    def to_spec(self, project_config, skip: bool = False):
        if self.source:
            project_config = project_config.include_source(self.source)
        task_class = import_class(self.task_class)
        assert issubclass(task_class, BaseTask)
        return StepSpec(
            step_num=self.step_num,
            task_name=self.
            path,  # skip from_flow path construction in StepSpec ctr
            task_config=self.task_config or {"options": {}},
            task_class=task_class,
            skip=skip,
            project_config=project_config,
        )

    def __str__(self):
        return f"Step {self.name} of {self.plan.title} ({self.step_num})"
Esempio n. 18
0
        if value is None:
            return value

        return PathValue(instance.__dict__[self.field_name])

    def __set__(self, instance, value):
        if instance is None:
            return self

        instance.__dict__[self.field_name] = value


path_label_validator = RegexValidator(
    r"^[A-Za-z0-9_.]+$",
    "A label is a sequence of alphanumeric characters and underscores separated by dots.",
    "invalid",
)


class PathFormField(forms.CharField):
    default_validators = [path_label_validator]


class PathField(TextField):
    default_validators = [path_label_validator]

    def db_type(self, connection):
        return "ltree"

    def formfield(self, **kwargs):
Esempio n. 19
0
class NotaFiscalSaida(NotaFiscal):
    tpnf = models.CharField(max_length=1,
                            choices=TP_NFE_ESCOLHAS,
                            default=u'1')
    n_nf_saida = models.CharField(max_length=9,
                                  validators=[RegexValidator(r'^\d{1,10}$')],
                                  unique=True)
    venda = models.ForeignKey('vendas.PedidoVenda',
                              related_name="venda_nfe",
                              on_delete=models.SET_NULL,
                              null=True,
                              blank=True)
    emit_saida = models.ForeignKey('cadastro.Empresa',
                                   related_name="emit_nfe_saida",
                                   on_delete=models.SET_NULL,
                                   null=True,
                                   blank=True)
    dest_saida = models.ForeignKey('cadastro.Cliente',
                                   related_name="dest_nfe_saida",
                                   on_delete=models.SET_NULL,
                                   null=True,
                                   blank=True)

    # Cobranca Fatura(NF-e)
    n_fat = models.CharField(max_length=60, null=True, blank=True, unique=True)
    v_orig = models.DecimalField(
        max_digits=13,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0.00'))],
        null=True,
        blank=True)
    v_desc = models.DecimalField(
        max_digits=13,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0.00'))],
        null=True,
        blank=True)
    v_liq = models.DecimalField(
        max_digits=13,
        decimal_places=2,
        validators=[MinValueValidator(Decimal('0.00'))],
        null=True,
        blank=True)
    grupo_cobr = models.BooleanField(default=True)

    class Meta:
        verbose_name = "Nota Fiscal"
        permissions = (
            ("view_notafiscal", "Can view nota fiscal"),
            ("emitir_notafiscal", "Pode emitir notas fiscais"),
            ("cancelar_notafiscal", "Pode cancelar notas fiscais"),
            ("gerar_danfe", "Pode gerar DANFE/DANFCE"),
            ("consultar_cadastro", "Pode consultar cadastro no SEFAZ"),
            ("inutilizar_notafiscal", "你可以不使用纳税申报单"),
            ("consultar_notafiscal", "Pode consultar notas fiscais"),
            ("baixar_notafiscal", "Pode baixar notas fiscais"),
            ("manifestacao_destinatario",
             "Pode efetuar manifestação do destinatário"),
        )

    @property
    def estado(self):
        if self.emit_saida:
            if self.emit_saida.endereco_padrao:
                return self.emit_saida.endereco_padrao.uf
        return ''

    def get_emit_cmun(self):
        if self.emit_saida:
            if self.emit_saida.endereco_padrao:
                return self.emit_saida.endereco_padrao.cmun
        return ''

    def __unicode__(self):
        s = u'Série %s,  Nº %s, Chave %s' % (self.serie, self.n_nf_saida,
                                             self.chave)
        return s

    def __str__(self):
        s = u'Série %s,  Nº %s, Chave %s' % (self.serie, self.n_nf_saida,
                                             self.chave)
        return s
Esempio n. 20
0
import re  # use a regular expression to validate a colour field

from django.db import models
# can validate a hex code using a regular expression
from django.core.validators import RegexValidator

# only matches hex codes of # + six hex digits
colour_re = re.compile('^#([A-Fa-f0-9]{6})$')
validate_colour = RegexValidator(colour_re, 'Please enter a valid colour',
                                 'invalid')


class ColourField(models.CharField):
    # we define a new custom field to hold tag colours
    # It's stored as a string, so it extends from CharField

    description = "A 6 character hex code, in the form #5ABCDE"

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 18
        kwargs['validators'] = [validate_colour]
        return super(ColourField, self).__init__(*args, **kwargs)
Esempio n. 21
0
        user.is_superuser = True
        # Checks if admin group exists, creates if not, and adds user.
        Group.objects.get_or_create(name="admin")
        admin_group = Group.objects.get(name="admin")
        admin_group.user_set.add(user)
        # Checks if member group exists, creates if not, and adds user.
        member_check = Group.objects.get_or_create(name="member")
        member_group = Group.objects.get(name="member")
        member_group.user_set.add(user)
        user.save(using=self._db)

        return user


phone_regex = RegexValidator(
    regex=r"^09\d{2}\d{7}$",
    message="Phone number must be entered in the following format: '09123456789'.",
)


class User(AbstractBaseUser, PermissionsMixin):
    """Custom user model that support email, phonenumber, etc."""

    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255, null=True, blank=True)
    phone = models.CharField(
        validators=[phone_regex], max_length=11, null=True, blank=True
    )
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    member_since = models.DateTimeField(auto_now_add=True, blank=True, null=True)
Esempio n. 22
0
import json
import re

from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import models
from django.utils.functional import curry
from django.utils.html import mark_safe, conditional_escape
from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils import six

from .widgets import AttributesWidget

regex_key_validator = RegexValidator(regex=r'^[a-z][-a-z0-9_]*\Z',
                                     flags=re.IGNORECASE,
                                     code='invalid')


class AttributesFormField(forms.CharField):
    empty_values = [None, '']

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('widget', AttributesWidget)
        super(AttributesFormField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if isinstance(value, six.string_types) and value:
            try:
                return json.loads(value)
            except ValueError as exc:
Esempio n. 23
0
class RegisterForm(forms.Form):
    email = forms.EmailField(
        label=_("Email address"),
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': 'Email address'
        }),
        help_text=_("Member's registered email address."))
    national_id = forms.CharField(
        label=_("National ID"),
        widget=forms.TextInput(attrs={
            'class': 'form-control',
        }),
        help_text=_("National ID Number as indicated on membership form."),
        validators=[
            RegexValidator(
                regex=r'\d{2}\d{6,7}[a-zA-Z]{1}\d{2}',
                message=
                'ID Number should match format like: 58 398766 B 25, without the spaces.',
            )
        ])
    username = forms.CharField(
        label=_("Username"),
        widget=forms.TextInput(attrs={
            'class': 'form-control',
        }),
        help_text=_("Create a username for your account."))
    password = forms.CharField(
        label=_("Password"),
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
        }),
        help_text=_("Create account Password."))
    password2 = forms.CharField(
        label=_("Confirm password"),
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
        }),
        help_text=_("Repeat your password to confirm it."))

    def clean(self):
        data = super().clean()
        email = data.get('email')
        national_id = data.get('national_id')
        password = data.get('password')
        password2 = data.get('password2')
        if len(password) < 6:
            self.add_error(
                'password',
                "Password too short. Please enter at least 6 Characters.")
        else:
            if password != password2:
                self.add_error(
                    'password2',
                    "Failed to confirm your password. Please try again.")

        if Member.objects.filter(email_address=email).count() < 1:
            self.add_error("email",
                           "No membership record found with that email!")
        else:
            if Member.objects.filter(
                    email_address=email)[0].national_id != national_id:
                self.add_error(
                    None,
                    "Failed to find an account with such details. Please contact your branch"
                )

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if User.objects.filter(username=username).exists():
            self.add_error('username',
                           "Username already taken, please choose another.")
        else:
            if len(username) > 12:
                self.add_error("username",
                               'Username too long. Max: 12 Characters.')
        return username

    def save(self):
        user = User.objects.create_user(
            username=self.cleaned_data.get('username'),
            password=self.cleaned_data.get('password'))
        if User.objects.filter(email=self.cleaned_data.get('email')).exists():
            pass
        else:
            user.email = self.cleaned_data.get('email')
            user.save()
        member = Member.objects.get(
            email_address=self.cleaned_data.get("email"))
        member.user_account = user
        member.save()
        return True
Esempio n. 24
0
    def clean(self):
        cleaned_data = super().clean()

        if not (cleaned_data.get('org_unit_id')
                or cleaned_data.get('org_unit_column')):
            self.add_error(
                'org_unit_column',
                _('Either "OrgUnitID" or "OrgUnitID column" is required.'))

        if (cleaned_data.get('org_unit_id')
                and cleaned_data.get('org_unit_column')):
            self.add_error(
                'org_unit_column',
                _('Either "OrgUnitID" or "OrgUnitID column" is required, but '
                  'not both.'))

        if (cleaned_data.get('period') and cleaned_data.get('period_column')):
            self.add_error(
                'period_column',
                _('Either "Period" or "Period column" is required, but not '
                  'both. Alternatively, leave both fields blank to use the '
                  "UCR's date filter."))

        if (cleaned_data.get('frequency') == SEND_FREQUENCY_WEEKLY
                and not _int_in_range(cleaned_data.get('day_to_send'), 1, 7)):
            self.add_error(
                'day_to_send',
                _('Enter a day of the week, where Monday is 1 and Sunday is 7.'
                  ))

        elif (cleaned_data.get('frequency') != SEND_FREQUENCY_WEEKLY
              and not _int_in_range(cleaned_data.get('day_to_send'), 1, 28)):
            self.add_error(
                'day_to_send',
                _('Enter a day of the month that occurs in every month (i.e. '
                  'from 1 to 28).'))

        if cleaned_data.get('period'):
            period_validators = {
                SEND_FREQUENCY_WEEKLY:
                RegexValidator(
                    r'^\d{4}W\d{1,2}$',
                    _('"Frequency" is set to "Weekly". Please enter a valid '
                      'week period in the format yyyyWn (e.g. "2004W10" for '
                      'week 10, 2004).')),
                SEND_FREQUENCY_MONTHLY:
                RegexValidator(
                    r'^\d{6}$',
                    _('"Frequency" is set to "Monthly". Please enter a valid '
                      'month period in the format yyyyMM (e.g. "200403" for '
                      'March 2004).')),
                SEND_FREQUENCY_QUARTERLY:
                RegexValidator(
                    r'^\d{4}Q\d$',
                    _('"Frequency" is set to "Quarterly". Please enter a valid '
                      'quarter period in the format yyyyQn (e.g. "2004Q1" for '
                      'January-March 2004).')),
            }
            validate_period = period_validators[cleaned_data.get('frequency')]
            try:
                validate_period(cleaned_data.get('period'))
            except ValidationError:
                self.add_error('period', validate_period.message)

        return self.cleaned_data
Esempio n. 25
0
class BaseUser(AbstractUser):
    """User model."""

    # We are inheriting AbstractUser and username is already defined there
    # We dont want to use username as we will be using email as login
    # inorder to not use username we say username = None
    username = None

    #we want to login via otp also without setting password. In that case we
    #want to create a random password
    #overrides password defined in AbstractBaseUser
    random_string = generateSecureRandomString()
    random_string_hassed = make_password(random_string)
    password = models.CharField(_('password'),
                                max_length=128,
                                default=random_string_hassed)

    # AbstractBaseUser has last_login. But here we are loging via 2 menthods so we need more variables
    recentdate_login_via_passwd = models.DateTimeField(
        _('last login via password'), blank=True, null=True)
    recentdate_login_via_otp = models.DateTimeField(_('last login via otp'),
                                                    blank=True,
                                                    null=True)
    recentdate_password_change = models.DateTimeField(
        _('last password change'), blank=True, null=True)

    # We are inheriting AbstractUser and first_name and last_name are already defined there
    # We want first_name and last name to be entered compulsory, But in the AbstactUser it
    # says blank=TRUE. So we have to rewrite it so redefine again without blank=True
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    # NULL allowed, but will never be set as NULL
    # The exception is CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string ('').
    last_name = models.CharField(_('last name'), max_length=150, blank=True)

    # We are inheriting AbstractUser and email is already defined there
    # its defined as blank=TRUE in the AbstractUser.
    # But we will be using it as the login field and also want to be unique
    email = models.EmailField(
        _('email address'),
        help_text="Please Enter valid Email Address",
        unique=True,
        error_messages={
            'unique': _("This email already exists."),
        },
    )

    # We are inheriting AbstractUser and is_active is already defined there
    # We dont want a user to be active unless his email is confirmed
    # we modify it with default=False
    is_active = models.BooleanField(
        _('active'),
        default=False,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'))

    # NULL allowed, but will never be set as NULL
    # The exception is CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string ('').
    recent_otp_used_for_pass_change = models.CharField(
        _('otp'),
        help_text="Please Enter valid OTP sent to your Email",
        max_length=6,
        validators=[
            RegexValidator(r'^\d{6}$',
                           message=_('OTP shoud be of 6 digits'),
                           code='invalid')
        ])

    date_of_recent_otp_used_for_pass_change = models.DateTimeField(null=True)

    # when we create a login and pass singup form, we try to verify the email then this is required
    otp_used_while_passlogin_create = models.CharField(
        _('otp'),
        help_text="Please Enter valid OTP sent to your Email",
        max_length=6,
        validators=[
            RegexValidator(r'^\d{6}$',
                           message=_('OTP shoud be of 6 digits'),
                           code='invalid')
        ])

    date_of_otp_used_while_passlogin_create = models.DateTimeField(null=True)

    first_otp_used_for_otplogin = models.CharField(
        _('otp'),
        help_text="Please Enter valid OTP sent to your Email",
        max_length=6,
        validators=[
            RegexValidator(r'^\d{6}$',
                           message=_('OTP shoud be of 6 digits'),
                           code='invalid')
        ])

    date_of_first_otp_used_for_otplogin = models.DateTimeField(null=True)

    # List of fields inhereted from AbstractUser
    # is_staff    #'Designates whether the user can log into this admin site.'
    # date_joined

    # List of fields inhereted from AbstractBaseUser
    # password
    # last_login
    # is_active

    # Optional fields to be filled by user for more information
    about = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

    modified_date = models.DateTimeField(_('modified date'), auto_now=True)

    creation_date = models.DateTimeField(_('creation date'), auto_now_add=True)

    # Because last_login is set by the signal in login() we dont want it and instead have our own
    last_login2 = models.DateTimeField(blank=True, null=True)

    # A string describing the name of the field on the user model that is
    # used as the unique identifier. This will usually be a username of
    # some kind, but it can also be an email address, or any other unique
    # identifier. The field must be unique (i.e., have unique=True set in its
    # definition), unless you use a custom authentication backend that can
    # support non-unique usernames.
    USERNAME_FIELD = 'email'

    # REQUIRED_FIELDS DEFINITION
    # A list of the field names that will be prompted for when creating a user
    # via the createsuperuser management command. The user will be prompted to
    # supply a value for each of these fields. It must include any field for which
    # blank is False or undefined and may include additional fields you want prompted
    # for when a user is created interactively. REQUIRED_FIELDS has no effect in other
    # parts of Django, like creating a user in the admin.

    # presently we dont want to be asked for anything while createsuperuser
    REQUIRED_FIELDS = []

    class Meta:
        """Define Meta class for BaseUser model."""
        # We want this class to be abstract so we define the below
        abstract = True
Esempio n. 26
0
class DataSetMapForm(forms.ModelForm):
    description = forms.CharField(label=_('Description'), )
    frequency = forms.ChoiceField(
        label=_('Frequency'),
        choices=SEND_FREQUENCY_CHOICES,
        initial=SEND_FREQUENCY_MONTHLY,
    )
    day_to_send = forms.CharField(
        label=_('Day to send data'),
        help_text=_('Day of the month if "Frequency" is monthly or quarterly. '
                    'Day of the week if "Frequency" is weekly, where Monday '
                    'is 1 and Sunday is 7.'),
    )
    data_set_id = forms.CharField(
        label=_('DataSetID'),
        help_text=_('Set DataSetID if this UCR adds values to an existing '
                    'DHIS2 DataSet'),
        validators=[RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)],
        required=False,
    )
    org_unit_id = forms.CharField(
        label=_('OrgUnitID¹'),
        validators=[RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)],
        required=False,
    )
    org_unit_column = forms.CharField(
        label=_('OrgUnitID column¹'),
        help_text=_('¹ Please set either a fixed value for "OrgUnitID", or '
                    'specify an "OrgUnitID column" where a DHIS2 Organisation '
                    'Unit ID will be found.'),
        required=False,
    )
    period = forms.CharField(
        label=_('Period²'),
        help_text=_('Week periods use the format yyyyWn (e.g. "2004W10" for '
                    'week 10, 2004). Month periods use the format yyyyMM '
                    '(e.g. "200403" for March 2004). Quarter periods use the '
                    'format yyyyQn (e.g. "2004Q1" for January-March 2004).'),
        required=False,
    )
    period_column = forms.CharField(
        label=_('Period column²'),
        help_text=_('² Please set a fixed value for "Period", or specify a '
                    '"Period column" where a period will be found, or if the '
                    'UCR has a date filter then leave both fields blank to '
                    'filter the UCR by the date range of the previous '
                    'period.'),
        required=False,
    )
    attribute_option_combo_id = forms.CharField(
        label=_('AttributeOptionComboID'),
        validators=[RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)],
        required=False,
    )
    complete_date = forms.DateField(
        label=_('CompleteDate'),
        required=False,
    )

    class Meta:
        model = SQLDataSetMap
        fields = [
            'description',
            'connection_settings',
            'ucr_id',
            'frequency',
            'day_to_send',
            'data_set_id',
            'org_unit_id',
            'org_unit_column',
            'period',
            'period_column',
            'attribute_option_combo_id',
            'complete_date',
        ]

    def __init__(self, domain, *args, **kwargs):
        from corehq.motech.dhis2.views import DataSetMapListView

        super().__init__(*args, **kwargs)
        self.domain = domain
        self.fields['connection_settings'] = get_connection_settings_field(
            domain)
        self.fields['ucr_id'] = get_ucr_field(domain)

        self.helper = hqcrispy.HQFormHelper()
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _('DataSet Details'),
                crispy.Field('description'),
                crispy.Field('connection_settings'),
                crispy.Field('ucr_id'),
                crispy.Field('frequency'),
                crispy.Field('day_to_send'),
                crispy.Field('data_set_id'),
                crispy.Field('org_unit_id'),
                crispy.Field('org_unit_column'),
                crispy.Field('period'),
                crispy.Field('period_column'),
                crispy.Field('attribute_option_combo_id'),
                crispy.Field('complete_date', css_class='date-picker'),
            ),
            hqcrispy.FormActions(
                twbscrispy.StrictButton(
                    _("Save"),
                    type="submit",
                    css_class="btn btn-primary",
                ),
                hqcrispy.LinkButton(
                    _("Cancel"),
                    reverse(
                        DataSetMapListView.urlname,
                        kwargs={'domain': self.domain},
                    ),
                    css_class="btn btn-default",
                ),
            ),
        )

    def save(self, commit=True):
        self.instance.domain = self.domain
        return super().save(commit)

    def clean(self):
        cleaned_data = super().clean()

        if not (cleaned_data.get('org_unit_id')
                or cleaned_data.get('org_unit_column')):
            self.add_error(
                'org_unit_column',
                _('Either "OrgUnitID" or "OrgUnitID column" is required.'))

        if (cleaned_data.get('org_unit_id')
                and cleaned_data.get('org_unit_column')):
            self.add_error(
                'org_unit_column',
                _('Either "OrgUnitID" or "OrgUnitID column" is required, but '
                  'not both.'))

        if (cleaned_data.get('period') and cleaned_data.get('period_column')):
            self.add_error(
                'period_column',
                _('Either "Period" or "Period column" is required, but not '
                  'both. Alternatively, leave both fields blank to use the '
                  "UCR's date filter."))

        if (cleaned_data.get('frequency') == SEND_FREQUENCY_WEEKLY
                and not _int_in_range(cleaned_data.get('day_to_send'), 1, 7)):
            self.add_error(
                'day_to_send',
                _('Enter a day of the week, where Monday is 1 and Sunday is 7.'
                  ))

        elif (cleaned_data.get('frequency') != SEND_FREQUENCY_WEEKLY
              and not _int_in_range(cleaned_data.get('day_to_send'), 1, 28)):
            self.add_error(
                'day_to_send',
                _('Enter a day of the month that occurs in every month (i.e. '
                  'from 1 to 28).'))

        if cleaned_data.get('period'):
            period_validators = {
                SEND_FREQUENCY_WEEKLY:
                RegexValidator(
                    r'^\d{4}W\d{1,2}$',
                    _('"Frequency" is set to "Weekly". Please enter a valid '
                      'week period in the format yyyyWn (e.g. "2004W10" for '
                      'week 10, 2004).')),
                SEND_FREQUENCY_MONTHLY:
                RegexValidator(
                    r'^\d{6}$',
                    _('"Frequency" is set to "Monthly". Please enter a valid '
                      'month period in the format yyyyMM (e.g. "200403" for '
                      'March 2004).')),
                SEND_FREQUENCY_QUARTERLY:
                RegexValidator(
                    r'^\d{4}Q\d$',
                    _('"Frequency" is set to "Quarterly". Please enter a valid '
                      'quarter period in the format yyyyQn (e.g. "2004Q1" for '
                      'January-March 2004).')),
            }
            validate_period = period_validators[cleaned_data.get('frequency')]
            try:
                validate_period(cleaned_data.get('period'))
            except ValidationError:
                self.add_error('period', validate_period.message)

        return self.cleaned_data
Esempio n. 27
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. 28
0
class Profile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    SEX_CHOICES = ((1, _('man')), (0, _('woman')), (None, _("don't show")))
    user = models.OneToOneField(User, related_name='profile')
    sex = models.IntegerField(choices=SEX_CHOICES,
                              blank=True,
                              null=True,
                              verbose_name=_('gender'))
    slug = models.SlugField(
        unique=True,
        max_length=100,
        help_text=_("automatically generated, don't change manually !"))
    address_line1 = models.CharField(verbose_name=_("address line1"),
                                     max_length=200,
                                     blank=True,
                                     null=True)
    address_line2 = models.CharField(verbose_name=_("address line2"),
                                     max_length=200,
                                     blank=True,
                                     null=True)
    city = models.CharField(_("city"), max_length=200, blank=True, null=True)
    state = CountryField(blank=True,
                         null=True,
                         blank_label=_('(select country)'))
    postal = models.CharField(_("postal"),
                              max_length=200,
                              blank=True,
                              null=True)
    dob = models.DateField(null=True, blank=True, verbose_name=_('birthday'))
    phone = models.CharField(
        max_length=50,
        verbose_name=_("phone"),
        blank=True,
        null=True,
    )
    cell = models.CharField(
        max_length=20,
        verbose_name=_("cell number"),
        blank=True,
        null=True,
        validators=[
            RegexValidator(
                regex=r'^\+?1?\d{9,15}$',
                message=
                _("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
                  ))
        ])
    profile_image = ProcessedImageField(
        upload_to=UploadToPathAndRename('profile_images'),
        processors=[
            ResizeToFill(400, 400),
            Adjust(sharpness=1.1, contrast=1.1)
        ],
        format='JPEG',
        options={'quality': 90},
        null=True,
        blank=True)

    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-id', )

    def __str__(self):
        return self.user.username

    @property
    def user_container(self):
        # be carefull this data is exposed to frontend to user :)
        context = {
            "first_name": self.user.first_name,
            "last_name": self.user.last_name,
            "email": self.user.email
        }
        return json.dumps(context)

    # thumbnail for admin interface
    def admin_image_thumb(self):
        if self.profile_image:
            return '<img src="{0}{1}" width="100" height="100" />'.format(
                settings.MEDIA_URL, self.profile_image)
        else:
            return '<img src="{0}accounts/default-avatar.jpg" width="100" height="100" />'.format(
                settings.STATIC_URL)

    admin_image_thumb.allow_tags = True

    # small thumbnail and method for it
    profile_image_thumbnail_sm = ImageSpecField(
        source='profile_image',
        processors=[ResizeToFill(155, 155)],
        format='JPEG',
        options={'quality': 80})

    def get_avatar_sm(self):
        if self.profile_image:
            return self.profile_image_thumbnail_sm.url
        else:
            return '{}accounts/default-avatar_sm.jpg'.format(
                settings.STATIC_URL)

    # extra small thumbnail and method for it
    profile_image_thumbnail_xs = ImageSpecField(
        source='profile_image',
        processors=[ResizeToFill(48, 48)],
        format='JPEG',
        options={'quality': 80})

    def get_avatar_xs(self):
        if self.profile_image:
            return self.profile_image_thumbnail_xs.url
        else:
            return '{}accounts/default-avatar_xs.jpg'.format(
                settings.STATIC_URL)
Esempio n. 29
0
class RegisterForm(forms.Form):
    username = forms.CharField(
        label='用户名',
        min_length=3,
        max_length=10,
        widget=forms.TextInput(
            attrs={
                'class':'form-control',
                'placeholder':'3-10位字母开头的字母数字组合', }),
        error_messages={
            'required':'用户名不能为空',
            'max_length':'不能超过10位',
            'min_length':'不能少于3位', },
        validators=[RegexValidator('^[a-zA-Z][a-zA-Z0-9_]{2,9}$', '必须是字母开头的字母数字组合')])

    password = forms.CharField(
        label='密码',
        min_length=8,
        max_length=23,
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '8-23位字母开头的大小写字母和数字组合', }),
        error_messages={
            'required': '密码不能为空',
            'max_length': '不能超过23位',
            'min_length': '不能少于8位',},
        validators=[RegexValidator('^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,18}$', '必须是字母开头的大小写字母和数字组合')])
    password_again = forms.CharField(
        label='再输一遍密码',
        min_length=8,
        max_length=23,
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '请再输一遍密码', }),
        error_messages={
            'required': '密码不能为空',
            'max_length': '不能超过23位',
            'min_length': '不能少于8位', })
    email = forms.EmailField(
        label='邮箱',
        widget=forms.EmailInput(
            attrs={
                'class': 'form-control',
                'placeholder': '请输入可用的邮箱地址', }),
        error_messages={
            'required': '邮箱不能为空', })
    verification_code = forms.CharField(
        label='验证码',
        required=False,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': '点击“发送验证码”,输入您邮箱收到的四位验证码'}),)

    def __init__(self, *args, **kwargs):
        if 'request' in kwargs:
            self.request = kwargs.pop('request')
        super(RegisterForm, self).__init__(*args, **kwargs)

    def clean_username(self):
        username = self.cleaned_data.get('username', '')
        if username == '':
            raise forms.ValidationError('用户名不能为空')
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('该用户名已存在')
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email', '')
        if email == '':
            raise forms.ValidationError('邮箱不能为空')
        if User.objects.filter(email=email).exists():
            raise forms.Validationerror('该邮箱已被使用')
        return email

    def clean_password_again(self):
        password = self.cleaned_data.get('password', '')
        password_again = self.cleaned_data.get('password_again', '')
        if password == '':
            raise forms.ValidationError('密码不能为空')
        if password != password_again:
            raise forms.ValidationError('两次输入的密码不一致')
        return password_again

    def clean_verification_code(self):
        # 判断验证码
        email = self.cleaned_data.get('email', '')
        print(email, '++++++++++++++++++++email')
        code = self.request.session.get(email, '')
        print(code, '++++++++++++++++++code')
        verification_code = self.cleaned_data.get('verification_code').strip()
        print(verification_code,'++++++++++++++++++++++ver')
        if verification_code == '':
            raise forms.ValidationError('验证码不能为空')
        if code != verification_code:
            raise forms.ValidationError('验证码不正确')

        # 验证码时效验证
        now = int(time.time())
        send_code_time = self.request.session.get('send_code_time', 0)
        if now - send_code_time > 120:
            raise forms.ValidationError('填写验证码超时,请重新获取验证码')
        return verification_code
Esempio n. 30
0
class NUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField('username',
                                max_length=30,
                                unique=True,
                                validators=[
                                    validators.RegexValidator(
                                        r'^[\w.@+-]+$',
                                        'Enter a valid username.', 'invalid')
                                ])

    email = models.EmailField('email', unique=True)
    is_staff = models.BooleanField('is_staff', default=False)
    is_active = models.BooleanField('is_active', default=False)
    date_joined = models.DateTimeField('date_joined', default=timezone.now)
    date_login = models.DateTimeField('date_login', null=True, blank=True)
    color = models.CharField(max_length=6,
                             default=get_random_color,
                             validators=[
                                 RegexValidator(regex='^[A-F0-9]{6}$',
                                                message='No color',
                                                code='nocolor'),
                                 validate_user_color
                             ])

    migrated = models.BooleanField(default=True)
    old_password = models.CharField(max_length=500,
                                    null=True,
                                    blank=True,
                                    default=None)
    bio = models.CharField(max_length=400, default='', blank=True)
    pw_reset_token = models.CharField(max_length=30, null=True, blank=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

    def save(self, *args, **kwargs):
        if not self.pw_reset_token:
            self.pw_reset_token = None
        if not self.old_password:
            self.old_password = None
        super(NUser, self).save(*args, **kwargs)

    def is_authenticated_raw(self):
        return super(NUser, self).is_authenticated()

    def is_authenticated(self):
        return self.is_authenticated_raw() and self.migrated

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def migrate(self, password, request=None):
        with transaction.atomic():
            self.migrated = True
            self.old_password = None
            self.save()

            if request is None:
                self.set_password(password)
            else:
                self.set_password_keep_session(request, password)

    def set_password_keep_session(self, request, raw_password):
        self.set_password(raw_password)
        self.save()

        auth_user = authenticate(username=self.username, password=raw_password)
        login(request, auth_user)

    def email_user(self,
                   subject,
                   message,
                   from_email=None,
                   recipient=None,
                   **kwargs):
        if recipient is None:
            recipient = self.email
        send_mail(subject, message, from_email, [recipient], **kwargs)

    def _email_user_template(self, tpl, context, lang, recipient=None):
        options = settings.EMAILS[tpl]
        siteurl = settings.SITEURL

        context['username'] = self.username
        context['siteurl'] = siteurl

        c = Context(context)

        text_content = render_to_string(tpl + '_' + lang + '.txt', c)
        self.email_user(options['subject'][lang],
                        text_content,
                        recipient=recipient)

    def add_email_token(self, email):
        token = '%030x' % random.randrange(16**30)
        email_token = NUserEmailToken(user=self, email=email, token=token)
        email_token.save()
        return email_token

    def check_email_token(self, token):
        return self.email_tokens.get(token=token)

    def apply_email_token(self, token_obj):
        self.email = token_obj.email
        self.is_active = True
        token_obj.delete()
        self.save()

    def email_user_activation(self, lang, token):
        ctx = {'token': token}
        self._email_user_template('activation', ctx, lang)

    def email_new_mail_confirmation(self, lang, token, email):
        ctx = {'token': token}
        self._email_user_template('newmail_confirmation',
                                  ctx,
                                  lang,
                                  recipient=email)

    def set_pw_reset_token(self):
        token = '%030x' % random.randrange(16**30)
        self.pw_reset_token = token
        self.save()

    def check_pw_reset_token(self, token):
        return self.pw_reset_token is not None and\
               token is not None and\
               self.pw_reset_token == token

    def apply_pw_reset_token(self, password):
        print(password)
        self.pw_reset_token = None
        self.set_password(password)
        self.migrated = True
        self.save()

    def email_pw_reset(self, lang):
        ctx = {'token': self.pw_reset_token}
        self._email_user_template('pwreset', ctx, lang)