我有这个型号:
class Member(models.Model):
profile = models.OneToOneField(Profile, editable=False, null=True)
title = models.CharField(max_length=4, choices=TITLE_TYPES, null=True)
name = models.CharField(max_length=100, null=True, verbose_name='Name')
lastname = models.CharField(max_length=100, null=True, verbose_name='LastName')
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, verbose_name='Gender')
dob = models.DateField('dob')
redressno = models.CharField(max_length=100, null=True, verbose_name='RedressNo')
表格:
class MemberForm(ModelForm):
dob = forms.DateField(required=False, input_formats=('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y'))
class Meta:
model = Member
exclude = ('profile',)
观点:
MemberFormSet = formset_factory(MemberForm, formset=BaseFormSet)
print request.method
if request.method == 'POST': # If the form has been submitted...
signup_form = SignupForm(None, request.POST) # A form bound to the POST data
# Create a formset from the submitted data
member_formset = MemberFormSet(request.POST, request.FILES)
# import pdb; pdb.set_trace()
if signup_form.is_valid() and member_formset.is_valid():
print 'in valid'
signup = signup_form.save(request.POST)
for form in member_formset.forms:
member = form.save(commit=False)
member.profile = signup
# import pdb; pdb.set_trace()
member.save()
#log-in to user
user = authenticate(username = request.POST['username'], password = request.POST['password'] )
auth_login(request, user)
return redirect("/main") # Redirect to a 'success' page
else:
signup_form = SignupForm()
data = {
'form-TOTAL_FORMS': u'1',
'form-INITIAL_FORMS': u'0',
'form-MAX_NUM_FORMS': u''
}
member_formset = MemberFormSet(data)
# member_formset.total_form_count=0
# For CSRF protection
# See http://docs.djangoproject.com/en/dev/ref/contrib/csrf/
c = {
'form': signup_form,
'member_formset': member_formset,
}
c.update(csrf(request))
return render_to_response('registration.html', c, RequestContext(request))
模板:
<form action="/registration/" method="POST">
{% csrf_token %}
<div class="section">
{{ form.as_p }}
</div>
<h2>Members</h2>
{{ member_formset.management_form }}
{% for form in member_formset.forms %}
<div class="item">
{{ form.as_table }}
<p style=""><a class="delete" href="#">Delete</a></p>
</div>
{% endfor %}
<p><a id="add" href="#">Add another item</a></p>
<input type="submit" value=" Submit " />
并且对memberform的验证无效。请说明原因?
答案 0 :(得分:1)
你没有真正解释你的问题,但是如果注册表单无效,我猜你不会继续验证成员表单集,因为这行:
if signup_form.is_valid() and member_formset.is_valid():
在Python中,与许多其他语言一样,and
是快捷方式评估的:即,如果第一个元素为False,则从不评估第二个元素。因此,is_valid
永远不会在formset上运行,因此不会显示任何错误。
相反,这样做:
signup_valid = signup_form.is_valid()
formset_valid = member_formset.is_valid()
if signup_valid and formset_valid:
确保两个验证都是单独执行的。
答案 1 :(得分:0)
首先,我没有看到无效表单的else
分支。其次,不是第一个参数None
,对于此行中的表单初始化是错误的:signup_form = SignupForm(None, request.POST)
。