Esempio n. 1
0
class FormJuego(forms.Form):

    enlace = forms.CharField(
        label="Enlace Zmart",
        min_length=52,
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'Ingresa link de Zmart'}),
        validators=[
            validators.MinLengthValidator(
                limit_value=52,
                message="En link de Zmart debe tener minimo 52 caracteres"),
        ])

    enlace2 = forms.CharField(
        label="Enlace Microplay",
        min_length=33,
        widget=forms.TextInput(
            attrs={'placeholder': 'Ingresa link de Microplay'}))

    enlace3 = forms.CharField(
        label="Enlace Weplay",
        min_length=22,
        widget=forms.TextInput(
            attrs={'placeholder': 'Ingresa link de Weplay'}))
Esempio n. 2
0
class Article(models.Model):
    """An article for our simple blog."""

    title = models.CharField(
        max_length=128,
        validators=[
            validators.MinLengthValidator(1, message="titles cannot be empty!")
        ],
    )
    pub_date = models.DateTimeField(auto_now_add=True)
    body = models.TextField(help_text="The main body for this blog post.")
    tags = models.ManyToManyField(
        Tag,
        related_name="articles",
        blank=True,
    )

    def __str__(self) -> str:
        """Return a string representation of this article."""
        return str(self.title)

    def get_absolute_url(self) -> str:
        """Get the absolute URL for this article."""
        return reverse("blog:article-detail", kwargs={"pk": self.pk})
Esempio n. 3
0
class ProfileView(forms.ModelForm):
    user_name = forms.CharField(validators=[validators.MinLengthValidator(3)])
    first_name = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={"placeholder": "optional"}))

    last_name = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={"placeholder": "optional"}))

    YEARS = [x for x in range(1940, 2003)]
    birthdate = forms.DateField(initial="1994-06-21",
                                widget=forms.SelectDateWidget(years=YEARS))

    class Meta:
        model = Profile
        fields = [
            "user_name", "first_name", "last_name", "gender", "birthdate"
        ]

    def clean(self):
        user_name = self.cleaned_data["user_name"]
        if Profile.objects.filter(user_name=user_name).exists():
            raise forms.ValidationError("This username is already taken")
Esempio n. 4
0
class SampleForm(forms.Form):
    name = forms.CharField(max_length=200,
                           required=True,
                           label="Name :",
                           validators=[validate_name])

    email = forms.EmailField(max_length=100,
                             required=True,
                             label="Email :",
                             validators=[validators.MinLengthValidator(10)])

    confirm_email = forms.EmailField(max_length=100,
                                     required=True,
                                     label="Confirm Email :")
    ip_address = forms.CharField(max_length=100,
                                 required=True,
                                 validators=[validators.validate_ipv4_address])
    pwd = forms.CharField(
        max_length=200,
        required=True,
        label="Password :"******"Password"}))
    profile_pic = forms.ImageField(max_length=200,
                                   required=True,
                                   label="Profile Pic :")

    def clean(self, *args, **kwargs):
        cleaned_data = super().clean(
        )  #getting all the data that is filled in the form
        email = cleaned_data.get("email")
        cemail = cleaned_data.get("confirm_email")
        if email == cemail:
            return cleaned_data
        self.add_error(
            'confirm_email', "Both the emails are not same"
        )  #this method will decide to which field we need to show the error
Esempio n. 5
0
class FormularioArticulo(forms.Form):
    title = forms.CharField(
        label="Titulo",
        max_length=20,
        required=True,
        widget=forms.TextInput(attrs={
            'placeholder': 'Mete el titulo',
            'class': 'titulo_form_article'
        }),
        validators=[
            validators.MinLengthValidator(4, 'EL titulo es muy corto'),
            validators.RegexValidator('^[A-Za-z0-9Ññ]*$',
                                      'El titulo esta mal formado',
                                      'invalid_title')
        ])
    content = forms.CharField(label="Contenido",
                              widget=forms.Textarea,
                              validators=[
                                  validators.MaxLengthValidator(
                                      200,
                                      'Te has pasado, has puesto mucho texto')
                              ])
    public = forms.TypedChoiceField(label="Publicado?",
                                    choices=[(1, 'Si'), (0, 'No')])
Esempio n. 6
0
class FeedbackForm(forms.Form):
    subject = forms.CharField(
        label='主题',
        max_length=20,
        validators=[validators.MinLengthValidator(2, message='主题不得少于2个字符')],
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    category = forms.ChoiceField(
        label='分类',
        choices=Feedback.CATEGORIES,
        widget=forms.Select(attrs={'class': 'form-control'}))
    username = forms.CharField(
        label='姓名', widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(
        label='邮箱', widget=forms.TextInput(attrs={'class': 'form-control'}))
    screenshot = forms.FileField(label='问题截图', required=False)
    description = forms.CharField(
        label='问题描述', widget=forms.Textarea(attrs={'class': 'form-control'}))
    subscription = forms.BooleanField(label='订阅资讯', required=False)
    status = forms.ChoiceField(
        label='处理状态',
        choices=Feedback.STATUS,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}))
    posted_time = forms.DateTimeField(label='发布 时间', required=False)
Esempio n. 7
0
class Event(models.Model):
    """
    Base class for Event-objects.
    """

    IMAGE_FOLDER = "images/events"
    IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".gif", ".png", ".tif", ".tiff"]

    # Managers
    objects = models.Manager()
    by_registration = EventOrderedByRegistration()

    author = models.ForeignKey(
        User, related_name="oppretter", null=True, blank=True, on_delete=models.CASCADE
    )
    title = models.CharField(_("tittel"), max_length=60)
    """Event title"""
    event_start = models.DateTimeField(_("start-dato"))
    """Datetime for event start"""
    event_end = models.DateTimeField(_("slutt-dato"))
    """Datetime for event end"""
    location = models.CharField(_("lokasjon"), max_length=100)
    """Event location"""
    ingress_short = models.CharField(
        _("kort ingress"),
        max_length=150,
        validators=[validators.MinLengthValidator(25)],
        help_text="En kort ingress som blir vist på forsiden",
    )
    """Short ingress used on the frontpage"""
    ingress = models.TextField(
        _("ingress"),
        validators=[validators.MinLengthValidator(25)],
        help_text="En ingress som blir vist før beskrivelsen.",
    )
    """Ingress used in archive and details page"""
    description = models.TextField(
        _("beskrivelse"), validators=[validators.MinLengthValidator(45)]
    )
    """Event description shown on details page"""
    image = models.ForeignKey(
        ResponsiveImage,
        related_name="events",
        blank=True,
        null=True,
        on_delete=SET_NULL,
    )
    """Event image"""
    event_type = models.SmallIntegerField(
        _("type"), choices=EventType.ALL_CHOICES, null=False
    )
    """Event type. Used mainly for filtering"""
    organizer = models.ForeignKey(
        Group, verbose_name=_("arrangør"), blank=True, null=True, on_delete=SET_NULL
    )
    """Committee responsible for organizing the event"""
    visible = models.BooleanField(
        _("Vis arrangementet utenfor Dashboard og Adminpanelet"),
        default=True,
        help_text=_("Denne brukes for å skjule eksisterende arrangementer."),
    )

    feedback = GenericRelation(FeedbackRelation)

    def is_attendance_event(self):
        """ Returns true if the event is an attendance event """
        return hasattr(self, "attendance_event")

    # TODO move payment and feedback stuff to attendance event when dasboard is done

    def feedback_users(self):
        if self.is_attendance_event():
            return [
                a.user for a in self.attendance_event.attendees.filter(attended=True)
            ]
        return []

    def feedback_date(self):
        return self.event_end

    def feedback_title(self):
        return self.title

    def feedback_info(self):
        info = OrderedDict()
        if self.is_attendance_event():
            info[_("Påmeldte")] = self.attendance_event.number_of_attendees
            info[_("Oppmøtte")] = self.attendance_event.number_of_attendees - len(
                self.attendance_event.not_attended()
            )
            info[_("Venteliste")] = self.attendance_event.number_on_waitlist

        return info

    @property
    def company_event(self):
        return CompanyEvent.objects.filter(event=self)

    @property
    def organizer_name(self):
        return self.organizer.name

    def feedback_mail(self):
        """
        Get feedback mail from organizer Online group.
        Use default from email if the organizer group does not have configured an email.
        """
        if self.organizer:
            organizer_group = OnlineGroup.objects.filter(pk=self.organizer.id).first()
            if organizer_group and organizer_group.email:
                return organizer_group.email

        return settings.DEFAULT_FROM_EMAIL

    def can_display(self, user):
        restriction = GroupRestriction.objects.filter(event=self).first()
        if (
            not user.is_anonymous
            and self.is_attendance_event()
            and self.attendance_event.is_attendee(user)
        ):
            return True
        if not self.visible:
            return False
        if not restriction:
            return True
        if not user:
            return False
        return restriction.has_access(user)

    @property
    def slug(self):
        return slugify(unidecode(self.title))

    def get_absolute_url(self):
        return reverse(
            "events_details", kwargs={"event_id": self.id, "event_slug": self.slug}
        )

    def clean(self):
        if not self.organizer:
            raise ValidationError({"organizer": ["Arrangementet krever en arrangør."]})

    def save(
        self, force_insert=False, force_update=False, using=None, update_fields=None
    ):
        super().save(
            force_insert=force_insert,
            force_update=force_update,
            using=using,
            update_fields=update_fields,
        )

        if self.organizer:
            assign_perm("events.change_event", self.organizer, obj=self)
            assign_perm("events.delete_event", self.organizer, obj=self)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = _("arrangement")
        verbose_name_plural = _("arrangementer")
        permissions = (("view_event", "View Event"),)
        default_permissions = ("add", "change", "delete")
