Max Goodridge Max Goodridge - 3 months ago 63
Python Question

Django AttributeError: 'InterestsForm' object has no attribute '_errors'

I am trying to use a Django form to allow a Django User to input their three favourite interests. The error occurs during the template rendering where it says

{{form.as_ul}}
.

Here is the code:

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


I think there is a problem with the form, but I don't know how or why I need to define
_errors
. Should Django itself not take care of that? If not, how do I define
_errors
?

Answer

This code can't possibly work at all, because you override the __init__ method of the form so that a) you only accept a request argument - and not any of the other things a form is expecting, like data or initial - and b) you never call the superclass init method to initialise the things the rest of the form code expects. You need to preserve the signature and call super.

def __init__(self, *args, **kwargs):
     request = kwargs.pop('request')
     self.user = request.user
     super(InterestsForm, self).__init__(*args, **kwargs)