我正在探索Django中的formsets机制。以下是我所做的一切:
forms.py
from django import forms
MONTH_CHOICES = (("JANUARY", "January"),
("FEBRUARY", "February"),
("MARCH", "March"),
("DECEMBER", "December"),)
class NameForm(forms.Form):
your_name = forms.ChoiceField(label="Your Name",choices=MONTH_CHOICES)
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
from django.forms.formsets import formset_factory
from .forms import NameForm
def index(request):
lfs = formset_factory(NameForm)
if request.method == 'POST':
postedformset = lfs(request.POST)
if postedformset.is_valid():
for formz in postedformset:
print formz.cleaned_data['your_name']
return HttpResponseRedirect('/polls/thanks/')
else:
form = NameForm()
return render(request,'name.html',{'form':lfs})
def thanks(request):
return HttpResponse('Form filled. Thanks!')
3.用于实现带有一些javascript的formset的HTML,用于添加和删除表单
name.html
<html>
<head>
<title>DJANGO - First Forms</title>
</head>
<body>
<form action="/polls/" method="POST">
{{ form.management_form }}
<div class="link-formset">
{{ form }}
</div>
<input type="Submit"/>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.formset/1.2.2/jquery.formset.min.js"></script>
<script>
$('.link-formset').formset({
addText: 'add link',
deleteText: 'remove'
});
</script>
使用此reference
进行实施问题
我能够添加多个选择字段并保存表单而不会出现任何问题。但是,仅在
时打印了第一个表单的选项 print formz.cleaned_data['your_name')
被执行了。来自request.POST的Querydict可以选择formset中的所有表单(引用更新)
请分享您对此的看法。
PS:我确实检查了this和this等问题,但仍然无法追查根本原因。
更新
对于我的formset中的2个表单,当我尝试打印request.POST时,获取了QueryDict,其中包含来自两种表单的信息..
<QueryDict: {u'form-1-form-TOTAL_FORMS': [u''], u'form-1-form-MIN_NUM_FORMS': [u''], u'form-1-form-MAX_NUM_FORMS': [u''], u'form-1-form-INITIAL_FORMS': [u''], u'form-MAX_NUM_FORMS': [u'1000', u'1000'], u'form-1-your_name': [u'FEBRUARY'], u'form-0-your_name': [u'FEBRUARY'], u'form-MIN_NUM_FORMS': [u'0', u'0'], u'form-INITIAL_FORMS': [u'0', u'0'], u'form-TOTAL_FORMS': [u'2', u'1']}>