How to change a Django form field to a hidden field

0 votes

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 way to make this field a <input type="hidden"> field?

Jul 29, 2020 in Python by kartik
• 37,520 points
13,657 views

1 answer to this question.

0 votes

Hello @kartik,

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!!

Thank You!!

answered Jul 29, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How to update date automatically after a value change in django?

Hello @kartik, Only change your pub_date if published has ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,840 points
9,675 views
0 votes
1 answer
0 votes
1 answer

How do I make a field readonly (or disabled) so that it cannot be edited in Django form?

Hello @kartik, Setting readonly on a widget only makes the ...READ MORE

answered Aug 6, 2020 in Python by Niroj
• 82,840 points
16,611 views
0 votes
1 answer

How to change one character in a string in Python?

Python strings are immutable, you change them ...READ MORE

answered Dec 4, 2018 in Python by Nymeria
• 3,560 points
1,277 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,451 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,564 views
0 votes
1 answer

How to PATCH a single field using Django Rest Framework?

Hello @kartik, Serializers allow partial updates by specifying partial=True when initializing ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,840 points
15,393 views
0 votes
1 answer

How to get value from form field in django framework?

Hello @kartik, Using a form in a view can ...READ MORE

answered Jun 30, 2020 in Python by Niroj
• 82,840 points
9,134 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP