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

So, let's say, at the last minute (in the view), I decided that I want to specify the default value for the field and make it hidden, for example:

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 the request here? I mean, I already know, from the initial, it’s the coconut that I’m talking about. Why do I also need to point out that the universe of affordable coconuts is the set of coconuts that this particular swallow wears (huskily)?

Is there a way that I can refrain from specifying a set of queries? A simple drop causes django to raise a TypeError.

If it's really needed, isn't it a little wet?

+3
source share
3 answers

The problem is that you are trying to set up a hidden ModelChoiceField. To have a choice (a drop-down list, traditionally), he needs to know his choice - that’s why you give a request.

But you are not trying to give the user a choice, are you? This is hidden input, and you install it from the server (so that it returns POSTED, presumably).

My suggestion is to try and find a way to use hidden input in general. I find them a bit hacked. But otherwise, why not just specify a text box with some_particular_coconut.idand hide it? The model only wraps this identifier.

+1
source

, , stackoverflow "" -, , . , , , :

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

, HiddenInput, , .

+8

, django , , django . , , . , form.fields['coconut'].initial = some_particular_coconut .py?

If you find that you really need to send the identifier anyway (you don't need to re-inflate the object at the end), why not send it to the char field?

0
source

Source: https://habr.com/ru/post/1780157/


All Articles