Reputation: 2827
I'm trying to create a form where you have to choose a year. I'm pretty sure this is really easy, but I don't know why I get some errors.
The main error is this:
'AbiturForm' object has no attribute 'fields'
My class with the form:
class AbiturForm(forms.Form):
year=forms.CharField(widget=forms.Select(),required=False)
abitur=forms.BooleanField(required=False)
def __init__(self):
choices=[(x,x) for x in range(1900,2000)]
self.fields['year'].choices=choices
My template:
{% extends "home/portal.html" %}
{% block body %}
<div id="content-main">
<div class="module">
<h2>Suche:</h2>
<form action="/suchen/abitur/" method="post">
{% csrf_token %}
<table>
<tr>
<td><label><b>Jahr:</b></label></td>
<td>
<select style="width:200px" name="year" id="year">
</select>
</td>
</tr>
<tr>
<td><label><b>Abitur?:</b></label></td>
<td>
<input type="checkbox" name="abitur" id="abitur" class="texto" />
</td>
</tr>
</table>
<input type="submit" value="Speichern" class="button"/>
</form>
</div>
</div>
{% endblock %}
Any help would be appreciated.
Thanks :)
Upvotes: 0
Views: 2200
Reputation: 599540
zsquare is correct, but note that there's no need to override __init__
unless you want to build the choices dynamically. Usually you would just do it in the declaration:
class AbiturForm(forms.Form):
year = forms.ChoiceField(choices=[(x, x) for x in range(1900, 2000)], required=False)
Couple of points to note: it's probably better to use ChoiceField
(which defaults to a Select widget already), and please note PEP8 format for spaces around punctuation.
Upvotes: 2
Reputation: 10146
Fields is not setup until you call super. Try:
class AbiturForm(forms.Form):
year=forms.CharField(widget=forms.Select(),required=False)
abitur=forms.BooleanField(required=False)
def __init__(self):
super(AbiturForm, self).__init__()
choices=[(x,x) for x in range(1900,2000)]
self.fields['year'].choices=choices
Upvotes: 2