将 Django 表单字段更改为隐藏字段 [英] Change a Django form field to a hidden field
问题描述
我有一个带有 RegexField
的 Django 表单,它与普通的文本输入字段非常相似.
I have a Django form with a RegexField
, which is very similar to a normal text input field.
在我看来,在某些情况下,我想对用户隐藏它,并尽量保持表单的相似性.将此字段转换为 HiddenInput
字段的最佳方法是什么?
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.
使该字段成为 <input type="hidden">
字段的最佳/最django-y"/最不hacky"的方法是什么?
What's the best / most "django-y" / least "hacky" way to make this field a <input type="hidden">
field?
推荐答案
如果您有自定义模板和视图,您可以排除该字段并使用 {{ modelform.instance.field }}
获得价值.
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.
希望有帮助.
这篇关于将 Django 表单字段更改为隐藏字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!