我尝试使用Django表单来允许Django用户输入他们最喜欢的三个兴趣爱好。错误发生在模板呈现过程中,它显示{{form.as_ul}}
。在
代码如下:
注册_兴趣.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 %}
视图.py
^{pr2}$表单.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
?在
这段代码根本不可能工作,因为您重写了表单的}-并且b)您永远不会调用超类init方法来初始化表单代码其余部分所期望的内容。你需要保留签名然后打电话给超级。在
__init__
方法,以便a)您只接受request
参数,而不接受表单所期望的任何其他内容,例如data
或{相关问题 更多 >
编程相关推荐