Example #1
0
 def clean(self):
     if self.followee_id == self.follower_id:
         raise validators.ValidationError(u'关注者和被关注者不能相同。')
     objs = UserFollow.objects.filter(follower_id=self.follower_id,
                                      followee_id=self.followee_id).all()
     if len(objs) > 0 and objs[0].id != self.id:
         raise validators.ValidationError(u'不能重复关注。')
 def clean(self):
     fields = self.cleaned_data
     keys = list(fields.keys())
     if(len(fields['title']) <=10):
         raise validators.ValidationError("%(val)s Must be Greater Then 10 ", params={'val':keys[0]})
     if(len(fields['Content']) <=10):
         raise validators.ValidationError("%(val)s Must be Greater Then 10 ", params={'val':keys[0]})
Example #3
0
    def validateBackupPeer(self, field_data, all_data):
        if all_data["peerHost"]:
            hostCapabilities = smartbox.remotebackup.getHostCapabilities(
                all_data["peerHost"], all_data["peerUsername"],
                all_data["peerPassword"])
            if not hostCapabilities:
                raise validators.ValidationError(
                    "Unable to connect to this backup host: check username and password."
                )

            # Test if rsync is available.
            if not hostCapabilities[smartbox.remotebackup.CAP_RSYNC]:
                raise validators.ValidationError(
                    "The specified backup host does not support rsync, which is essential for efficient backups."
                )

            # Test encryption caps
            if all_data["peerEncryptionKey"]:
                if not hostCapabilities[
                        smartbox.remotebackup.
                        CAP_RSYNC_SMARTBOX] or not hostCapabilities[
                            smartbox.remotebackup.CAP_OPENSSL]:
                    raise validators.ValidationError(
                        "Although data transfer will be encrypted, the specified backup host does not support encrypted storage of the data.  Please set the encryption key to empty for this host."
                    )
Example #4
0
def check_tx_hash(tx_hash):
    """Does the input look like a hash?
    """

    if not tx_hash.isalnum():
        raise validators.ValidationError('tx_hash must be alphanumeric')

    if len(tx_hash) != HASH_LEN:
        raise validators.ValidationError('tx_hash length not {}'.format(HASH_LEN))
Example #5
0
    def clean(self):
        fields=self.cleaned_data
        print(fields)
        keys=list(fields.keys())
        if(len(fields[keys[0]])<10):
            raise validators.ValidationError(f"{keys[0]} must have at list 10 charchter")

        if(len(fields[keys[1]])<10):
            raise validators.ValidationError(f"{keys[1]} must have at list 10 charchter")
Example #6
0
def check_addr(dest_addr):
    """Does the input look like a bitcoin address?
    """

    if not dest_addr.isalnum():
        raise validators.ValidationError('dest_addr must be alphanumeric')

    if not MIN_ADDR_LEN <= len(dest_addr) <= MAX_ADDR_LEN:
        raise validators.ValidationError('dest_addr length between {} and {}'.format(MIN_ADDR_LEN, MAX_ADDR_LEN))
 def isValidUser(self, field_data, all_data):
     username = field_data
     password = all_data.get('password', None)
     self.user_cache = authenticate(username=username, password=password)
     if self.user_cache is None:
         raise validators.ValidationError(
             _("Please enter a correct username and password. Note that both fields are case-sensitive."
               ))
     elif not self.user_cache.is_active:
         raise validators.ValidationError(_("This account is inactive."))
Example #8
0
 def validate_int(self, value, index):
     try:
         value = int(value)
     except TypeError:
         raise validators.ValidationError(message=self.int_message %
                                          (self.int_min, self.int_max),
                                          code=self.code)
     if not self.int_min <= value <= self.int_max:
         raise validators.ValidationError(message=self.int_message %
                                          (self.int_min, self.int_max),
                                          code=self.code)
Example #9
0
    def clean_projectId(self):
        projectId = self.cleaned_data['projectId']
        if projectId is None:
            raise validators.ValidationError('Error')

        project = Project.objects.get(id=self.cleaned_data['projectId'])

        if project is None:
            raise validators.ValidationError('Error')

        return project
Example #10
0
    def clean(self):
        fields = self.cleaned_data
        keys = list(fields.keys())

        if len(fields['title']) <= 10:
            raise validators.ValidationError(
                "%(vals)s must be greater than 10", params={'vals': keys[0]})

        if len(fields['content']) <= 50:
            raise validators.ValidationError(
                "%(vals)s must be greater than 10", params={'vals': keys[1]})
