Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value for dropdown in django forms

I am unable to set default value for a dropdown while loading forms.

Here is the code

state = forms.TypedChoiceField(choices = formfields.State)

State = (
         ('QC_APPROVED','QC_APPROVED'),
         ('REVERT','REVERT'),
         ('FIXED','FIXED'),
        )

If I want to make the default state as FIXED. I am writing this code

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

If I execute the above code I am getting the below error.

Exception Value: __init__() got an unexpected keyword argument 'default'

Can some one help on this?

like image 994
vkrams Avatar asked May 03 '11 04:05

vkrams


2 Answers

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

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

like image 182
JackLeo Avatar answered Oct 05 '22 12:10

JackLeo


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.

like image 32
Nic Scozzaro Avatar answered Oct 05 '22 10:10

Nic Scozzaro