将django表单字段更改为隐藏字段 [英] Change a django form field to a hidden field

查看:885
本文介绍了将django表单字段更改为隐藏字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django表单,一个 RegexField (与普通文本输入字段非常相似)。在我看来,在某些条件下,我想把这个隐藏起来,并试图保持表单尽可能的相似。

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 this from the user, and trying to keep the form as similar as possible.

打开这个字段的最好方法是什么成为 HiddenInput 字段?我知道我可以使用 form ['fieldname']设置字段的属性field.widget.attr ['readonly'] ='readonly',我可以设置所需的初始值与 form.initial ['fieldname'] ='mydesiredvalue'。但是,这不会改变窗口小部件的形式。

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.

什么是最佳/最django-y /最简单的hacky方式使这个字段为$ code> < input type =hidden field?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