0
我有一個表單可以選擇多個複選框,但是當我嘗試從發佈請求中的字典中檢索密鑰時。它只提供數組的第一個值(可能不是數組)。我想檢索所有的數據點。如何檢索請求(django)中複選框的所有數據?
模型
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))
在撬調試信息發佈將提供:
<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'
工作!我如何使用表單來獲取數據? – Dap
您應該使用form.cleaned_data來訪問表單驗證後的數據。這一切都在表單文檔中解釋,正如向用戶顯示錯誤的正確模式一樣。 –