开发者

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 co开发者_StackOverflow社区de 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.


fields take initial values


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'
    )


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")


Try the number:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