I am trying to assign a value to a ChoiceField in a Django form.
# forms.py
MONTH_CHOICES = (
("JANUARY", "January"),
("FEBRUARY", "February"),
#...
("DECEMBER", "December"),
)
class SomeMonthSelectingform(forms.Form):
month = forms.ChoiceField(choices=MONTH_CHOICES)
def __init__(self, *args, **kwargs):
month = kwargs.pop("month")
super(SomeMonthSelectingform, self).__init__(*args, **kwargs)
self.fields['month'] = month
The selected value of the choice field named month should be the actual month (e.g. right now it would be ‘JULY’)
# views.py
def month_view(request: HttpRequest):
month = datetime.now().month
monthIndex = month - 1
monthChoice = MONTH_CHOICES[monthIndex][0]
monthForm = SomeMonthSelectingform(month=monthChoice)
if request.method == 'POST':
filledForm = SomeMonthSelectingform(data=request.POST)
if not filledForm.is_valid():
raise Exception("Month form was invalid")
monthForm = filledForm
args = {
'monthForm': monthForm
}
return render(request, 'month.html', 'args')
<!-- month.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Month</h2>
<form action="{% url '...' %}" method="post">
{% csrf_token %}
{{ monthForm }}
<input type="submit" name="..." value="Show">
</form>
{% endblock %}
Sadly, I keep getting the error 'str' object has no attribute 'get_bound_field'
. I am quite sure it is because, I should not assign ‘JULY’ to self.fields['month']
inside the constructor of the form. But I can not find another solution.