Esempio n. 8
0
class SSUser(models.Model):
    @classmethod
    def userTodyChecked(cls):
        '''返回今日签到人数'''
        return len([o for o in cls.objects.all() if o.get_check_in()])

    @classmethod
    def userNeverChecked(cls):
        '''返回从未签到过人数'''
        return len([
            o for o in cls.objects.all() if o.last_check_in_time.year == 1970
        ])

    @classmethod
    def userNeverUsed(cls):
        '''返回从未使用过的人数'''
        return len([o for o in cls.objects.all() if o.last_use_time == 0])

    @classmethod
    def coreUser(cls):
        '''返回流量用的最多的前十名用户'''
        rec = {}
        for u in cls.objects.filter(download_traffic__gt=0):
            rec[u] = u.upload_traffic + u.download_traffic
        # 按照流量倒序排序,切片取出前十名
        rec = sorted(rec.items(), key=lambda rec: rec[1], reverse=True)[:10]
        return [(r[0], r[0].get_traffic()) for r in rec]

    @classmethod
    def randomPord(cls):
        '''从其实端口~最大端口随机找出一个没有用过的端口'''
        users = cls.objects.all()
        port_list = []
        for user in users:
            '''将所有端口都加入列表'''
            port_list.append(int(user.port))
        # 生成从最小到最大的断口池
        all_ports = [i for i in range(10000, max(port_list) + 1)]
        try:
            # 随机返回一个没有没占用的端口(取差集)
            return choice(list(set(all_ports).difference(set(port_list))))
        except:
            return max(port_list) + 1

    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                related_name='ss_user')

    last_check_in_time = models.DateTimeField(
        '最后签到时间',
        null=True,
        # 默认设置为时间戳开始的那天
        default=datetime.datetime.fromtimestamp(0),
        editable=False,
    )

    # shadowsocks 数据库表字段
    password = models.CharField(
        'Shadowsocks密码',
        max_length=32,
        # 当密码少于8位时报错
        validators=[
            validators.MinLengthValidator(8),
        ],
        default=get_short_random_string,
        db_column='passwd',
    )
    port = models.IntegerField(
        '端口',
        db_column='port',
        unique=True,
    )
    last_use_time = models.IntegerField('最后使用时间',
                                        default=0,
                                        editable=False,
                                        help_text='时间戳',
                                        db_column='t')
    upload_traffic = models.BigIntegerField('上传流量', default=0, db_column='u')
    download_traffic = models.BigIntegerField('下载流量', default=0, db_column='d')
    transfer_enable = models.BigIntegerField('总流量',
                                             default=settings.DEFAULT_TRAFFIC,
                                             db_column='transfer_enable')
    switch = models.BooleanField(
        '保留字段switch',
        default=True,
        db_column='switch',
    )
    enable = models.BooleanField(
        '开启与否',
        default=True,
        db_column='enable',
    )

    method = models.CharField(
        '加密类型',
        default=settings.DEFAULT_METHOD,
        max_length=32,
        choices=METHOD_CHOICES,
    )

    protocol = models.CharField(
        '协议',
        default=settings.DEFAULT_PROTOCOL,
        max_length=32,
        choices=PROTOCOL_CHOICES,
    )

    obfs = models.CharField(
        '混淆',
        default=settings.DEFAULT_OBFS,
        max_length=32,
        choices=OBFS_CHOICES,
    )

    # 等级字段 和 shadowsocks.user 的level 同步
    level = models.PositiveIntegerField(
        '用户等级',
        default=0,
    )

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

    def get_last_use_time(self):
        '''返回上一次的使用到时间'''
        return timezone.datetime.fromtimestamp(self.last_use_time)

    def get_traffic(self):
        '''返回用户使用的总流量GB '''
        return '{:.2f}'.format(
            (self.download_traffic + self.upload_traffic) / settings.GB)

    def get_transfer(self):
        '''返回用户的总流量 GB'''
        return '{:.2f}'.format(self.transfer_enable / settings.GB)

    def get_unused_traffic(self):
        '''返回用户的剩余流量'''
        return '{:.2f}'.format((self.transfer_enable - self.upload_traffic -
                                self.download_traffic) / settings.GB)

    def get_used_percentage(self):
        '''返回用户的为使用流量百分比'''
        try:
            return '{:.2f}'.format(
                (self.download_traffic + self.upload_traffic) /
                self.transfer_enable * 100)
        except ZeroDivisionError:
            return '100'

    def get_check_in(self):
        '''返回当天是否签到'''
        # 获取当天日期
        check_day = self.last_check_in_time.day
        now_day = datetime.datetime.now().day
        return check_day == now_day

    def clean(self):
        '''保证端口在1024<50000之间'''
        if self.port:
            if not 9999 < self.port < 50001:
                raise ValidationError('端口必须在10000和50000之间')
        else:
            max_port_user = SSUser.objects.order_by('-port').first()
            if max_port_user:
                self.port = max_port_user.port + choice([2, 3])
            else:
                self.port = settings.START_PORT

    class Meta:
        verbose_name_plural = 'SS账户'
        ordering = ('-last_check_in_time', )
        db_table = 'user'
Esempio n. 9
0
class UserProfile(OnChangeMixin, ModelBase, AbstractBaseUser):
    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']
    username = models.CharField(max_length=255, default='', unique=True)
    display_name = models.CharField(max_length=50,
                                    default='',
                                    null=True,
                                    blank=True,
                                    validators=[
                                        validators.MinLengthValidator(2),
                                        OneOrMorePrintableCharacterValidator()
                                    ])

    email = models.EmailField(unique=True, null=True, max_length=75)

    averagerating = models.FloatField(null=True)
    # biography can (and does) contain html and other unsanitized content.
    # It must be cleaned before display.
    biography = models.TextField(blank=True, null=True)
    deleted = models.BooleanField(default=False)
    display_collections = models.BooleanField(default=False)
    homepage = models.URLField(max_length=255, blank=True, default='')
    location = models.CharField(max_length=255, blank=True, default='')
    notes = models.TextField(blank=True, null=True)
    occupation = models.CharField(max_length=255, default='', blank=True)
    # This is essentially a "has_picture" flag right now
    picture_type = models.CharField(max_length=75,
                                    default=None,
                                    null=True,
                                    blank=True)
    read_dev_agreement = models.DateTimeField(null=True, blank=True)

    last_login_ip = models.CharField(default='', max_length=45, editable=False)
    email_changed = models.DateTimeField(null=True, editable=False)
    banned = models.DateTimeField(null=True, editable=False)

    # Is the profile page for this account publicly viewable?
    # Note: this is only used for API responses (thus addons-frontend) - all
    # users's profile pages are publicly viewable on legacy frontend.
    # TODO: Remove this note once legacy profile pages are removed.
    is_public = models.BooleanField(default=False, db_column='public')

    fxa_id = models.CharField(blank=True, null=True, max_length=128)

    # Identifier that is used to invalidate internal API tokens (i.e. those
    # that we generate for addons-frontend, NOT the API keys external clients
    # use) and django sessions. Should be changed if a user is known to have
    # been compromised.
    auth_id = models.PositiveIntegerField(null=True, default=generate_auth_id)

    # Token used to manage the users subscriptions in basket. Basket
    # is proxying directly to Salesforce, e.g for the about-addons
    # newsletter
    basket_token = models.CharField(blank=True, default='', max_length=128)

    bypass_upload_restrictions = models.BooleanField(default=False)

    reviewer_name = models.CharField(
        max_length=50,
        default='',
        null=True,
        blank=True,
        validators=[validators.MinLengthValidator(2)])

    class Meta:
        db_table = 'users'

    def __init__(self, *args, **kw):
        super(UserProfile, self).__init__(*args, **kw)
        if self.username:
            self.username = force_text(self.username)

    def __str__(self):
        return u'%s: %s' % (self.id, self.display_name or self.username)

    @property
    def is_superuser(self):
        return any(group.rules == '*:*' for group in self.groups_list)

    @property
    def is_staff(self):
        """Property indicating whether the user should be able to log in to
        the django admin tools. Does not guarantee that the user will then
        be able to do anything, as each module can have its own permission
        checks. (see has_module_perms() and has_perm())"""
        from olympia.access import acl
        return acl.action_allowed_user(self, amo.permissions.ANY_ADMIN)

    def has_perm(self, perm, obj=None):
        """Determine what the user can do in the django admin tools.

        perm is in the form "<app>.<action>_<model>".
        """
        from olympia.access import acl
        return acl.action_allowed_user(
            self, amo.permissions.DJANGO_PERMISSIONS_MAPPING[perm])

    def has_module_perms(self, app_label):
        """Determine whether the user can see a particular app in the django
        admin tools. """
        # If the user is a superuser or has permission for any action available
        # for any of the models of the app, they can see the app in the django
        # admin. The is_superuser check is needed to allow superuser to access
        # modules that are not in the mapping at all (i.e. things only they
        # can access).
        return (self.is_superuser or any(
            self.has_perm(key)
            for key in amo.permissions.DJANGO_PERMISSIONS_MAPPING
            if key.startswith('%s.' % app_label)))

    def has_read_developer_agreement(self):
        from olympia.zadmin.models import get_config

        # Fallback date in case the config date value is invalid or set to the
        # future. The current fallback date is the last update on June 10, 2019
        dev_agreement_change_fallback = datetime(2019, 6, 10, 12, 00)

        if self.read_dev_agreement is None:
            return False
        try:
            last_agreement_change_config = get_config(
                'last_dev_agreement_change_date')
            change_config_date = datetime.strptime(
                last_agreement_change_config, '%Y-%m-%d %H:%M')

            # If the config date is in the future, instead check against the
            # fallback date
            if change_config_date > datetime.now():
                return self.read_dev_agreement > dev_agreement_change_fallback

            return self.read_dev_agreement > change_config_date
        except (ValueError, TypeError):
            log.exception('last_developer_agreement_change misconfigured, '
                          '"%s" is not a '
                          'datetime' % last_agreement_change_config)
            return self.read_dev_agreement > dev_agreement_change_fallback

    backend = 'django.contrib.auth.backends.ModelBackend'

    def get_session_auth_hash(self):
        """Return a hash used to invalidate sessions of users when necessary.

        Can return None if auth_id is not set on this user."""
        if self.auth_id is None:
            # Old user that has not re-logged since we introduced that field,
            # return None, it won't be used by django session invalidation
            # mechanism.
            return None
        # Mimic what the AbstractBaseUser implementation does, but with our
        # own custom field instead of password, which we don't have.
        key_salt = 'olympia.models.users.UserProfile.get_session_auth_hash'
        return salted_hmac(key_salt, str(self.auth_id)).hexdigest()

    @staticmethod
    def create_user_url(id_, src=None):
        from olympia.amo.utils import urlparams
        url = reverse('users.profile', args=[id_])
        return urlparams(url, src=src)

    def get_themes_url_path(self, src=None, args=None):
        from olympia.amo.utils import urlparams
        url = reverse('users.themes', args=[self.id] + (args or []))
        return urlparams(url, src=src)

    def get_url_path(self, src=None):
        return self.create_user_url(self.id, src=src)

    @cached_property
    def groups_list(self):
        """List of all groups the user is a member of, as a cached property."""
        return list(self.groups.all())

    def get_addons_listed(self):
        """Return queryset of public add-ons thi user is listed as author of.
        """
        return self.addons.public().filter(addonuser__user=self,
                                           addonuser__listed=True)

    @property
    def num_addons_listed(self):
        """Number of public add-ons this user is listed as author of."""
        return self.get_addons_listed().count()

    def my_addons(self, n=8):
        """Returns n addons"""
        qs = order_by_translation(self.addons, 'name')
        return qs[:n]

    @property
    def picture_dir(self):
        from olympia.amo.templatetags.jinja_helpers import user_media_path
        split_id = re.match(r'((\d*?)(\d{0,3}?))\d{1,3}$', str(self.id))
        return os.path.join(user_media_path('userpics'),
                            split_id.group(2) or '0',
                            split_id.group(1) or '0')

    @property
    def picture_path(self):
        return os.path.join(self.picture_dir, str(self.id) + '.png')

    @property
    def picture_path_original(self):
        return os.path.join(self.picture_dir, str(self.id) + '_original.png')

    @property
    def picture_url(self):
        from olympia.amo.templatetags.jinja_helpers import user_media_url
        if not self.picture_type:
            return settings.STATIC_URL + '/img/zamboni/anon_user.png'
        else:
            split_id = re.match(r'((\d*?)(\d{0,3}?))\d{1,3}$', str(self.id))
            modified = int(time.mktime(self.modified.timetuple()))
            path = "/".join([
                split_id.group(2) or '0',
                split_id.group(1) or '0',
                "%s.png?modified=%s" % (self.id, modified)
            ])
            return user_media_url('userpics') + path

    @cached_property
    def cached_developer_status(self):
        addon_types = list(
            self.addonuser_set.exclude(
                addon__status=amo.STATUS_DELETED).values_list('addon__type',
                                                              flat=True))

        all_themes = [t for t in addon_types if t in amo.GROUP_TYPE_THEME]
        return {
            'is_developer': bool(addon_types),
            'is_extension_developer': len(all_themes) != len(addon_types),
            'is_theme_developer': bool(all_themes)
        }

    @property
    def is_developer(self):
        return self.cached_developer_status['is_developer']

    @property
    def is_addon_developer(self):
        return self.cached_developer_status['is_extension_developer']

    @property
    def is_artist(self):
        """Is this user a theme artist?"""
        return self.cached_developer_status['is_theme_developer']

    @use_primary_db
    def update_is_public(self):
        pre = self.is_public
        is_public = (self.addonuser_set.filter(
            role__in=[amo.AUTHOR_ROLE_OWNER, amo.AUTHOR_ROLE_DEV],
            listed=True,
            addon__status=amo.STATUS_APPROVED).exists())
        if is_public != pre:
            log.info('Updating %s.is_public from %s to %s' %
                     (self.pk, pre, is_public))
            self.update(is_public=is_public)
        else:
            log.info('Not changing %s.is_public from %s' % (self.pk, pre))

    @property
    def name(self):
        if self.display_name:
            return force_text(self.display_name)
        else:
            return ugettext('Firefox user {id}').format(id=self.id)

    welcome_name = name

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def anonymize_username(self):
        """Set an anonymous username."""
        if self.pk:
            log.info('Anonymizing username for {}'.format(self.pk))
        else:
            log.info('Generating username for {}'.format(self.email))
        self.username = '******'.format(
            force_text(binascii.b2a_hex(os.urandom(16))))
        return self.username

    @property
    def has_anonymous_username(self):
        return re.match('^anonymous-[0-9a-f]{32}$', self.username) is not None

    @property
    def has_anonymous_display_name(self):
        return not self.display_name

    @cached_property
    def ratings(self):
        """All ratings that are not dev replies."""
        return self._ratings_all.filter(reply_to=None)

    def delete_or_disable_related_content(self, delete=False):
        """Delete or disable content produced by this user if they are the only
        author."""
        self.collections.all().delete()
        for addon in self.addons.all().iterator():
            if not addon.authors.exclude(pk=self.pk).exists():
                if delete:
                    addon.delete()
                else:
                    addon.force_disable()
            else:
                addon.addonuser_set.filter(user=self).delete()
        user_responsible = core.get_user()
        self._ratings_all.all().delete(user_responsible=user_responsible)
        self.delete_picture()

    def delete_picture(self, picture_path=None, original_picture_path=None):
        """Delete picture of this user."""
        # Recursive import
        from olympia.users.tasks import delete_photo

        if picture_path is None:
            picture_path = self.picture_path
        if original_picture_path is None:
            original_picture_path = self.picture_path_original

        if storage.exists(picture_path):
            delete_photo.delay(picture_path)

        if storage.exists(original_picture_path):
            delete_photo.delay(original_picture_path)

        if self.picture_type:
            self.update(picture_type=None)

    def ban_and_disable_related_content(self):
        """Admin method to ban the user and disable the content they produced.

        Similar to deletion, except that the content produced by the user is
        forcibly disabled instead of being deleted where possible, and the user
        is not fully anonymized: we keep their fxa_id and email so that they
        are never able to log back in.
        """
        self.delete_or_disable_related_content(delete=False)
        return self.delete(ban_user=True)

    @classmethod
    def ban_and_disable_related_content_bulk(cls, users, move_files=False):
        """Like ban_and_disable_related_content, but in bulk. """
        from olympia.addons.models import Addon, AddonUser
        from olympia.addons.tasks import index_addons
        from olympia.bandwagon.models import Collection
        from olympia.files.models import File
        from olympia.ratings.models import Rating

        # collect affected addons
        addon_ids = set(
            Addon.unfiltered.exclude(status=amo.STATUS_DELETED).filter(
                addonuser__user__in=users).values_list('id', flat=True))

        # First addons who have other authors we aren't banning
        addon_joint_ids = set(
            AddonUser.objects.filter(addon_id__in=addon_ids).exclude(
                user__in=users).values_list('addon_id', flat=True))
        AddonUser.objects.filter(user__in=users,
                                 addon_id__in=addon_joint_ids).delete()

        # Then deal with users who are the sole author
        addons_sole = Addon.unfiltered.filter(id__in=addon_ids -
                                              addon_joint_ids)
        # set the status to disabled - using the manager update() method
        addons_sole.update(status=amo.STATUS_DISABLED)
        # collect Files that need to be disabled now the addons are disabled
        files_to_disable = File.objects.filter(version__addon__in=addons_sole)
        files_to_disable.update(status=amo.STATUS_DISABLED)
        if move_files:
            # if necessary move the files out of the CDN (expensive operation)
            for file_ in files_to_disable:
                file_.hide_disabled_file()

        # Finally run Addon.force_disable to add the logging; update versions
        # Status was already DISABLED so shouldn't fire watch_disabled again.
        for addon in addons_sole:
            addon.force_disable()
        # Don't pass a set to a .delay - sets can't be serialized as JSON
        index_addons.delay(list(addon_ids - addon_joint_ids))

        # delete the other content associated with the user
        Collection.objects.filter(author__in=users).delete()
        Rating.objects.filter(user__in=users).delete(
            user_responsible=core.get_user())
        # And then delete the users.
        for user in users:
            user.delete(ban_user=True)

    def delete(self, hard=False, ban_user=False):
        # Cache the values in case we do a hard delete and loose
        # reference to the user-id.
        picture_path = self.picture_path
        original_picture_path = self.picture_path_original

        if hard:
            super(UserProfile, self).delete()
        else:
            if ban_user:
                log.info(f'User ({self}: <{self.email}>) is being partially '
                         'anonymized and banned.')
                # We don't clear email or fxa_id when banning
                self.banned = datetime.now()
            else:
                log.info(u'User (%s: <%s>) is being anonymized.' %
                         (self, self.email))
                self.email = None
                self.fxa_id = None
                self.last_login_ip = ''
            self.biography = ''
            self.display_name = None
            self.homepage = ''
            self.location = ''
            self.deleted = True
            self.picture_type = None
            self.auth_id = generate_auth_id()
            self.anonymize_username()
            self.save()

        self.delete_picture(picture_path=picture_path,
                            original_picture_path=original_picture_path)

    def set_unusable_password(self):
        raise NotImplementedError('cannot set unusable password')

    def set_password(self, password):
        raise NotImplementedError('cannot set password')

    def check_password(self, password):
        raise NotImplementedError('cannot check password')

    @staticmethod
    def user_logged_in(sender, request, user, **kwargs):
        """Log when a user logs in and records its IP address."""
        log.debug(u'User (%s) logged in successfully' % user,
                  extra={'email': user.email})
        user.update(last_login_ip=core.get_remote_addr() or '')

    def mobile_collection(self):
        return self.special_collection(amo.COLLECTION_MOBILE,
                                       defaults={
                                           'slug': 'mobile',
                                           'listed': False,
                                           'name':
                                           ugettext('My Mobile Add-ons')
                                       })

    def favorites_collection(self):
        return self.special_collection(amo.COLLECTION_FAVORITES,
                                       defaults={
                                           'slug': 'favorites',
                                           'listed': False,
                                           'name':
                                           ugettext('My Favorite Add-ons')
                                       })

    def special_collection(self, type_, defaults):
        from olympia.bandwagon.models import Collection
        c, new = Collection.objects.get_or_create(author=self,
                                                  type=type_,
                                                  defaults=defaults)
        if new:
            # Do an extra query to make sure this gets transformed.
            c = Collection.objects.using('default').get(id=c.id)
        return c

    def addons_for_collection_type(self, type_):
        """Return the addons for the given special collection type."""
        from olympia.bandwagon.models import CollectionAddon
        qs = CollectionAddon.objects.filter(collection__author=self,
                                            collection__type=type_)
        return qs.values_list('addon', flat=True)

    @cached_property
    def mobile_addons(self):
        return self.addons_for_collection_type(amo.COLLECTION_MOBILE)

    @cached_property
    def favorite_addons(self):
        return self.addons_for_collection_type(amo.COLLECTION_FAVORITES)

    @cached_property
    def watching(self):
        return self.collectionwatcher_set.values_list('collection', flat=True)
