tags:

views:

24

answers:

1

I'm making a form for user registration. Here's what my template looks like:

<h1>Register</h1>
    <form action="/register/" method="post">
        {{ form.as_p }}
        <input type="submit" value="Register">
    </form>

And here's my view:

from djangoproject1.authentication import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def main(request):
    rform = forms.RegisterForm()
    return render_to_response("authentication/index.html", {'form': rform})

def register(request):
    if request.method == 'POST':
        rform = forms.RegisterForm(request.POST)
        if rform.is_valid():
            print 'VALID!'
            # do something
            return HttpResponseRedirect("/register-success/")
        else:
            print 'INVALID!'
            rform = forms.RegisterForm()
    return render_to_response("authentication/index.html", {'form': rform})

I haven't gotten to the VALID part yet, I'm still working on the invalid part. Here is what my form looks like:

from django import forms

class RegisterForm(forms.Form):
    username = forms.CharField(min_length=6,max_length=15)
    password = forms.CharField(widget = forms.PasswordInput(),min_length=6,max_length=15)
    confirm_password = forms.CharField(widget = forms.PasswordInput(),min_length=6,max_length=15)
    phone_number = forms.RegexField('\d\d\d-\d\d\d-\d\d\d\d',error_message='Invalid format')

    def clean_password(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if password != confirm_password:
            raise forms.ValidationError("Passwords don't match")
        return password

Username, password, phone number. Pretty straightforward. However, when I hit "Register" without filling in anything, I should get a bunch of errors but they don't appear anywhere. Is that supposed to happen automatically or am I missing something?

Thanks!

+1  A: 

Hello again, I think your problem is that in your else you're resetting your form to a new one, and the new form hasn't been validated. Try removing this line of code from your else

rform = forms.RegisterForm()
Matthew J Morrison
Yep, if you remove that line, you will return the invalid form, which will contain the error message(s) for the fields that were left empty.
nstehr
so does that answer your question?
Matthew J Morrison
Sorry, ran off for a bit. Yes that does answer my question, however, I'm still running into an issue. I'm getting a KeyError exception on "confirm_password". I looked up KeyError and it says Raised "when a mapping (dictionary) key is not found in the set of existing keys." From what I understand about cleaned_data, 'confirm_password' should be in there b/c it's a field but I guess it isnt
JPC