Login

use oldforms validators in newforms forms

Author:
garywilson
Posted:
April 9, 2007
Language:
Python
Version:
.96
Score:
4 (after 4 ratings)

Using the run_oldforms_validators function, you can run oldforms validators in your newforms clean_XXX methods.

Usage example:

class PasswordForm(forms.Form):

    password = forms.CharField(widget=forms.PasswordInput())

    def clean_password(self):
        validator_list = [
            isStrongPassword,
            isValidLength,
            SomeValidators(
                num_required=3,
                validator_list=[hasLower, hasUpper, hasNumeric, hasSpecial],
                error_message="Password must contain at least 3 of: lowercase, uppercase, numeric, and/or special characters."
            )
        ]
        run_oldforms_validators('password', self, validator_list)
        return self.clean_data['password']

Above, isStrongPassword, isValidLength, etc. are oldforms validators. If you are interested in seeing the implementation of isStrongPassword, please see my Using CrackLib to require stronger passwords blog post.

 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
from django.core.validators import ValidationError, CriticalValidationError
from django.newforms import ValidationError as newformsValidationError

def run_oldforms_validator(field_name, form, validator):
    """
    Run an oldforms validator against a newforms form.  This function is nearly
    identical to oldforms.FormField.run_validator.
    """
    # Use form.data here instead of form.clean_data because the oldforms
    # validators worked with the raw POST data.
    if form.fields[field_name].required or \
            form.data.get(field_name, None) or \
            hasattr(validator, 'always_test'):
        validator(form.data.get(field_name, ''), form.data)

def run_oldforms_validators(field_name, form, validator_list):
    """
    Run a list of oldforms validators against a newforms form.  This function
    is nearly identical to oldforms.FormField.run_validators.
    """
    errors = {}
    try:
        for validator in validator_list:
            try:
                run_oldforms_validator(field_name, form, validator)
            except ValidationError, e:
                errors.setdefault(field_name, []).extend(e.messages)
    # If a CriticalValidationError is raised, ignore any other ValidationErrors
    # for this particular field
    except CriticalValidationError, e:
        errors.setdefault(field_name, []).extend(e.messages)
    if errors:
        raise newformsValidationError(errors[field_name])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

drg006 (on August 17, 2007):

This is a great snipppet :) Thanks!

But why does errors need to be a dict? Couldn't it just be a list since only one key (field_name) is ever used?

#

Please login first before commenting.