我正在尝试使用Django表单来允许Django用户输入他们最喜欢的三个兴趣.在模板呈现期间发生错误,其中显示{{form.as_ul}}.
这是代码:
reg_interests.html
{% block content %}
<br><br>
<h1>Choose the 3 things that interest you most!</h1>
<form method="post" action="/reg_interests/">
{% csrf_token %}
{{form.as_ul}}
<br>
<p class="submit"><input class="btn btn-default" type="submit" name="commit" value="Continue"></p>
</form>
{% endblock %}
views.py
def reg_interests_view(request):
if request.POST:
form = InterestsForm(request.POST, request=request)
if form.is_valid():
form.save(request)
return redirect('/reg_video/')
args = {}
args['form'] = InterestsForm(request=request)
return render(request, 'login/reg_interests.html', args)
forms.py
class InterestsForm(RequestModelForm):
interest1 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")])
interest2 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")])
interest3 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")])
class Meta:
model = Interest
fields = ('interest1', 'interest2', 'interest3')
def __init__(self, request):
self.user = request.user
def save(self, commit=True):
interest = super(InterestsForm, self).save(commit=False)
interest.user = self.user
interest.interest1 = self.cleaned_data['interest1']
interest.interest2 = self.cleaned_data['interest2']
interest.interest3 = self.cleaned_data['interest3']
if commit:
interest.save()
return interest
我认为表单存在问题,但我不知道如何或为什么需要定义_errors. Django本身不应该照顾它吗?如果没有,我该如何定义_errors?
最佳答案 这段代码根本不可能工作,因为你覆盖了表单的__init__方法,以便a)你只接受一个请求参数 – 而不是表单所期望的任何其他东西,比如数据或初始 – 和b)你永远不会调用超类init方法来初始化表单代码所需的其余内容.您需要保留签名并调用super.
def __init__(self, *args, **kwargs):
request = kwargs.pop('request')
self.user = request.user
super(InterestsForm, self).__init__(*args, **kwargs)