Reputation: 4114
I have a form where I define selection criterias for report. One of the dropdowns 'building' that is auto populated from the model , should be not mandatory and have default value as empty. I can't achieve the empty part .
I want first field in my dropdown
in my form
building = forms.IntegerField(
widget=forms.Select(
choices=Building.objects.all().values_list('id', 'name')
) , required=False
)
in view file when I initialize the code
form = PaymentRangeForm(initial = {'building': 0 })
I use crispy forms in my template but I don't think it makes any difference.
<form method="POST" class="form" action="" method="get">
{% csrf_token %}
{{ form|crispy}}
<br>
<button type="submit" class="btn btn-primary btn-primary">Search</button>
</form>
I am not getting any error but the default is not empty it has a value of first record from the model.
What I am missing?
Upvotes: 3
Views: 2403
Reputation: 4114
Ok Solution was simple. In my from file I have added
from django.db.models.fields import BLANK_CHOICE_DASH
and updated the form
class PaymentRangeForm(forms.Form):
start_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'} ))
end_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'} ))
building = forms.ChoiceField(choices=BLANK_CHOICE_DASH + list(Building.objects.values_list('id', 'name')), required=False)
Upvotes: 3
Reputation: 1415
load crispy_forms_tags top of the template.
{% load crispy_forms_tags %}
<form method="POST" class="form" action="" method="get">
{% csrf_token %}
{{ form|crispy}}
<br>
<button type="submit" class="btn btn-primary btn-primary">Search</button>
</form>
Upvotes: 0