Example #11
0
 def clean(
         self):  #for all fields rather than indivual, creates a dictionary
     fields = self.cleaned_data
     print(fields)
     keys = list(fields.keys())
     if (len(fields['title']) <= 10):  #if this is envoked other bellow wont
         raise validators.ValidationError("%(val)s Must be grater than 10",
                                          params={'val': keys[0]})
     if (len(fields['content']) <= 10):
         raise validators.ValidationError("%(val)s Must be greater than 10",
                                          params={'val': keys[1]})
Example #12
0
 def clean(self):
     password = self.cleaned_data.get('password')
     confirm_password = self.cleaned_data.get('confirm_password')
     # print('rakesh', password, confirm_password)
     if password == confirm_password:
         if not len(password) >= 6:
             raise validators.ValidationError(
                 'Password length is less then 6')
         return self.cleaned_data
     else:
         raise validators.ValidationError(
             'Password and confirm_password does not match')
Example #13
0
def phone_number_validator(phone_number):
    try:
        phone_number = str(phone_number)
    except ValueError:
        raise validators.ValidationError('Invalid Input')

    if phone_number.isdigit() is False:
        raise validators.ValidationError(
            'Phone numbers can only contain numbers')

    if not (10 <= len(phone_number) <= 11):
        raise validators.ValidationError(
            'Length of phone number must be either 10 or 11')
Example #14
0
 def validate_range(self, value, index):
     try:
         min_, max_ = value.split('-')
     except ValueError:
         raise validators.ValidationError(message=_("Bad range format"),
                                          code=self.code)
     self.validate_int(min_, index)
     self.validate_int(max_, index)
     min_, max_ = int(min_), int(max_)
     if min_ >= max_:
         raise validators.ValidationError(message=self.range_message %
                                          (self.int_min, self.int_max),
                                          code=self.code)
Example #15
0
 def validate_frequency(self, value, index):
     star, freq = value.split('/')
     try:
         freq = int(freq)
     except TypeError:
         raise validators.ValidationError(message=self.freq_message,
                                          code=self.code)
     if freq <= 0:
         raise validators.ValidationError(message=self.freq_message,
                                          code=self.code)
     if star != '*':
         raise validators.ValidationError(
             message=_("The first character of frequency must be '*'."),
             code=self.code)
Example #16
0
def isValiableRInfo(field_data,all_data):
    r_type = RecordType.objects.get(id=all_data['record_type'])
    if r_type.record_type == 'A':
        ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
        if ipv4_re.match(str(all_data['record_info'])) == None:
            raise validators.ValidationError(_('record_info_iperr'))
    elif r_type.record_type == 'CNAME':
        try:
            domain_str = all_data['record_info']
            name = domain_str[:domain_str.index('.')]
            domain = domain_str[domain_str.index('.')+1:]
            if len(Record.objects.filter(name=name,domain__name=domain)) == 0:
                raise validators.ValidationError(_('record_not_existed_a'))
        except:
            raise validators.ValidationError(_('record_syntax_err'))
Example #17
0
 def clean_email(self) :
     email = self.cleaned_data.get("email", "")
     try :
         User.objects.get(email=email)
     except User.DoesNotExist :
         return email
     raise validators.ValidationError(u'邮箱 %s 已被注册。' % email)
    def isValidTemplate(self, field_data, all_data):
        # get the settings module
        # if the site isn't set, we don't raise an error since the site field will
        try:
            site_id = int(all_data.get('site', None))
        except (ValueError, TypeError):
            return
        settings_module = self.settings_modules.get(site_id, None)
        if settings_module is None:
            return

        # so that inheritance works in the site's context, register a new function
        # for "extends" that uses the site's TEMPLATE_DIRS instead.
        def new_do_extends(parser, token):
            node = loader.do_extends(parser, token)
            node.template_dirs = settings_module.TEMPLATE_DIRS
            return node
        register = template.Library()
        register.tag('extends', new_do_extends)
        template.builtins.append(register)

        # Now validate the template using the new template dirs
        # making sure to reset the extends function in any case.
        error = None
        try:
            tmpl = loader.get_template_from_string(field_data)
            tmpl.render(template.Context({}))
        except template.TemplateSyntaxError as e:
            error = e
        template.builtins.remove(register)
        if error:
            raise validators.ValidationError(e.args)
Example #19
0
 def clean(self):
     cleaned_data = super().clean()
     pwd1 = cleaned_data.get('pwd1')
     pwd2 = cleaned_data.get('pwd2')
     if pwd1 != pwd2:
         raise validators.ValidationError(message='两次输入密码不一致')
     return cleaned_data
Example #20
0
 def userExists(self, field_data, all_data):
     """ Checks if a user by the username exists and raises and error if not """
     try:
         User.objects.get(username=field_data)
     except User.DoesNotExist:
         raise validators.ValidationError(
             'The username "%s" is does not exist.' % field_data)