Esempio n. 10
0
class BasicForm(forms.Form):
    title = forms.CharField(validators=[
        validators.MinLengthValidator(2, "Please enter 2 or more characters")
    ])
    mileage = forms.IntegerField()
    purchase_date = forms.DateField()
Esempio n. 11
0
class Config(InMemoryMixin, models.Model):

    #InMemoryMixin必须放到models.Model之前, 否则其save方法调用不到

    class Meta:
        verbose_name = "考试配置"
        verbose_name_plural = verbose_name

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

    # 系统字段
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    edit_time = models.DateTimeField(verbose_name='编辑时间', auto_now=True)

    enable = models.BooleanField(verbose_name='激活', default=False)
    model_name = models.CharField(verbose_name='报名表类型',
                                  max_length=20,
                                  choices=CHOICE_KAOSHI,
                                  default='')
    url = models.URLField(verbose_name='公告链接', default='')
    title = models.CharField(
        verbose_name='考试标题',
        max_length=80,
        default='',
        unique=True,
        validators=[validators.MinLengthValidator(2)],
    )
    fee = models.PositiveIntegerField(verbose_name='报名费', default=0)
    jingzheng_rate = models.PositiveSmallIntegerField(
        verbose_name='录取比例(面试数:录取数)', default=3)
    bscj_rate = models.FloatField(verbose_name='笔试比重', default=0.5)
    mscj_rate = models.FloatField(verbose_name='面试比重', default=0.5)
    bkgw = models.CharField(
        verbose_name='岗位及其录取数',
        max_length=500,
        default='',
        validators=[ArrayValidator(['\w{2,20}', '\d{1,3}'])])
    bbsgw = models.CharField(verbose_name='不笔试岗位',
                             max_length=500,
                             default='',
                             blank=True,
                             validators=[ArrayValidator(['\w{2,20}'])])
    special_rules = models.CharField(verbose_name='特别规定',
                                     max_length=500,
                                     default='',
                                     blank=True,
                                     validators=[ArrayValidator(col_dlt='\t')])
    bsmenu = models.CharField(
        verbose_name='考试时间地点科目',
        max_length=500,
        default='',
        validators=[ArrayValidator(['\w{2,20}', '\w{2,20}', '\w{2,20}'])])
    submit0 = models.DateTimeField(verbose_name='报名开始时间')
    submit1 = models.DateTimeField(verbose_name='报名结束时间')
    pay0 = models.DateTimeField(verbose_name='缴费开始时间')
    pay1 = models.DateTimeField(verbose_name='缴费结束时间')
    detail0 = models.DateTimeField(verbose_name='打印报名表开始时间')
    detail1 = models.DateTimeField(verbose_name='打印报名表结束时间')
    zkz0 = models.DateTimeField(verbose_name='打印准考证开始时间')
    zkz1 = models.DateTimeField(verbose_name='打印准考证结束时间')
    bscj0 = models.DateTimeField(verbose_name='查询笔试成绩开始时间')
    bscj1 = models.DateTimeField(verbose_name='查询笔试成绩结束时间')
    all0 = models.DateTimeField(verbose_name='查询总成绩开始时间')
    all1 = models.DateTimeField(verbose_name='查询总成绩结束时间')

    article = models.TextField(verbose_name='公告',
                               max_length=5000,
                               default='',
                               blank=True)
Esempio n. 12
0
class AddBookReview(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
        label='Book Title',
        validators=[validators.MinLengthValidator(2)])
    author = forms.ModelChoiceField(
        label='Existing Author',
        queryset=Author.objects.all(),
        required=False,
    )
    newauthor = forms.CharField(
        label="or add new Author",
        widget=forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
        validators=[
            validators.MinLengthValidator(5),
        ],
        required=False,
    )
    review = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'mdl-textfield__input'}),
        validators=[validators.MinLengthValidator(20)])
    rating = forms.ChoiceField(widget=forms.Select(),
                               choices=([0, 0], [1, 1], [2,
                                                         2], [3,
                                                              3], [4,
                                                                   4], [5, 5]))

    def clean(self):
        cleaned_data = super(AddBookReview, self).clean()
        authfield = cleaned_data.get('author')
        newauth = cleaned_data.get('newauthor')

        if not authfield and newauth and len(newauth) < 5:
            self.add_error('author', 'Must specify author')
            self.add_error('newauthor', 'Must specify author')
        if newauth and len(newauth) and not re.match(r'^\w+ \w+$', newauth):
            self.add_error('newauthor',
                           'Author name must have first and last names')

    def save(self):
        author = self.cleaned_data.get('author')
        if not author:
            newauth = self.cleaned_data.get('newauthor')
            newauth = newauth.split(' ')
            first_name = newauth[0]
            last_name = newauth[1]
            try:
                author = Author.objects.get(first_name=first_name,
                                            last_name=last_name)
            except:
                author = Author.objects.create(first_name=first_name,
                                               last_name=last_name)
        book = self.cleaned_data.get('name')
        book_obj = None

        try:
            book_obj = Book.objects.create(name=book, author=author)
        except:
            book_obj = Book.objects.get(name=book)
        rating = self.cleaned_data.get('rating')
        review = self.cleaned_data.get('review')
        review = Review.objects.create(rating=rating,
                                       review=review,
                                       book=book_obj,
                                       user=self.data['user'])
        return review
Esempio n. 13
0
class profileForm(forms.Form):
    email = forms.EmailField(
        validators=[validators.MaxLengthValidator(50)],
        label='Email: ',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control form-input col-md-3',
                'placeholder': '*****@*****.**'
            }))

    alternateEmail = forms.EmailField(
        required=False,
        validators=[validators.MaxLengthValidator(50)],
        label='Alternate Email: ',
        widget=forms.TextInput(attrs={
            'class': 'form-control form-input',
            'placeholder': '*****@*****.**'
        }))

    mobile = forms.IntegerField(
        required=False,
        validators=[
            validators.MaxLengthValidator(10),
            validators.MinLengthValidator(10)
        ],
        min_value=6000000000,
        max_value=9999999999,
        widget=forms.TextInput(attrs={
            'class': 'form-control form-input',
            'placeholder': '9012345678'
        }))

    firstName = forms.CharField(
        label='First Name: ',
        min_length=3,
        max_length=20,
        widget=forms.TextInput(attrs={
            'class': 'form-control form-input',
            'placeholder': 'John'
        }))

    #middleName = forms.CharField(min_length=3, max_length=20, label='Middle Name: ', required=False, widget=forms.TextInput(attrs={'class':'form-control form-input', 'placeholder': 'Ivy'}))

    lastName = forms.CharField(
        min_length=3,
        max_length=20,
        label='Last Name: ',
        widget=forms.TextInput(attrs={
            'class': 'form-control form-input col-md-3',
            'placeholder': 'Doe'
        }))

    dob = forms.DateField(
        required=False,
        label='Date of Birth: ',
        widget=DateInput(attrs={'class': 'form-control form-input'}))

    CHOICES = [(0, 'Male'), (1, 'Female'), (2, 'Other')]
    gender = forms.IntegerField(
        required=False,
        label='Gender: ',
        widget=forms.RadioSelect(
            choices=CHOICES,
            attrs={
                'class': 'custom-control custom-radio custom-control-inline'
            }))

    profilePic = forms.ImageField(required=False,
                                  label='Upload Profile Picture')
Esempio n. 14
0
class User(AbstractBaseUser, PermissionsMixin, TimeStampedModel):
    MALE = 'male'
    FEMALE = 'female'
    OTHER = 'other'
    GENDER_CHOICES = (
        (MALE, _("Male")),
        (FEMALE, _("Female")),
        (OTHER, _("Other")),
    )

    id = models.CharField(
        max_length=11,
        primary_key=True,
        default=custom_uuid,
        editable=False,
    )
    username = models.CharField(
        max_length=24,
        unique=True,
        help_text=_('Max length is 24 symbols. Letters, digits and _/./_ only.'),
        validators=[
            validators.MinLengthValidator(1),
            validators.MaxLengthValidator(24),
        ],
        error_messages={'unique': _("A user with this nickname already exists.")},
        default=custom_uuid,
    )
    name = models.CharField(
        _("Full name of User"),
        max_length=60,
        validators=[validators.MaxLengthValidator(60),
                    validators.MinLengthValidator(1)],
    )
    email = models.EmailField(
        unique=True,
    )
    gender = models.CharField(
        max_length=10,
        choices=GENDER_CHOICES,
        blank=True,
    )
    birth_date = models.DateField(
        null=True,
    )

    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_('Designates whether this user should be treated as active. '
                    'Unselect this instead of deleting accounts.'),
    )
    date_joined = models.DateTimeField(
        _('date joined'),
        default=timezone.now,
    )

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    class Meta:
        db_table = 'users'

    def __str__(self):
        return self.username

    @property
    def is_new(self):
        # Only this data does not exist when a new user is filled with data from a social provider.
        return not any((self.name, self.gender, self.birth_date, self.profile_images_set.exists()))
Esempio n. 15
0
class FeedBackForm(forms.Form):
    name=forms.CharField()
    rollno=forms.IntegerField()
    email=forms.EmailField(validators=[gmail_varification])
    feedback=forms.CharField(widget=forms.Textarea,validators=[validators.MaxLengthValidator(40),validators.MinLengthValidator(10)])
