我正在尝试为Web应用程序的客户端创建一个基本的用户注册系统。
我已经创建了适当的视图和模板来创建一个表单页面,该页面创建了一个Django User对象和我自己创建的UserProfile对象。 (这些是通过1-1字段链接的。)
在我的注册页面上的表单中访问和归档后,我单击“提交”,将清除与初始化UserProfile字段相关的字段,并显示“此字段是必需的”。错误将显示在每个输入框上(尽管先前已正确填写)。如果我再次填写这些选定的字段,然后按提交,将正确处理注册请求。
在终端中,我已经为每个表单打印出is_valid()的值。在第一次传递时,User表单返回true,而UserProfile表单返回false。在第二次提交时,它们都返回true。
你能帮助我理解为什么第二个表格在第一遍中返回false并强迫我重新提交?
代码如下:
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=32)
email = models.CharField(max_length=100)
institute = models.CharField(max_length=100)
address1 = models.CharField(max_length=100)
address2 = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
postal_code = models.CharField(max_length=24)
description = models.TextField(max_length=2500)
def __unicode__(self):
return self.name
class UserForm(ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'email']
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ['user']
def registration(request):
if request.method == 'POST':
print('post')
user_form = UserForm(request.POST, prefix='user')
profile_form = UserProfileForm(request.POST, prefix='userprofile')
print('user form ' + str(user_form.is_valid()))
print('profile form ' + str(profile_form.is_valid()))
if user_form.is_valid() and profile_form.is_valid():
print('both valid')
user = user_form.save(commit=False)
user.is_active = False
user.save()
userprofile = profile_form.save(commit=False)
userprofile.user = user
userprofile.save()
print('success')
return HttpResponseRedirect('registration-success/')
else:
print('unbound')
user_form = UserForm(prefix='user')
profile_form = UserProfileForm(prefix='profile')
context = { 'userform': user_form,
'userprofileform': profile_form,}
return render(request, 'registration/register.html', context)
def success(request):
return render(request, 'registration/success.html', )
<!DOCTYPE html>
<html>
<body>
<h2> Registration </h2>
<form method="POST">
{% csrf_token %}
{{userform}}
</br></br>
{{userprofileform}}
<input type="submit" value="Submit"/>
</form>
<a href="password_reset/" id="forgot"> forgot username/password</a><br />
<a href="register" id="new">new user</a>
</body>
</html>
答案 0 :(得分:0)
在你的POST代码路径中,你有这个:
profile_form = UserProfileForm(request.POST, prefix='userprofile')
在你的else代码路径中,这个:
profile_form = UserProfileForm(prefix='profile')
前缀值需要匹配,以便POST数据正确绑定到配置文件表单。它适用于您的重新提交,因为它通过POST代码路径,因此模板中使用的ID与表单对象所期望的那些匹配。