Change a Django form field to a hidden field

后端 未结 7 2098
故里飘歌
故里飘歌 2020-12-22 20:21

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

相关标签:
7条回答
  • 2020-12-22 21:14

    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.

    0 讨论(0)
提交回复
热议问题