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

11,931

Solution 1

The problem is that you're trying to set up a hidden ModelChoiceField. In order to have a Choice (dropdown, traditionally) it needs to know its Choices - this is why you give a queryset.

But you're not trying to give the user a choice, right? It's a hidden input, and you're setting it from the server (so it gets POSTed back, presumably).

My suggestion is to try to find a way around using the hidden input at all. I find them a bit hacky. But otherwise, why not just specify a text field with some_particular_coconut.id, and hide that? The model's only wrapping that id anyway.

Solution 2

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.

Share:
11,931

Related videos on Youtube

jMyles
Author by

jMyles

I am the Chief Chocobo Breeder (and one of the founding members) of the slashRoot Collective. We're an education and innovation dojo in New Paltz, NY. For a while, we operated a public coffee shop that many of you came up from NYC to visit. :-) We'll probably open another space again when we get around to it.

Updated on May 12, 2022

Comments

  • jMyles
    jMyles almost 2 years

    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?

  • jMyles
    jMyles over 13 years
    But this still doesn't make DRY sense - if it has an integer, and the field is a foreign key, what's the difference in the end? In other words, it always expects an integer as the field value where the foreign key has an integer PK.
  • jMyles
    jMyles over 13 years
    django knows it's a ForeignKey from the model. On the other end, I'm just doing EuropeanSwallowForm(request.POST). Coconut has a ForeignKey to EuropeanSwallow. In the handler view, django has no idea that I ever made the field hidden in the interim.