Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
Gill Bates Avatar asked Aug 11 '26 22:08

Gill Bates


1 Answers

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 ?

like image 140
jbub Avatar answered Aug 13 '26 13:08

jbub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!