[Fixed]-Set default value for dropdown in django forms

21👍

state = forms.TypedChoiceField(choices=formfields.State, initial='FIXED')

As shown in documentation: http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial

7👍

I came across this thread while looking for how to set the initial “selected” state of a Django form for a foreign key field, so I just wanted to add that you do this as follows:

models.py:

class Thread(NamedModel):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    title = models.CharField(max_length=70, blank=False)

forms.py:

class ThreadForm(forms.ModelForm):
    class Meta:
        model = Thread
        fields = ['topic', 'title']

views.py:

def createThread(request, topic_title):
    topic = Topic.getTopic(topic_title)
    threadForm = ThreadForm(initial={'topic': topic.id})
...

The key is setting initial={'topic': topic.id} which is not well documented in my opinion.

3👍

fields take initial values

👤dting

1👍

state = forms.TypedChoiceField(choices=formfields.State, initial='FIXED')

title = forms.CharField(widget=forms.Select(choices=formfields.State) , initial='FIXED')

toppings = forms.ChoiceField(
        widget=forms.Select(attrs={'class':"hhhhhhhh"}),
        choices = formfields.State,
        initial='FIXED'
    )

1👍

If the other solutions dont work for you,Try this:

It turns out that ModelChoiceField has an attribute called empty_label.With empty _label you can enter a default value for the user to see.
Example: In forms.py

Class CreateForm(forms.ModelForm):
      category = forms.ModelChoiceField(empty_label="Choose Category")

-2👍

Try the number:

state = forms.TypedChoiceField(choices = formfields.State, default = 2 )

Leave a comment