1
我想使用Django表單來允許Django用戶輸入他們三個最喜歡的興趣。錯誤發生在模板渲染過程中,它表示{{form.as_ul}}
。Django AttributeError:'InterestsForm'對象沒有屬性'_errors'
下面是代碼:
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
?
謝謝!我永遠不會想到這一點。 –