Esempio n. 16
0
class WifiForm(ConnectionForm):
    """Form to create/edit a Wi-Fi connection."""
    field_order = [
        'name', 'interface', 'zone', 'ssid', 'mode', 'band', 'channel',
        'bssid', 'auth_mode', 'passphrase', 'ipv4_method', 'ipv4_address',
        'ipv4_netmask', 'ipv4_gateway', 'ipv4_dns', 'ipv4_second_dns',
        'ipv6_method', 'ipv6_address', 'ipv6_prefix', 'ipv6_gateway',
        'ipv6_dns', 'ipv6_second_dns'
    ]

    ssid = forms.CharField(label=_('SSID'),
                           help_text=_('The visible name of the network.'))
    mode = forms.ChoiceField(label=_('Mode'),
                             choices=[('infrastructure', _('Infrastructure')),
                                      ('ap', _('Access Point')),
                                      ('adhoc', _('Ad-hoc'))])
    band = forms.ChoiceField(label=_('Frequency Band'),
                             choices=[('auto', _('Automatic')),
                                      ('a', _('A (5 GHz)')),
                                      ('bg', _('B/G (2.4 GHz)'))])
    channel = forms.IntegerField(
        label=_('Channel'),
        help_text=_('Optional value. Wireless channel in the selected '
                    'frequency band to restrict to. Blank or 0 value means '
                    'automatic selection.'),
        min_value=0,
        max_value=255,
        required=False)
    bssid = forms.RegexField(
        label=_('BSSID'),
        help_text=_('Optional value. Unique identifier for the access point. '
                    'When connecting to an access point, connect only if the '
                    'BSSID of the access point matches the one provided. '
                    'Example: 00:11:22:aa:bb:cc.'),
        regex=r'^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$',
        required=False)
    auth_mode = forms.ChoiceField(
        label=_('Authentication Mode'),
        help_text=_('Select WPA if the wireless network is secured and \
requires clients to have the password to connect.'),
        choices=[('wpa', _('WPA')), ('open', _('Open'))])
    passphrase = forms.CharField(label=_('Passphrase'),
                                 validators=[validators.MinLengthValidator(8)],
                                 required=False)

    def __init__(self, *args, **kwargs):
        """Initialize the form, populate interface choices."""
        super(WifiForm, self).__init__(*args, **kwargs)
        choices = self._get_interface_choices(nm.DeviceType.WIFI)
        self.fields['interface'].choices = choices

    def get_settings(self):
        """Return setting dict from cleaned data."""
        settings = super().get_settings()
        settings['common']['type'] = '802-11-wireless'
        settings['wireless'] = {
            'ssid': self.cleaned_data['ssid'],
            'mode': self.cleaned_data['mode'],
            'band': self.cleaned_data['band'],
            'channel': self.cleaned_data['channel'],
            'bssid': self.cleaned_data['bssid'],
            'auth_mode': self.cleaned_data['auth_mode'],
            'passphrase': self.cleaned_data['passphrase'],
        }
        return settings
Esempio n. 17
0
class Event(models.Model):
    """
    Base class for Event-objects.
    """

    IMAGE_FOLDER = "images/events"
    IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff']

    # Managers
    objects = models.Manager()
    by_registration = EventOrderedByRegistration()

    author = models.ForeignKey(User, related_name='oppretter', null=True, blank=True)
    title = models.CharField(_('tittel'), max_length=60)
    event_start = models.DateTimeField(_('start-dato'))
    event_end = models.DateTimeField(_('slutt-dato'))
    location = models.CharField(_('lokasjon'), max_length=100)
    ingress_short = models.CharField(_("kort ingress"), max_length=150,
                                     validators=[validators.MinLengthValidator(25)])
    ingress = models.TextField(_('ingress'), validators=[validators.MinLengthValidator(25)])
    description = models.TextField(_('beskrivelse'), validators=[validators.MinLengthValidator(45)])
    image = models.ForeignKey(ResponsiveImage, related_name='events', blank=True, null=True, on_delete=SET_NULL)
    event_type = models.SmallIntegerField(_('type'), choices=TYPE_CHOICES, null=False)

    def is_attendance_event(self):
        """ Returns true if the event is an attendance event """
        try:
            return True if self.attendance_event else False
        except AttendanceEvent.DoesNotExist:
            return False

    def images(self):
        if not self.old_image:
            return []
        from apps.events.utils import find_image_versions
        return find_image_versions(self.old_image)

    # TODO move payment and feedback stuff to attendance event when dasboard is done

    def feedback_users(self):
        if self.is_attendance_event:
            return [a.user for a in self.attendance_event.attendees.filter(attended=True)]
        return []

    def feedback_date(self):
        return self.event_end

    def feedback_title(self):
        return self.title

    def feedback_info(self):
        info = OrderedDict()
        if self.is_attendance_event():
            info[_('Påmeldte')] = self.attendance_event.number_of_attendees
            info[_('Oppmøtte')] = self.attendance_event.number_of_attendees - len(self.attendance_event.not_attended())
            info[_('Venteliste')] = self.attendance_event.number_on_waitlist

        return info

    @property
    def company_event(self):
        try:
            return CompanyEvent.objects.filter(event=self)
        except CompanyEvent.DoesNotExist:
            return None

    def feedback_mail(self):
        if self.event_type == 1 or self.event_type == 4:  # Sosialt & Utflukt
            return settings.EMAIL_ARRKOM
        elif self.event_type == 2:  # Bedpres
            return settings.EMAIL_BEDKOM
        elif self.event_type == 3:  # Kurs
            return settings.EMAIL_FAGKOM
        elif self.event_type == 5:  # Ekskursjon
            return settings.EMAIL_EKSKOM
        else:
            return settings.DEFAULT_FROM_EMAIL

    def can_display(self, user):
        restriction = GroupRestriction.objects.filter(event=self)

        if not restriction:
            return True

        if not user:
            return False

        groups = restriction[0].groups

        # returns True if any of the users groups are in one of the accepted groups
        return any(group in user.groups.all() for group in groups.all())

    @property
    def slug(self):
        return slugify(unidecode(self.title))

    @models.permalink
    def get_absolute_url(self):
        return 'events_details', None, {'event_id': self.id, 'event_slug': self.slug}

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = _('arrangement')
        verbose_name_plural = _('arrangement')
        permissions = (
            ('view_event', 'View Event'),
        )
Esempio n. 18
0
class RegisterForm(forms.Form):
    first_name = forms.CharField(
        required=True,
        label="نام",
        widget=forms.TextInput(attrs={'placeholder': 'نام خود را وارد کنید'}),
        validators=[
            validators.MaxLengthValidator(
                limit_value=20,
                message='نام نمیتواند بیشتر از 20 کاراکتر باشد'),
        ])

    last_name = forms.CharField(
        required=True,
        label="نام خانوادگی",
        widget=forms.TextInput(
            attrs={'placeholder': 'نام خانوادگی را وارد کنید'}),
        validators=[
            validators.MaxLengthValidator(
                limit_value=30,
                message='نام خانوادگی نمیتواند بیشتر از 30 کاراکتر باشد'),
        ])

    # validator excepts username which contains ( 5 < ch < 20 ) characters
    username = forms.CharField(
        required=True,
        label="نام کاربری",
        widget=forms.TextInput(attrs={'placeholder': 'انتخاب نام کاربری'}),
        validators=[
            validators.MaxLengthValidator(
                limit_value=20,
                message='نام کاربری نمیتواند بیشتر از 20 کاراکتر باشد'),
            validators.MinLengthValidator(
                limit_value=5,
                message='نام کاربری نمیتواند کمتر از 5 کاراکتر باشد')
        ])

    email = forms.EmailField(
        required=True,
        label="آدرس ایمیل",
        widget=forms.EmailInput(
            attrs={'placeholder': 'آدرس ایمیل را وارد کنید'}))

    phone_number = forms.CharField(
        required=False,
        label="شماره تماس",
        widget=forms.NumberInput(
            attrs={'placeholder': 'شماره تماس را وارد کنید (اختیاری)'}))

    age = forms.CharField(
        required=False,
        label="سن",
        widget=forms.NumberInput(
            attrs={'placeholder': 'سن خود را وارد کنید (اختیاری)'}))

    # validator excepts passwords which contain more than 6 characters
    password = forms.CharField(
        required=True,
        label="کلمه ی عبور",
        widget=forms.PasswordInput(attrs={"placeholder": "انتخاب کلمه عبور"}),
        validators=[
            validators.MinLengthValidator(
                limit_value=6,
                message='کلمه ی عبور نمیتواند کمتر از 6 کاراکتر باشد')
        ])

    password_again = forms.CharField(
        required=True,
        label="تکرار کلمه ی عبور",
        widget=forms.PasswordInput(attrs={"placeholder": "تکرار کلمه ی عبور"}))

    # checks weather passwords are the same or not!

    def clean_password_again(self):
        data = self.cleaned_data
        password = data.get('password')
        password2 = data.get('password_again')
        if password != password2:
            raise forms.ValidationError('عدم مطابقت کلمه ی عبور')
        return data

    # checks weather the email is taken already or not !
    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError(
                'ایمیل توسط شخص دیگری استفاده شده است ')
        return email

    # checks weather the username is taken already or not!
    def clean_username(self):
        username = self.cleaned_data.get('username')
        qs = User.objects.filter(username=username)
        if qs.exists():
            raise forms.ValidationError(
                'نام کاربری توسط شخص دیگری استفاده شده است')
        return username
