Gill Bates
Gill Bates

Reputation: 15177

Why does MultipleHiddenInput render only if there is initial data? (Django)

class MyForm(forms.Form):
    my_hidden_field = forms.MultipleChoiceField(
            widget=forms.MultipleHiddenInput,
            choices=(...))


def my_view(request):
  form = MyForm(initial={
       'my_hidden_field': MyModel.objects.values_list('id', flat=True)})

If I remove the initial argument from the MyForm call, my_hidden_field is not rendered in HTML. But if I remove the MultipleHiddenInput widget, then it is rendered.

How do I make it render?

Upvotes: 3

Views: 1769

Answers (1)

jbub
jbub

Reputation: 2665

This is just the way it is implemented. If you do not pass any values, then there is nothing to render, because it is hidden anyway, so the user can't alter the values.

You can see the implementation here: https://github.com/django/django/blob/master/django/forms/widgets.py#L316

If you need to render it, you will need to pass some initial data to it, but it is strange, what is the use case exactly ?

Upvotes: 3

Related Questions