如何禁用 Django 表单中的模型字段 [英] How can I disable a model field in a django form

查看:27
本文介绍了如何禁用 Django 表单中的模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的模型:

class MyModel(models.Model):
    REGULAR = 1
    PREMIUM = 2
    STATUS_CHOICES = ((REGULAR, "regular"), (PREMIUM, "premium"))
    name = models.CharField(max_length=30)
    status = models.IntegerField(choices = STATUS_CHOICES, default = REGULAR)

class MyForm(forms.ModelForm):
    class Meta:
        model = models.MyModel

在视图中,我初始化一个字段并尝试使其不可

In a view I initialize one field and try to make it non-editable:

myform = MyForm(initial = {'status': requested_status})
myform.fields['status'].editable = False

但用户仍然可以更改该字段.

But the user can still change that field.

实现我所追求的真正方法是什么?

What's the real way to accomplish what I'm after?

推荐答案

第一步:禁用前端小部件

使用 HTML readonly 属性:
http://www.w3schools.com/tags/att_input_readonly.asp

Use the HTML readonly attribute:
http://www.w3schools.com/tags/att_input_readonly.asp

disabled 属性:
http://www.w3.org/TR/html401/interact/forms.html#adef-disabled

您可以通过小部件 attrs 属性注入任意 HTML 键值对:

You can inject arbitrary HTML key value pairs via the widget attrs property:

myform.fields['status'].widget.attrs['readonly'] = True # text input
myform.fields['status'].widget.attrs['disabled'] = True # radio / checkbox

第 2 步:确保在后端有效禁用该字段

覆盖您的字段的 clean 方法,以便无论 POST 输入如何(有人可以伪造 POST、编辑原始 HTML 等),您都会获得已存在的字段值.

Override your clean method for your field so that regardless of POST input (somebody can fake a POST, edit the raw HTML, etc.) you get the field value that already exists.

def clean_status(self):
    # when field is cleaned, we always return the existing model field.
    return self.instance.status

这篇关于如何禁用 Django 表单中的模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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