Using Django Forms
December 22, 2010 Leave a comment
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')
u.save()
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
try:
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}
c.update(csrf(request))
return render_to_response('<appname>/register.html', c)
Read more about csrf.