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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With