예제 #1
0
    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                if u'@' in username:
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _(
                                "Your e-mail address is not your username."
                                " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        self.check_for_test_cookie()
        return self.cleaned_data
예제 #2
0
 def clean_url(self):
     url = self.cleaned_data['url']
     if not url.startswith('/'):
         raise forms.ValidationError(
             ugettext("URL is missing a leading slash."))
     if (settings.APPEND_SLASH
             and 'my_django.middleware.common.CommonMiddleware'
             in settings.MIDDLEWARE_CLASSES and not url.endswith('/')):
         raise forms.ValidationError(
             ugettext("URL is missing a trailing slash."))
     return url
 def clean_email(self):
     """
     Validates that an active user exists with the given email address.
     """
     email = self.cleaned_data["email"]
     self.users_cache = User.objects.filter(email__iexact=email,
                                            is_active=True)
     if not len(self.users_cache):
         raise forms.ValidationError(self.error_messages['unknown'])
     if any((user.password == UNUSABLE_PASSWORD)
            for user in self.users_cache):
         raise forms.ValidationError(self.error_messages['unusable'])
     return email
    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'])
            elif not self.user_cache.is_active:
                raise forms.ValidationError(self.error_messages['inactive'])
        self.check_for_test_cookie()
        return self.cleaned_data
 def clean_password2(self):
     password1 = self.cleaned_data.get("password1", "")
     password2 = self.cleaned_data["password2"]
     if password1 != password2:
         raise forms.ValidationError(
             self.error_messages['password_mismatch'])
     return password2
 def clean_password2(self):
     password1 = self.cleaned_data.get('password1')
     password2 = self.cleaned_data.get('password2')
     if password1 and password2:
         if password1 != password2:
             raise forms.ValidationError(
                 self.error_messages['password_mismatch'])
     return password2
 def clean_username(self):
     # Since User.username is unique, this check is redundant,
     # but it sets a nicer error message than the ORM. See #13147.
     username = self.cleaned_data["username"]
     try:
         User.objects.get(username=username)
     except User.DoesNotExist:
         return username
     raise forms.ValidationError(self.error_messages['duplicate_username'])
 def clean_old_password(self):
     """
     Validates that the old_password field is correct.
     """
     old_password = self.cleaned_data["old_password"]
     if not self.user.check_password(old_password):
         raise forms.ValidationError(
             self.error_messages['password_incorrect'])
     return old_password
예제 #9
0
    def clean(self):
        cleaned_data = self.cleaned_data

        if cleaned_data.get('from_rev') > cleaned_data.get('to_rev'):
            raise forms.ValidationError(
                'The "from" revision must be lower than the "to" revision.')
            del cleaned_data['to_rev']
            del cleaned_data['from_rev']
        return cleaned_data
예제 #10
0
 def clean_security_hash(self):
     """Check the security hash."""
     security_hash_dict = {
         'content_type': self.data.get("content_type", ""),
         'object_pk': self.data.get("object_pk", ""),
         'timestamp': self.data.get("timestamp", ""),
     }
     expected_hash = self.generate_security_hash(**security_hash_dict)
     actual_hash = self.cleaned_data["security_hash"]
     if not constant_time_compare(expected_hash, actual_hash):
         raise forms.ValidationError("Security hash check failed.")
     return actual_hash
    def clean(self, value):
        """
        Validates that the input value can be converted to a Geometry
        object (which is returned).  A ValidationError is raised if
        the value cannot be instantiated as a Geometry.
        """
        if not value:
            if self.null and not self.required:
                # The geometry column allows NULL and is not required.
                return None
            else:
                raise forms.ValidationError(self.error_messages['no_geom'])

        # Trying to create a Geometry object from the form value.
        try:
            geom = GEOSGeometry(value)
        except:
            raise forms.ValidationError(self.error_messages['invalid_geom'])

        # Ensuring that the geometry is of the correct type (indicated
        # using the OGC string label).
        if str(geom.geom_type).upper(
        ) != self.geom_type and not self.geom_type == 'GEOMETRY':
            raise forms.ValidationError(
                self.error_messages['invalid_geom_type'])

        # Transforming the geometry if the SRID was set.
        if self.srid:
            if not geom.srid:
                # Should match that of the field if not given.
                geom.srid = self.srid
            elif self.srid != -1 and self.srid != geom.srid:
                try:
                    geom.transform(self.srid)
                except:
                    raise forms.ValidationError(
                        self.error_messages['transform_error'])

        return geom
예제 #12
0
    def clean(self):
        url = self.cleaned_data.get('url', None)
        sites = self.cleaned_data.get('sites', None)

        same_url = FlatPage.objects.filter(url=url)
        if self.instance.pk:
            same_url = same_url.exclude(pk=self.instance.pk)

        if same_url.filter(sites__in=sites).exists():
            for site in sites:
                if same_url.filter(sites=site).exists():
                    raise forms.ValidationError(
                        _('Flatpage with url %(url)s already exists for site %(site)s'
                          % {
                              'url': url,
                              'site': site
                          }))

        return super(FlatpageForm, self).clean()
예제 #13
0
 def clean_comment(self):
     """
     If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
     contain anything in PROFANITIES_LIST.
     """
     comment = self.cleaned_data["comment"]
     if settings.COMMENTS_ALLOW_PROFANITIES == False:
         bad_words = [
             w for w in settings.PROFANITIES_LIST if w in comment.lower()
         ]
         if bad_words:
             raise forms.ValidationError(
                 ungettext(
                     "Watch your mouth! The word %s is not allowed here.",
                     "Watch your mouth! The words %s are not allowed here.",
                     len(bad_words)) % get_text_list([
                         '"%s%s%s"' % (i[0], '-' * (len(i) - 2), i[-1])
                         for i in bad_words
                     ], ugettext('and')))
     return comment
 def check_for_test_cookie(self):
     if self.request and not self.request.session.test_cookie_worked():
         raise forms.ValidationError(self.error_messages['no_cookies'])
예제 #15
0
 def clean_timestamp(self):
     """Make sure the timestamp isn't too far (> 2 hours) in the past."""
     ts = self.cleaned_data["timestamp"]
     if time.time() - ts > (2 * 60 * 60):
         raise forms.ValidationError("Timestamp check failed")
     return ts
예제 #16
0
 def clean_honeypot(self):
     """Check that nothing's been entered into the honeypot."""
     value = self.cleaned_data["honeypot"]
     if value:
         raise forms.ValidationError(self.fields["honeypot"].label)
     return value