Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial value in django form dropdown is not empty?

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?

like image 850
Ilya Bibik Avatar asked Nov 16 '25 06:11

Ilya Bibik


1 Answers

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)
like image 169
Ilya Bibik Avatar answered Nov 18 '25 19:11

Ilya Bibik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!