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):
cpassword = 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>