Change a Django form field to a hidden field

后端 未结 7 2097
故里飘歌
故里飘歌 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 20:51

    You can just use css :

    #id_fieldname, label[for="id_fieldname"] {
      position: absolute;
      display: none
    }

    This will make the field and its label invisible.

    0 讨论(0)
  • 2020-12-22 20:57

    If you want the field to always be hidden, use the following:

    class MyForm(forms.Form):
        hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")
    
    0 讨论(0)
  • 2020-12-22 21:00

    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.

    0 讨论(0)
  • 2020-12-22 21:01

    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.

    0 讨论(0)
  • 2020-12-22 21:01

    For normal form you can do

    class MyModelForm(forms.ModelForm):
        slug = forms.CharField(widget=forms.HiddenInput())
    

    If you have model form you can do the following

    class MyModelForm(forms.ModelForm):
        class Meta:
            model = TagStatus
            fields = ('slug', 'ext')
            widgets = {'slug': forms.HiddenInput()}
    

    You can also override __init__ method

    class Myform(forms.Form):
        def __init__(self, *args, **kwargs):
            super(Myform, self).__init__(*args, **kwargs)
            self.fields['slug'].widget = forms.HiddenInput()
    
    0 讨论(0)
  • 2020-12-22 21:14

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

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