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.
- Django – inlineformset_factory with more than one ForeignKey
- Yuglify compressor can't find binary from package installed through npm
- Django formset set current user
- Maintain SQL operator precedence when constructing Q objects in Django
- Error loading sample django-bootstrap3 template
- How can I tell Django templates not to parse a block containing code that looks like template tags?
- What's the difference between override_settings and modify_settings in Django?
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'
)
- Celery beat not picking up periodic tasks
- Django template counter in nested loops
- Create a Session in Django
- Render one queryset into 2 div columns (django template)
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")
- Using Django's m2m_changed to modify what is being saved pre_add
- Multiple User Types For Auth in Django
-2👍
Try the number:
state = forms.TypedChoiceField(choices = formfields.State, default = 2 )
- Django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
- How do I call a model method in django ModelAdmin fieldsets?
- Schedule number of web dynos by time of day
Source:stackexchange.com