Django set default form values
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC C Schuberts Piano Sonata No 13 D
--
Chapters
00:00 Question
01:10 Accepted answer (Score 492)
01:36 Answer 2 (Score 55)
01:50 Answer 3 (Score 25)
02:08 Answer 4 (Score 18)
02:58 Thank you
--
Full question
https://stackoverflow.com/questions/6042...
Accepted answer links:
[Form.initial]: https://docs.djangoproject.com/en/dev/re...
[here]: https://djangobook.com/tying-forms-views...
Answer 3 links:
https://docs.djangoproject.com/en/1.10/t...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #djangomodels #djangoforms
#avk47
--
Track title: CC C Schuberts Piano Sonata No 13 D
--
Chapters
00:00 Question
01:10 Accepted answer (Score 492)
01:36 Answer 2 (Score 55)
01:50 Answer 3 (Score 25)
02:08 Answer 4 (Score 18)
02:58 Thank you
--
Full question
https://stackoverflow.com/questions/6042...
Accepted answer links:
[Form.initial]: https://docs.djangoproject.com/en/dev/re...
[here]: https://djangobook.com/tying-forms-views...
Answer 3 links:
https://docs.djangoproject.com/en/1.10/t...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #djangomodels #djangoforms
#avk47
ACCEPTED ANSWER
Score 510
You can use Form.initial, which is explained here.
You have two options either populate the value when calling form constructor:
form = JournalForm(initial={'tank': 123})
or set the value in the form definition:
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
ANSWER 2
Score 60
Other solution: Set initial after creating the form:
form.fields['tank'].initial = 123
ANSWER 3
Score 25
If you are creating modelform from POST values initial can be assigned this way:
form = SomeModelForm(request.POST, initial={"option": "10"})
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values
ANSWER 4
Score 21
I had this other solution (I'm posting it in case someone else as me is using the following method from the model):
class onlyUserIsActiveField(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
self.fields['is_active'].initial = False
class Meta:
model = User
fields = ['is_active']
labels = {'is_active': 'Is Active'}
widgets = {
'is_active': forms.CheckboxInput( attrs={
'class': 'form-control bootstrap-switch',
'data-size': 'mini',
'data-on-color': 'success',
'data-on-text': 'Active',
'data-off-color': 'danger',
'data-off-text': 'Inactive',
'name': 'is_active',
})
}
The initial is definded on the __init__ function as self.fields['is_active'].initial = False