Esempio n. 19
0
class AddWifiForm(forms.Form):
    """Form to create a new Wi-Fi connection."""
    name = forms.CharField(label=_('Connection Name'))
    interface = forms.ChoiceField(
        label=_('Physical Interface'),
        choices=(),
        help_text=_('The network device that this connection should be bound '
                    'to.'))
    zone = forms.ChoiceField(
        label=_('Firewall Zone'),
        help_text=_('The firewall zone will control which services are \
available over this interfaces. Select Internal only for trusted networks.'),
        choices=[('external', 'External'), ('internal', 'Internal')])
    ssid = forms.CharField(label=_('SSID'),
                           help_text=_('The visible name of the network.'))
    mode = forms.ChoiceField(label=_('Mode'),
                             choices=[('infrastructure', 'Infrastructure'),
                                      ('ap', 'Access Point'),
                                      ('adhoc', 'Ad-hoc')])
    auth_mode = forms.ChoiceField(
        label=_('Authentication Mode'),
        help_text=_('Select WPA if the wireless network is secured and \
requires clients to have the password to connect.'),
        choices=[('wpa', 'WPA'), ('open', 'Open')])
    passphrase = forms.CharField(label=_('Passphrase'),
                                 validators=[validators.MinLengthValidator(8)],
                                 required=False)
    ipv4_method = forms.ChoiceField(
        label=_('IPv4 Addressing Method'),
        choices=[('auto', 'Automatic (DHCP)'), ('shared', 'Shared'),
                 ('manual', 'Manual')],
        help_text=_('Select Automatic (DHCP) if you are connecting to an \
existing wireless network. Shared mode is useful when running an Access \
Point.'))
    ipv4_address = forms.CharField(
        label=_('Address'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_netmask = forms.CharField(
        label=_('Netmask'),
        help_text=_('Optional value. If left blank, a default netmask '
                    'based on the address will be used.'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_gateway = forms.CharField(
        label=_('Gateway'),
        help_text=_('Optional value.'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_dns = forms.CharField(
        label=_('DNS Server'),
        help_text=_('Optional value. If this value is given and IPv4 '
                    'addressing method is "Automatic", the DNS Servers '
                    'provided by a DHCP server will be ignored.'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_second_dns = forms.CharField(
        label=_('Second DNS Server'),
        help_text=_('Optional value. If this value is given and IPv4 '
                    'Addressing Method is "Automatic", the DNS Servers '
                    'provided by a DHCP server will be ignored.'),
        validators=[validators.validate_ipv4_address],
        required=False)

    def __init__(self, *args, **kwargs):
        """Initialize the form, populate interface choices."""
        super(AddWifiForm, self).__init__(*args, **kwargs)
        choices = _get_interface_choices(nm.DeviceType.WIFI)
        self.fields['interface'].choices = choices
Esempio n. 20
0
    uuid = api.get_cluster_uuid()
    key = UserData.from_userpass_pair(email, password, uuid).key
    return key[20:40].encode('hex')  # Return private part only


identifier_re = re.compile(r'^[a-zA-Z0-9-_]{2,}$')
"""Regex for cluster and volume names."""

identifier_validator = validators.RegexValidator(
    identifier_re,
    message=_("Name should consist of at least two characters and include "
              "only alphanumeric characters, hyphen and underscore."))

max_objects_validator = validators.MaxValueValidator(2**16)

password_validator = validators.MinLengthValidator(8)


def size_validator(value):
    if value < _min_volume_size and value != 0:
        raise ValidationError(_("Size must be either 0 or at least 1MB."))


def replicas_validator(value):
    nodes_count = len(api.listNodes()['nodeList'])
    if value < _min_replica_count or value > nodes_count:
        raise ValidationError(
            _("Replicas must be between {min} and {max}.").format(
                min=_min_replica_count, max=nodes_count))

Esempio n. 21
0
class hetong(BaseKaoshi):
    """
    """
    category = 1  # 用于渲染准考证号

    class Meta:
        verbose_name = "劳动合同"
        verbose_name_plural = verbose_name

    # 考生填写字段
    tx = models.ImageField("头像",
                           blank=True,
                           null=True,
                           upload_to=appname + '/avatar')
    xm = models.CharField(verbose_name='姓名',
                          max_length=10,
                          default='',
                          validators=[
                              validators.MinLengthValidator(2),
                          ])
    xb = models.CharField(verbose_name='性别',
                          max_length=1,
                          default='',
                          choices=CHOICE_XB)
    hjszd = models.CharField(verbose_name='户籍所在地',
                             max_length=50,
                             default='',
                             blank=True)
    kssf = models.CharField(verbose_name='考生身份',
                            max_length=10,
                            default='',
                            choices=CHOICE_KSSF)
    hf = models.CharField(verbose_name='婚否',
                          max_length=1,
                          default='',
                          choices=CHOICE_HF)
    lxdh = models.CharField(verbose_name='联系电话',
                            max_length=20,
                            default='',
                            validators=[
                                validators.RegexValidator(
                                    regex=r'^\d{7,11}$', message='请填写7到11位纯数字')
                            ])
    bkgw = models.CharField(verbose_name='报考岗位', max_length=50, default='')
    mz = models.CharField('民族', max_length=5, default='汉')
    zzmm = models.CharField(verbose_name='政治面貌',
                            max_length=7,
                            default='',
                            choices=CHOICE_ZZMM)
    xl = models.CharField('学历', max_length=4, default='', choices=CHOICE_XL)
    xw = models.CharField('学位',
                          max_length=4,
                          default='',
                          blank=True,
                          choices=CHOICE_XW)
    bysj = models.DateField('毕业时间', null=True)
    byyx = models.CharField('毕业院校', max_length=50, default='')
    zy = models.CharField('专业', max_length=50, default='')
    stzk = models.CharField('身体状况',
                            max_length=2,
                            default='',
                            choices=CHOICE_STZK,
                            blank=True)
    zc = models.CharField('专长', max_length=50, default='', blank=True)
    zgzs = models.CharField('资格证书', max_length=50, default='', blank=True)
    cjgzsj = models.DateField('参加工作时间', blank=True, null=True)
    xgzdwjgw = models.CharField('现工作单位及岗位',
                                max_length=50,
                                blank=True,
                                default='')
    zgsj = models.CharField('资格时间', max_length=60, blank=True, default='')
    jtzz = models.CharField(verbose_name='家庭住址', max_length=100, default='')
    grjl = models.TextField(verbose_name='个人简历', max_length=1000, default='')
    jcqk = models.TextField(verbose_name='奖惩情况',
                            max_length=1000,
                            blank=True,
                            default='')
    jtzycyqk = models.TextField('家庭主要成员情况',
                                max_length=500,
                                default='',
                                blank=True)
Esempio n. 22
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['password'].validators.append(
         validators.MaxLengthValidator(16))
     self.fields['password'].validators.append(
         validators.MinLengthValidator(6))
Esempio n. 23
0
class SSUser(models.Model):

    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                related_name='ss_user')

    plan = models.CharField(
        '套餐',
        max_length=32,
        default='Free',
        choices=PLAN_CHOICES,
    )

    last_check_in_time = models.DateTimeField(
        '最后签到时间',
        null=True,
        # 默认设置为时间戳开始的那天
        default=datetime.datetime.fromtimestamp(0),
        editable=False,
    )

    # shadowsocks 数据库表字段
    password = models.CharField(
        'Shadowsocks密码',
        max_length=32,
        # 当密码少于6位时报错
        validators=[
            validators.MinLengthValidator(6),
        ],
        default=get_short_random_string,
        db_column='passwd',
    )
    port = models.IntegerField(
        '端口',
        db_column='port',
        unique=True,
    )
    last_use_time = models.IntegerField('最后使用时间',
                                        default=0,
                                        editable=False,
                                        help_text='时间戳',
                                        db_column='t')
    upload_traffic = models.BigIntegerField('上传流量', default=0, db_column='u')
    download_traffic = models.BigIntegerField('下载流量', default=0, db_column='d')
    transfer_enable = models.BigIntegerField('总流量',
                                             default=settings.DEFAULT_TRAFFIC,
                                             db_column='transfer_enable')
    switch = models.BooleanField(
        '保留字段switch',
        default=True,
        db_column='switch',
    )
    enable = models.BooleanField(
        '开启与否',
        default=True,
        db_column='enable',
    )

    method = models.CharField(
        '加密类型',
        default=settings.DEFAULT_METHOD,
        max_length=32,
        choices=METHOD_CHOICES,
    )

    protocol = models.CharField(
        '协议',
        default=settings.DEFAULT_PROTOCOL,
        max_length=32,
        choices=PROTOCOL_CHOICES,
    )

    obfs = models.CharField(
        '混淆',
        default=settings.DEFAULT_OBFS,
        max_length=32,
        choices=OBFS_CHOICES,
    )

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

    def get_last_use_time(self):
        '''返回上一次的使用到时间'''
        return timezone.datetime.fromtimestamp(self.last_use_time)

    def get_traffic(self):
        '''返回用户使用的总流量GB '''
        return '{:.2f}'.format(
            (self.download_traffic + self.upload_traffic) / settings.GB)

    def get_transfer(self):
        '''返回用户的总流量 GB'''
        return '{:.2f} '.format(self.transfer_enable / settings.GB)

    def get_unused_traffic(self):
        '''返回用户的剩余流量'''
        return '{:.2f}'.format((self.transfer_enable - self.upload_traffic -
                                self.download_traffic) / settings.GB)

    def get_used_percentage(self):
        '''返回用户的为使用流量百分比'''
        return '{:.2f}'.format((self.download_traffic + self.upload_traffic) /
                               self.transfer_enable * 100)

    def get_check_in(self):
        '''返回当天是否签到'''
        # 获取当天日期
        check_day = self.last_check_in_time.day
        now_day = datetime.datetime.now().day
        return check_day == now_day

    @classmethod
    def get_absolute_url(cls):
        '''返回url链接'''
        return resolve_url('shadowsocks:index')

    def clean(self):
        '''保证端口在1024<50000之间'''
        if self.port:
            if not 1024 < self.port < 50000:
                raise ValidationError('端口必须在1024和50000之间')
        else:
            max_port_user = SSUser.objects.order_by('-port').first()
            if max_port_user:
                self.port = max_port_user.port + choice([2, 3])
            else:
                self.port = settings.START_PORT

    class Meta:
        verbose_name_plural = 'SS账户'
        ordering = ('-last_check_in_time', )
        db_table = 'user'
Esempio n. 24
0
class BetaTestApplication(ValidateModelMixin, TimeStampedModel):
    """
    An application to beta test the Instance Manager.
    """
    BASE_DOMAIN = 'opencraft.hosting'

    PENDING = 'pending'
    ACCEPTED = 'accepted'
    REJECTED = 'rejected'
    STATUS_CHOICES = (
        (PENDING, 'Pending'),
        (ACCEPTED, 'Accepted'),
        (REJECTED, 'Rejected'),
    )

    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE)
    subdomain = models.CharField(
        max_length=255,
        unique=True,
        verbose_name='domain name',
        help_text=('The URL students will visit. In the future, you will also '
                   'have the possibility to use your own domain name.'
                   '\n\nExample: hogwarts.{0}').format(BASE_DOMAIN),
        validators=[
            validators.MinLengthValidator(
                3,
                'The subdomain name must at least have 3 characters.',
            ),
            validators.MaxLengthValidator(
                63,
                'The subdomain name can have at most have 63 characters.',
            ),
            validators.RegexValidator(
                r'^[a-z0-9]([a-z0-9\-]+[a-z0-9])?$',
                'Please choose a name of at least 3 characters, using '
                'lower-case letters, numbers, and hyphens. '
                'Cannot start or end with a hyphen.',
            ),
            validate_available_subdomain,
        ],
        error_messages={
            'unique': 'This domain is already taken.',
            'blacklisted': 'This domain name is not publicly available.',
        },
    )
    external_domain = models.CharField(
        max_length=255,
        unique=True,
        verbose_name='external domain name',
        blank=True,
        null=True,
        help_text=(
            'The URL students will visit if you are using an external domain.'
        ),
        validators=[
            validators.MinLengthValidator(
                3,
                'The subdomain name must at least have 3 characters.',
            ),
            validators.MaxLengthValidator(
                250,
                'The subdomain name can have at most have 250 characters.',
            ),
            validators.RegexValidator(
                r'^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$',
                'Please choose a domain name that you already know and own, '
                'containing lower-case letters, numbers, dots, and hyphens. '
                'Cannot start or end with a hyphen.',
            ),
            validate_available_subdomain,
        ],
        error_messages={
            'unique': 'This domain is already taken.',
            'blacklisted': 'This domain name is not publicly available.',
        },
    )
    instance_name = models.CharField(
        max_length=255,
        help_text=('The name of your institution, company or project.'
                   '\n\nExample: Hogwarts Online Learning'),
    )
    public_contact_email = models.EmailField(
        help_text=('The email your instance of Open edX will be using to '
                   'send emails, and where your users should send their '
                   'support requests.'
                   '\n\nThis needs to be a valid email.'), )
    project_description = models.TextField(
        verbose_name='your project',
        help_text=('What are you going to use the instance for? What are '
                   'your expectations?'),
        blank=True,
        default='')
    privacy_policy_url = models.URLField(
        verbose_name='URL to Privacy Policy',
        help_text=('URL to the privacy policy.'),
        blank=True,
        default='',
    )

    # Theme fields. They allow to define the design, e.g. choose colors and logo
    main_color = models.CharField(
        max_length=7,
        help_text='This is used as the primary color in your theme palette. '
        'It is used as filler for buttons.',
        # #126f9a == $m-blue-d3 in variables.scss. It's rgb(18,111,154)
        default='#126f9a',
        validators=[validate_color],
    )
    link_color = models.CharField(
        max_length=7,
        help_text='This is used as the color for clickable links on your '
        'instance.',
        # Same as main_color. Almost like openedx's #0075b4 == rgb(0, 117, 180)
        default='#126f9a',
        validators=[validate_color],
    )
    header_bg_color = models.CharField(
        max_length=7,
        verbose_name='Header background color',
        help_text='Used as the background color for the top bar.',
        # openedx also uses white by default
        default='#ffffff',
        validators=[validate_color],
    )
    footer_bg_color = models.CharField(
        max_length=7,
        verbose_name='Footer background color',
        help_text='Used as the background color for the footer.',
        # openedx also uses white by default
        default='#ffffff',
        validators=[validate_color],
    )
    # If you're using SWIFT (OpenStack) to store files (this is enabled through
    # the MEDIAFILES_SWIFT_ENABLE environment variable) then you'll need to
    # upload these default images (logo and favicon) to your container. To do so,
    # download the configuration file from the OVH account (top right menu), and
    # run (replacing the cointainer name):
    #
    # source downloaded_openstack_configuration_file.sh
    # swift stat  # this is only to test the connection
    # swift upload 'daniel_testing_file_uploads_from_ocim' \
    #   static/img/png/opencraft_logo_small.png            \
    #   --object-name opencraft_logo_small.png
    # swift upload 'daniel_testing_file_uploads_from_ocim' \
    #   static/img/favicon/opencraft_favicon.ico           \
    #   --object-name opencraft_favicon.ico
    # swift list daniel_testing_file_uploads_from_ocim  # just to check
    #
    # Note that the file names must match the names used in "default", and that
    # the logo should be 48px tall.
    logo = models.ImageField(
        help_text="Your branding to be displayed throughout your instance. "
        "It should be 48px tall. "
        "If unset, OpenCraft's logo will be used.",
        null=True,  # to ease migrations
        blank=False,
        default='opencraft_logo_small.png',
        validators=[validate_logo_height],
    )
    # Same upload instructions as logo
    favicon = models.ImageField(
        help_text="This is used as the browser tab icon for your instance's "
        "pages. If unset, OpenCraft's icon will be used.",
        null=True,  # to ease migrations
        blank=False,
        default='opencraft_favicon.ico',
    )
    hero_cover_image = models.ImageField(
        help_text=
        "This is used as the cover image for the hero section in the instance LMS home page.",
        null=True,  # to ease migrations
        blank=True,
        default=None)
    status = models.CharField(
        max_length=255,
        choices=STATUS_CHOICES,
        default=PENDING,
    )
    instance = models.ForeignKey(
        OpenEdXInstance,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    use_advanced_theme = models.BooleanField(
        default=False,
        help_text=
        ('The advanced theme allows users to pick a lot more details than the regular theme.'
         'Setting this flag will enable the more complex theme editor.'),
    )
    draft_theme_config = JSONField(
        verbose_name='Draft Theme Configuration JSON',
        validators=[theme_schema_validate],
        null=True,
        blank=True,
        help_text=
        ('The theme configuration data currently being edited by the user. When finalised it will'
         'be copied over to the final theme config which will then be deployed to the next appserver'
         'that is launched.'),
    )

    draft_static_content_overrides = JSONField(
        verbose_name='Draft static content overrides JSON',
        validators=[static_content_overrides_schema_validate],
        null=True,
        blank=True,
        default=None,
        help_text=
        ("The static content overrides data currently being edited by the user. When finalised, it will "
         'be copied over to the final static content overrides which will then be deployed to the '
         'next appserver that is launched'))

    def __str__(self):
        return self.domain

    @property
    def first_activated(self):
        """
        Return the activation date for the first AppServer to activate.
        """
        if self.instance:
            return self.instance.first_activated
        return None

    @property
    def domain(self):
        """
        The full domain requested for this application.
        """
        return '{0}.{1}'.format(self.subdomain, self.BASE_DOMAIN)

    def email_addresses_verified(self):
        """
        Return True if both the user's email address and this application's
        public contact email address have been verified.
        """
        email_addresses = {self.user.email, self.public_contact_email}
        verified = EmailAddress.objects.exclude(confirmed_at=None).filter(
            email__in=email_addresses)
        return verified.count() == len(email_addresses)

    def clean(self):
        """
        Verify that the domains were not already been taken by any running instance.

        We can't do this in a regular validator, since we have to allow the subdomain of the
        instance associated with this application.
        """
        errors = {}

        # Check internal domain
        generated_domain = generate_internal_lms_domain(self.subdomain)
        if self.instance is not None and self.instance.internal_lms_domain == generated_domain:
            return
        if OpenEdXInstance.objects.filter(
                internal_lms_domain=generated_domain).exists():
            subdomain_error = ValidationError(
                message='This domain is already taken.',
                code='unique',
            )
            errors['subdomain'] = [subdomain_error]

        # Check external domain, if present
        if self.external_domain:
            if self.instance is not None and self.instance.external_lms_domain == self.external_domain:
                return
            if OpenEdXInstance.objects.filter(
                    external_lms_domain=self.external_domain).exists():
                external_domain_error = ValidationError(
                    message='This domain is already taken.',
                    code='unique',
                )
                errors['external_domain'] = [external_domain_error]

        if errors:
            raise ValidationError(errors)

    def commit_changes_to_instance(self,
                                   deploy_on_commit=False,
                                   retry_attempts=2,
                                   creator=None,
                                   deployment_type=None,
                                   cancel_pending_deployments=False):
        """
        Copies over configuration changes stored in this model to the related instance,
        and optionally spawn a new instance.

        :param deploy_on_commit: Initiate new deployment after committing changes
        :param deployment_type: Type of deployment
        :param creator: User initiating deployment
        :param retry_attempts: Number of times to retry deployment
        """
        instance = self.instance
        if instance is None:
            return

        instance.theme_config = self.draft_theme_config
        instance.static_content_overrides = self.draft_static_content_overrides
        instance.name = self.instance_name
        instance.privacy_policy_url = self.privacy_policy_url
        instance.email = self.public_contact_email
        instance.save()
        if deploy_on_commit:
            create_new_deployment(
                instance,
                creator=creator,
                deployment_type=deployment_type,
                mark_active_on_success=True,
                num_attempts=retry_attempts,
                cancel_pending=cancel_pending_deployments,
                add_delay=True,
            )
Esempio n. 25
0
        'master',
        'jennifer',
        '111111',
        '2000',
        'jordan',
        'superman'
        'harley'
    ]
    message = _("Please choose a less common password")
    code = 'password'

    def __init__(self, password_file=None):
        self.limit_value = password_file

    def clean(self, value):
        return value.strip()

    def compare(self, value, limit):
        return value in self.forbidden_passwords

    def get_forbidden_passwords(self):
        if self.limit_value is None:
            return self.forbidden_passwords


# List all requirements for password, site wide
password_validators = [
    validators.MinLengthValidator(6),
    CommonPasswordValidator(),
]
Esempio n. 26
0
class ContactForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={"placeholder" : "Fullname" , "class" : "form-control"}) , label='' , validators=[validators.MinLengthValidator(limit_value=3 , message="Fullname length should be more than 2 characters")])
    email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder" : "Email" , "class" : "form-control"}) , label='')
    subject = forms.CharField(widget=forms.TextInput(attrs={"placeholder" : "Subject" , "class" : "form-control"}) , label='' , validators=[validators.MinLengthValidator(limit_value=3 , message="Subject length should be more than 2 characters")])
    text = forms.CharField(widget=forms.Textarea(attrs={"placeholder" : "Message" , "class" : "form-control w-100"}) , label='' , validators=[validators.MinLengthValidator(limit_value=10 , message="Subject length should be more than 10 characters") , validators.MaxLengthValidator(limit_value=200 , message="Subject length should be less than 200 characters")])
Esempio n. 27
0
class User(CreatedUpdated, Registration):
    username = models.CharField(
        max_length=20,
        null=False,
        blank=False,
        unique=True,
        help_text='' \
            'Minimum of 3 characters, maximum of 20 characters, ' \
            'containing characters and numbers.',
        validators=[validators.MinLengthValidator(3)]
    )
    password = models.CharField(
        max_length=250,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(7),
            validators.RegexValidator(regex=r'[0-9]',
                                      message='Must have at least one number'),
            validators.RegexValidator(
                regex=r'[a-zA-Z]', message='Must have at least one character'),
        ])
    email = models.EmailField(max_length=250,
                              null=False,
                              blank=False,
                              unique=True)
    first_name = models.CharField(max_length=250, null=False, blank=False)
    last_name = models.CharField(max_length=250, null=False, blank=False)

    @classmethod
    def authenticate(cls, username, password_string):
        encoded_password_string = password_string.encode('utf-8')
        try:
            user = cls.objects.get(username=username)
            input_password = bcrypt.hashpw(encoded_password_string,
                                           user.password.encode('utf-8'))
            return user.password == input_password
        except cls.DoesNotExist:
            return None

    @property
    def full_name(self):
        return '%s %s' % (
            self.first_name,
            self.last_name,
        )

    def set_password(self, password_string):
        self.password = bcrypt.hashpw(password_string, bcrypt.gensalt())

    def has_a_group(self):
        return self.usergroup_set.all().count() > 0

    def is_logged_in(self, request):
        return request.session.get('logged_in_user_id', None) == self.id

    def is_registered(self):
        return self.id is not None

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

    def __unicode__(self):
        return unicode(self.full_name)
Esempio n. 28
0
class MailList(models.Model):
    account = models.ForeignKey(settings.AUTH_USER_MODEL,
                                blank=False,
                                null=True,
                                on_delete=models.CASCADE,
                                related_name='mail_list_account')

    company = models.ForeignKey('Company',
                                blank=False,
                                null=True,
                                on_delete=models.CASCADE,
                                related_name='mail_list_company')

    domain = models.ForeignKey('Domain',
                               blank=False,
                               null=False,
                               on_delete=models.CASCADE,
                               related_name='mail_list_domain')

    product_profile = models.ForeignKey(
        'ProductProfile',
        blank=False,
        null=True,
        on_delete=models.CASCADE,
        related_name='mail_list_product_profile')

    date_from = models.DateTimeField(auto_now_add=True)

    in_queue = models.BooleanField(default=False)

    is_active = models.BooleanField(default=False)

    is_moderated = models.BooleanField(default=False)

    name = models.EmailField(blank=False,
                             null=False,
                             validators=[
                                 validators.MinLengthValidator(5),
                                 validators.EmailValidator
                             ])

    remove = models.EmailField(blank=False,
                               null=False,
                               validators=[
                                   validators.MinLengthValidator(5),
                                   validators.EmailValidator
                               ])

    subscribe = models.EmailField(blank=False,
                                  null=False,
                                  validators=[
                                      validators.MinLengthValidator(5),
                                      validators.EmailValidator
                                  ])

    tracker = FieldTracker()

    class Meta:
        db_table = 'mail_list'

        default_permissions = ()

        verbose_name = 'Mailing List'
        verbose_name_plural = 'Mailing Lists'
Esempio n. 29
0
class Item(models.Model):
    """
    データ定義クラス
      各フィールドを定義する
    参考:
    ・公式 モデルフィールドリファレンス
    https://docs.djangoproject.com/ja/3.1/ref/models/fields/
    """

    name = models.CharField(
        verbose_name='顧客名',
        max_length=20,
        blank=True,
        null=True,
    )

    name_furigana = models.CharField(verbose_name='フリガナ',
                                     max_length=20,
                                     blank=True,
                                     null=True,
                                     default='',
                                     validators=[
                                         validators.RegexValidator(
                                             regex=u'^[ァ-ヶ]+$',
                                             message='全角フリガナ20文字以内で入力して下さい',
                                         )
                                     ])

    postcode = models.CharField(verbose_name='郵便番号',
                                max_length=7,
                                blank=True,
                                null=True,
                                default='',
                                validators=[
                                    validators.RegexValidator(
                                        regex=r'^[0-9]+$',
                                        message='半角数字7文字(ハイフン「-」無し)で入力して下さい',
                                    ),
                                    validators.MinLengthValidator(7)
                                ])

    todofukenChoice = (
        (1, '北海道'),
        (2, '青森県'),
        (3, '岩手県'),
        (4, '宮城県'),
        (5, '秋田県'),
        (6, '山形県'),
        (7, '福島県'),
        (8, '茨城県'),
        (9, '栃木県'),
        (10, '群馬県'),
        (11, '埼玉県'),
        (12, '千葉県'),
        (13, '東京都'),
        (14, '神奈川県'),
        (15, '新潟県'),
        (16, '富山県'),
        (17, '石川県'),
        (18, '福井県'),
        (19, '山梨県'),
        (20, '長野県'),
        (21, '岐阜県'),
        (22, '静岡県'),
        (23, '愛知県'),
        (24, '三重県'),
        (25, '滋賀県'),
        (26, '京都府'),
        (27, '大阪府'),
        (28, '兵庫県'),
        (29, '奈良県'),
        (30, '和歌山県'),
        (31, '鳥取県'),
        (32, '島根県'),
        (33, '岡山県'),
        (34, '広島県'),
        (35, '山口県'),
        (36, '徳島県'),
        (37, '香川県'),
        (38, '愛媛県'),
        (39, '高知県'),
        (40, '福岡県'),
        (41, '佐賀県'),
        (42, '長崎県'),
        (43, '熊本県'),
        (44, '大分県'),
        (45, '宮崎県'),
        (46, '鹿児島県'),
        (47, '沖縄県 '),
    )

    address1 = models.IntegerField(
        verbose_name='都道府県',
        choices=todofukenChoice,
        blank=True,
        null=True,
    )

    address2 = models.CharField(
        verbose_name='市町村番地',
        max_length=40,
        blank=True,
        null=True,
    )

    address3 = models.CharField(
        verbose_name='建物名',
        max_length=40,
        blank=True,
        null=True,
    )

    email = models.EmailField(
        verbose_name='メール',
        max_length=100,
        blank=True,
        null=True,
    )

    # サンプル項目9 選択肢(マスタ連動)
    Dantai = models.ForeignKey(
        Dantai,
        verbose_name='所属団体(マスタ連動)',
        blank=True,
        null=True,
        related_name='Dantai',
        on_delete=models.SET_NULL,
    )

    leaseDate = models.DateField(
        verbose_name='リース期限',
        blank=True,
        null=True,
    )

    onlineSupport = models.BooleanField(verbose_name='オンラインサポート', )

    hpUrl = models.URLField(
        verbose_name='HPのURL',
        max_length=100,
        blank=True,
        null=True,
    )

    memo = models.TextField(
        verbose_name='メモ',
        blank=True,
        null=True,
    )

    # # サンプル項目1 文字列
    # CustomerName = models.CharField(
    #     verbose_name='顧客名',
    #     max_length=20,
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目2 メモ
    # sample_2 = models.TextField(
    #     verbose_name='サンプル項目2 メモ',
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目3 整数
    # sample_3 = models.IntegerField(
    #     verbose_name='サンプル項目3 整数',
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目4 浮動小数点
    # sample_4 = models.FloatField(
    #     verbose_name='サンプル項目4 浮動小数点',
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目5 固定小数点
    # sample_5 = models.DecimalField(
    #     verbose_name='サンプル項目5 固定小数点',
    #     max_digits=5,
    #     decimal_places=2,
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目6 ブール値
    # sample_6 = models.BooleanField(
    #     verbose_name='サンプル項目6 ブール値',
    # )

    # # サンプル項目7 日付
    # sample_7 = models.DateField(
    #     verbose_name='サンプル項目7 日付',
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目8 日時
    # sample_8 = models.DateTimeField(
    #     verbose_name='サンプル項目8 日時',
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目9 選択肢(固定)
    # sample_9_choice = (
    #     (1, '選択1'),
    #     (2, '選択2'),
    #     (3, '選択3'),
    # )

    # sample_9 = models.IntegerField(
    #     verbose_name='サンプル項目9_選択肢(固定)',
    #     choices=sample_9_choice,
    #     blank=True,
    #     null=True,
    # )

    # # サンプル項目9 選択肢(マスタ連動)
    # sample_10 = models.ForeignKey(
    #     User,
    #     verbose_name='サンプル項目10_選択肢(マスタ連動)',
    #     blank=True,
    #     null=True,
    #     related_name='sample_10',
    #     on_delete=models.SET_NULL,
    # )

    # 以下、管理項目

    # 作成者(ユーザー)
    created_by = models.ForeignKey(
        User,
        verbose_name='作成者',
        blank=True,
        null=True,
        related_name='CreatedBy',
        on_delete=models.SET_NULL,
        editable=False,
    )

    # 作成日時
    created_at = models.DateTimeField(
        verbose_name='作成日時',
        blank=True,
        null=True,
        editable=False,
    )

    # 更新者(ユーザー)
    updated_by = models.ForeignKey(
        User,
        verbose_name='更新者',
        blank=True,
        null=True,
        related_name='UpdatedBy',
        on_delete=models.SET_NULL,
        editable=False,
    )

    # 更新日時
    updated_at = models.DateTimeField(
        verbose_name='更新日時',
        blank=True,
        null=True,
        editable=False,
    )

    def __str__(self):
        """
        リストボックスや管理画面での表示
        """
        return self.name

    class Meta:
        """
        管理画面でのタイトル表示
        """
        verbose_name = '顧客マスタ'
        verbose_name_plural = '顧客マスタ'
Esempio n. 30
0
class BillingForm(forms.Form):
    first_name = forms.CharField(widget=forms.TextInput(attrs={"placeholder" : "First name" , "class" : "form-control" , "id" : "first"}) , label='' , validators=[validators.MinLengthValidator(limit_value=3 , message="First length should be more than 2 characters")])
    last_name = forms.CharField(widget=forms.TextInput(attrs={"placeholder" : "Last name" , "class" : "form-control" , "id" : "last"}) , label='' , validators=[validators.MinLengthValidator(limit_value=3 , message="Last name length should be more than 2 characters")])
    phone = forms.CharField(widget=forms.TextInput(attrs={"placeholder" : "Phone number" , "class" : "form-control" , "id" : "number"}) , label='' , validators=[validators.MinLengthValidator(limit_value=3 , message="Phone length should be more than 2 characters")])
    email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder" : "Email" , "class" : "form-control" , "id" : "email"}) , label='')
    address = forms.CharField(widget=forms.TextInput(attrs={"placeholder" : "Address" , "class" : "form-control"}) , label='' , validators=[validators.MinLengthValidator(limit_value=3 , message="Address length should be more than 2 characters")])
    notes = forms.CharField(widget=forms.Textarea(attrs={"placeholder" : "Order Notes" , "class" : "form-control w-100"}) , label='' , validators=[validators.MinLengthValidator(limit_value=10 , message="Note length should be more than 10 characters") , validators.MaxLengthValidator(limit_value=200 , message="Note length should be less than 200 characters")] , required=False)
    is_accept_terms = forms.BooleanField(widget=forms.CheckboxInput(attrs={"id" : "f-option4"}) , label='I\'ve read and accept the terms and conditions')