Set default value for dropdown in django forms Set default value for dropdown in django forms django django

Set default value for dropdown in django forms


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

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


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.