The Python Oracle

Change a Django form field to a hidden field

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 Change A Django Form Field To A Hidden Field
00:42 Accepted Answer Score 223
01:08 Answer 2 Score 55
01:56 Answer 3 Score 275
02:06 Answer 4 Score 91
02:19 Thank you

--

Full question
https://stackoverflow.com/questions/6862...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #html #django #djangoforms

#avk47



ANSWER 1

Score 275


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




ACCEPTED ANSWER

Score 223


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:

field = form.fields['field_name']
field.widget = field.hidden_widget()

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

edit: field with multiple values don't supports HiddenInput as input type, so use default hidden input widget for this field instead.




ANSWER 3

Score 91


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.




ANSWER 4

Score 55


Firstly, if you don't want the user to modify the data, then it seems cleaner to simply exclude the field. Including it as a hidden field just adds more data to send over the wire and invites a malicious user to modify it when you don't want them to. If you do have a good reason to include the field but hide it, you can pass a keyword arg to the modelform's constructor. Something like this perhaps:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
    def __init__(self, *args, **kwargs):
        from django.forms.widgets import HiddenInput
        hide_condition = kwargs.pop('hide_condition',None)
        super(MyModelForm, self).__init__(*args, **kwargs)
        if hide_condition:
            self.fields['fieldname'].widget = HiddenInput()
            # or alternately:  del self.fields['fieldname']  to remove it from the form altogether.

Then in your view:

form = MyModelForm(hide_condition=True)

I prefer this approach to modifying the modelform's internals in the view, but it's a matter of taste.