Django ModelForm validated without submitting
I have a form on my home page. My view for that looks like this:
from djangoproject1.authentication import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def main(request):
uf = forms.UserForm()
upf = forms.UserProfileForm()
return render_to_response("authentication/index.html", {'form1': uf, 'form2':upf})
def register(request):
if request.method == 'POST':
uf = forms.UserForm(request.POST)
upf = forms.UserProfileForm(request.POST)
if uf.is_valid() and upf.is_valid():
user = uf.save(commit=False)
user.set_password(uf.cleaned_data["password"])
user.save()
userprofile = upf.save(commit=False)
userprofile.user = user
userprofile.save()
return HttpResponseRedirect("/register-success/")
return render_to_response("authentication/index.html", {'form1': uf,'form2':upf})
It makes one form with these two parts. When I launch my browser however, all the error messages already appear. I thought this left them unbound and therefore they wouldn't try and be validated since I didn't post anything.
Here's the form code:
from django import forms
from django.contrib.auth.models import User
from djangoproject1.authentication.models import UserProfile
class UserForm(forms.ModelForm):
cpas开发者_C百科sword = forms.PasswordInput()
def clean(self):
if self.cleaned_data['cpassword']!=self.cleaned_data['password']:
raise forms.ValidationError("Passwords don't match")
class Meta:
model = User
fields = ('username','email','password',)
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('phonenumber',)
Here's the html:
<h1>Register</h1>
<form action="/register/" method="post">
{{ form1.as_p }}
{{ form2.as_p }}
<input type="submit" value="Register">
</form>
From what you've described, it seems as if you're hitting the register
view with an invalid POST. But you say this is happening on the main
view when you go to the page?
There shouldn't be any form errors with an unbound form (like main
would return) but they would show up on a bound form after a failed is_valid
call in register
.
The one thing I can see is that your clean
method on UserForm
doesn't return self.cleaned_data
.
It might make things a bit easier to troubleshoot if you temporarily change the name of one of the templates and make sure you are getting the view you think you are.
Turns out it wasn't errors but help texts.
精彩评论