Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying default value for django hidden form field - bone DRY?

So let's say at the last minute (in the view) I decide I want to specify a default for a field and make it hidden, like so:

form.fields['coconut'] = forms.ModelChoiceField(label="", widget=forms.HiddenInput(), queryset=swallow.coconuts.all(), initial=some_particular_coconut)

My question is this: Do I really need to specify queryset here? I mean, I already know, from initial, exactly which coconut I'm talking about. Why do I also need to specify that the universe of available coconuts is the set of coconuts which this particular swallow carried (by the husk)?

Is there a way I can refrain from specifying queryset? Simply omitting causes django to raise TypeError.

If indeed it is required, isn't this a bit damp?

like image 883
jMyles Avatar asked Dec 13 '22 17:12

jMyles


1 Answers

I think is good that stackoverflow answers point to the 'right' way to do things, but increasingly the original question goes unanswered because the user was trying to do the wrong thing. So to answer this question directly this is what you can do:

form.fields['coconut'] = forms.ModelChoiceField(label="", widget=forms.HiddenInput(attrs={'value':some_particular_coconut}), queryset=swallow.coconuts.all())

Notice the named argument passed to HiddenInput, its super hackish but its a direct answer to the original question.

like image 109
Guillermo Siliceo Trueba Avatar answered Dec 15 '22 07:12

Guillermo Siliceo Trueba