gkomninos.com

programming, web and other stuff

Create a registration form with django

Published on June 28, 2010

categories: django and programming Tags : django

In this article i will show you how you can create a user registration form with django.

  • Let's define what we need to create:

A simple registration form containing username, email and password fields .

  • lets go into code (πάμε στο ζουμί !!! ... greek)

In your application create a forms.py file if not exits

-----forms.py-----

from django.contrib.auth.models import User
from django import forms

class SignupForm(forms.Form):
    username = forms.CharField(max_length=30)
    email = forms.EmailField();
    password1 = forms.CharField(max_length=30,
                            widget=forms.PasswordInput(render_value=False))
    password2 = forms.CharField(max_length=30,
                            widget=forms.PasswordInput(render_value=False))

    def clean_username(self):
        try:
            User.objects.get(username=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError("This username is already in use")

    def clean(self):
        if 'password1' in self.changed_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords do not match")
        return self.cleaned_data

    def save(self):
        new_user = User.objects.create_user(username=self.cleaned_data['username'],
                                         email=self.cleaned_data['email'],
                                        password=self.cleaned_data['password1'])

In the above code we use the django User model.

First we create a SignupForm class containig the fields we need and some methods.

Methods clean and clean_username are used for validation. In clean_username we check if the username exists in the database.
The clean method is a general method and applies to all form fields. So in clean we can check other fields in this method (not checked myself). Note the raise forms.ValidationError("") in both methods.

Method save saves the new user into database.

  • now we need a view to process the form

------ views.py --------

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from myproject.myapp.forms import SignupForm

def signup(request):
    if request.method == 'POST':
        form = SignupForm(data=request.POST)
        if form.is_valid():
            form.save();
            return HttpResponseRedirect("/welcome/")
    else:
        form = SignupForm()
    return render_to_response('signup.html',
                          {'form': form},
                           context_instance=RequestContext(request))

how this works:

  1. first we check the method of the incoming request
  2. if the method is POST then we instatiate a SignupForm passing request.POST as it's data.
  3. then we check if the form passes validation. if the data are valid then we save the form and redirect to another page.
  4. if the request.method is not POST then we initiate a SignupForm without any data.
  5. finally ( this is not executed for valid data) we render a template passing the form as a variable to it and return a response.

The final part is to display the form in signup.html

<html>
    <head>
        <title>Signup</title>
    </head>
    <body>
        <h1>Sign up for an account</h1>
        <form action="/signup/" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
    </form>
    </body>
</html>

you can find more about rendering the form displaying-a-form-using-a-template

Similar links from my delicious

Comments

Post a comment

captcha