我有一个表单,可以选择多个复选框,但是当我尝试从post请求中的字典中检索键时。它只提供数组的第一个值(可能不是数组)。我想检索所有数据点。
模型
class CreateJournalistForm(forms.Form):
vertical_choices = (('General', 'General'), ('News', 'News'), ('Life', 'Life'), ('Money', 'Money'), ('Sports', 'Sports'), ('Entertainment', 'Entertainment'), ('Dating', 'Dating'), ('Music', 'Music'), ('Humor', 'Humor'))
name = forms.CharField(max_length=40, required=False)
verticals = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple, choices=vertical_choices)
location = forms.CharField(max_length=40)
查看
def journalist(request):
if request.method == "POST":
form = CreateJournalistForm(request.POST)
pdb.set_trace()
if not form.data['name']:
if form.is_valid():
form.save()
return HttpResponse("Thank you for applying. We hope to get back to you soon")
else:
return HttpResponse("Sorry there was an error processing your application. Note: All fields on the application are required.")
else:
return HttpResponse("Thank you for applying. We hope to get back to you soon")
elif request.method == "GET":
form = CreateJournalistForm()
return render_to_response('journalist_application.html', {'form': form}, context_instance=RequestContext(request))
在pry调试器中,请求帖子将提供:
<QueryDict: {u'sample': [u'sdfsdf'], u'first_name': [u'sdfsd'], u'last_name': [u'sdfsf'], u'name': [u''], u'dob': [u'1/22/13'], u'twitter': [u'sdfsdf'], u'ideas': [u'sdfsdf'], u'contribution': [u'sdf'], u'verticals': [u'General', u'News', u'Life', u'Money', u'Sports'], u'google': [u'sdfsdf'], u'location': [u'sdfsdf']}
这是由调试器中的request.POST提供的。现在,如果我提供密钥request.POST ['verticals'],它将只返回数组中的一个对象。 u'Sports'
答案 0 :(得分:1)
我不知道你为什么要直接访问请求,因为你有一个表单,它负责将params转换为一个对象。
但是,您可以使用request.POST.getlist('verticals')
获取密钥的所有值。