The Python Oracle

Change a Django form field to a hidden field

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC P Beethoven - Piano Sonata No 2 in A

--

Chapters
00:00 Question
00:58 Accepted answer (Score 220)
01:35 Answer 2 (Score 258)
01:49 Answer 3 (Score 85)
02:10 Answer 4 (Score 54)
03:09 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.