Change a Django form field to a hidden field

StackOverflow

I have a Django form with a RegexField, which is very similar to a normal text input field.

In my view, under certain conditions I want to hide it from the user, and trying to keep the form as similar as possible. What"s the best way to turn this field into a HiddenInput field?

I know I can set attributes on the field with:

form["fieldname"].field.widget.attr["readonly"] = "readonly"

And I can set the desired initial value with:

form.initial["fieldname"] = "mydesiredvalue"

However, that won"t change the form of the widget.

What"s the best / most "django-y" / least "hacky" way to make this field a <input type="hidden"> field?

Answer rating: 231

This may also be useful: {{ form.field.as_hidden }}

Answer rating: 193

If you have a custom template and view you may exclude the field and use {{ modelform.instance.field }} to get the value.

also you may prefer to use in the view:

form.fields["field_name"].widget = forms.HiddenInput()

but I"m not sure it will protect save method on post.

Hope it helps.

Answer rating: 70

an option that worked for me, define the field in the original form as:

forms.CharField(widget = forms.HiddenInput(), required = False)

then when you override it in the new Class it will keep it"s place.





Get Solution for free from DataCamp guru