Example #21
0
    def clean(self):
        cleaned_data = super(LoginForm, self).clean()

        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        user = services.authenticate_user(username, password)

        if user is None:
            raise validators.ValidationError(
                u'Este usuario no existe o la contraseña es incorrecta.')
        if not user.is_active:
            raise validators.ValidationError(u'Este usuario está desactivado.')

        cleaned_data['user'] = user

        return cleaned_data
Example #22
0
 def checkUsername(self, wanted):
     try:
         User.objects.get(username=wanted)
     except:
         return
     raise validators.ValidationError(
         'Username is already taken')  #% wanted
Example #23
0
 def clean_twitter_username(self):
      _twitter_username=self.cleaned_data['twitter_username']
      try:
        match=profiles_target_model.objects.get(twitter_username=_twitter_username)
      except:
        return self.cleaned_data['twitter_username']
      raise validators.ValidationError("target already exsists")
Example #24
0
 def clean_username(self) :
     username = self.cleaned_data.get("username", "")
     try :
         User.objects.get(username=username)
     except User.DoesNotExist :
         return username
     raise validators.ValidationError(u'抱歉,用户名 %s 已被使用。' % username)
Example #25
0
    def save(self):
        user = User.objects.get(id=self.cleaned_data['id'])
        if user:
            user.username = self.cleaned_data['username']
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
            user.email = self.cleaned_data['email']
            user.is_staff = self.cleaned_data['is_staff']
            user.save()

            if self.cleaned_data['thumbnail']:
                thumbnail_name = self.cleaned_data['thumbnail'].name
                string = thumbnail_name.split('/')[-1]
                format = string.split('.')[-1]
                thumbnail_name = "avatar_"+str(user.id)+"."+format
                user.thumbnail.save(thumbnail_name, self.cleaned_data['thumbnail'], save=True)
            elif self.cleaned_data['photoId']:
                thumbnail_name = nameOfUserAvatar(str(user.id))
                file = localAvatarFile(self.cleaned_data['photoId'])
                if file:
                    user.thumbnail.save(thumbnail_name,file , save=True)


            return user
        else:
            raise validators.ValidationError('Error')
Example #26
0
def isValidUsername(field_data):
    try:
        User.objects.get(username=field_data)
    except User.DoesNotExist:
        return
    raise validators.ValidationError(
        'Der Benutzername {} ist bereits vergeben.'.format(field_data))
Example #27
0
def isValidUsername(username):
    try:
        User.objects.get(username=username)
    except User.DoesNotExist:
        return
    raise validators.ValidationError('The username "%s" is already taken.' %
                                     username)
 def clean_email(self):
     try:
         User.objects.get(email__iexact=self.data['email'])
     except User.DoesNotExist:
         return self.data['email']
     raise validators.ValidationError('The email "%s" is already taken.' %
                                      (self.data['email']))
Example #29
0
 def isValidUsername(self, field_data, all_data):
     try:
         User.objects.get(username=field_data)
     except User.DoesNotExist:
         return
     raise validators.ValidationError(
         'The username "%s" is already taken.' % field_data)
Example #30
0
def manipulator_validator_unique_for_date(from_field, date_field, opts,
                                          lookup_type, self, field_data,
                                          all_data):
    from django.db.models.fields.related import ManyToOneRel
    date_str = all_data.get(
        date_field.get_manipulator_field_names('')[0], None)
    date_val = oldforms.DateField.html2python(date_str)
    if date_val is None:
        return  # Date was invalid. This will be caught by another validator.
    lookup_kwargs = {'%s__year' % date_field.name: date_val.year}
    if isinstance(from_field.rel, ManyToOneRel):
        lookup_kwargs['%s__pk' % from_field.name] = field_data
    else:
        lookup_kwargs['%s__iexact' % from_field.name] = field_data
    if lookup_type in ('month', 'date'):
        lookup_kwargs['%s__month' % date_field.name] = date_val.month
    if lookup_type == 'date':
        lookup_kwargs['%s__day' % date_field.name] = date_val.day
    try:
        old_obj = self.manager.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        return
    else:
        if hasattr(
                self, 'original_object') and self.original_object._get_pk_val(
                ) == old_obj._get_pk_val():
            pass
        else:
            format_string = (lookup_type == 'date') and '%B %d, %Y' or '%B %Y'
            date_val = datetime_safe.new_datetime(date_val)
            raise validators.ValidationError("Please enter a different %s. The one you entered is already being used for %s." % \
                (from_field.verbose_name, date_val.strftime(format_string)))