Using Django Forms

You can customize your forms using this or build forms off the models.

With my project I chose to not go with the modelForm since I wanted to customize the text and input.  Here’s the registration form again:


class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=30, required=True)
    password = forms.CharField(widget=forms.PasswordInput, required=True)
    repeat_password = forms.CharField(widget=forms.PasswordInput, required=True)
    first_name = forms.CharField(max_length=30, required=False)
    last_name = forms.CharField(max_length=30, required=False)
    def save(self):
        if self.is_valid():
            cleaned_data = self.cleaned_data
            u = User.objects.create_user(cleaned_data.get('username'), '', cleaned_data.get('password'))
            u.first_name = cleaned_data.get('first_name')
            u.last_name = cleaned_data.get('last_name')


Note that we are using cleaned_data instead of the request.POST.

So, we’ll add more validation to the registration. We’d like to make sure we check if the username is already pre-existing before we add to the table and show errors.

Form.is_valid() executes validation when it is ran. One of the validation is Form.clean(). Let’s override that


    def clean(self):
        cleaned_data = self.cleaned_data
            u = User.objects.get(username__exact=cleaned_data.get('username'))
            raise forms.ValidationError("Username already exists.")
        except User.DoesNotExist:
            test = 0
        if (cleaned_data.get('password') != cleaned_data.get('repeat_password')):
            raise forms.ValidationError("Passwords don't match.")
        return cleaned_data


The errors will go into a variable that can be accessed with Form.non_field_errors()

On the view side, we can render the form with a few different ways mentioned here.

Or you can view my example found here.

And make sure you add this on the template before the <form>


{% csrf_token %}


And add this to the context of your view


c = {'form', form}
return render_to_response('<appname>/register.html', c)


Read more about csrf.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: