Django Form class question
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 != conf开发者_Python百科irm_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!
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()
精彩评论