我有以下表格:
class QuestionForm(forms.Form):
options = forms.ModelMultipleChoiceField(queryset=Option.objects.none(),
widget=forms.RadioSelect)
def __init__(self, *args, **kwargs):
question_id = kwargs.pop('question_id', None)
super(QuestionForm, self).__init__(*args, **kwargs)
if question_id:
print question_id
question = Question.objects.get(pk=question_id)
ts = Option.objects.filter(question = question)
for t in ts:
print t.name
self.fields['options'].queryset = Option.objects.filter(question = question)
def clean(self):
print 'in clean'
#this is the last thing to print before failing
cleaned_options = self.cleaned_data['options']
try:
print cleaned_options
raise forms.ValidationError('That is not the right answer. Try again.')
except:
return cleaned_options
我在我看来这样称呼它:
if request.method == "POST":
print 'in post'
form = QuestionForm(request.POST, question_id=question.id)
print '---'
options = request.POST.getlist('options')
option = options[0]
print option
if form.is_valid():
print '******'
print form
else:
print '######'
print form.errors
我的模板如下所示:
<form action="" method="post">
{% csrf_token %}
{{ form }}
{{ form.errors }}
<br />
<button type="submit">Save</button>
</form>
我在使用Form的行的模板中遇到一个关键错误:
抛出错误的行似乎是:
cleaned_options = self.cleaned_data['options']
答案 0 :(得分:1)
您永远不会在视图中返回HttpResponse
。
试试这个:
if request.method == "POST":
print 'in post'
form = QuestionForm(request.POST, question_id=question.id)
print '---'
options = request.POST.getlist('options')
option = options[0]
print option
if form.is_valid():
print '******'
print form
return HttpResponseRedirect('/admin/')
else:
form=QuestionForm()
return render(request,'myapp/form.html',{'form':form})
答案 1 :(得分:1)
覆盖clean()
方法时,您应该使用super()
。这会调用clean()
的继承功能。所以你的表格应该是这样的:
class QuestionForm(forms.Form):
# for logic
def clean(self):
super(QuestionForm, self).clean()
# get the initial 'cleaned_data' Dict from the form
cleaned_data = self.cleaned_data
# clean it however you wish, just make sure to return it at the end of clean()
return cleaned_data
同样如上所述的“脑风暴”,观点必须返回Http Responses
。