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

查看:77
本文介绍了如何禁用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

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

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

But the user can still change that field.

完成我以后的事情?

推荐答案

使用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

或禁用

http://www.w3.org/TR/html401/interact/forms.html#adef-禁用

您可以通过小部件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

这篇文章有一个很好的技巧来确保你的表单不能接受新值:

This post has a nice trick for ensuring your form can't accept new values: In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

覆盖您的领域的干净方法,以便不管POST输入(有人可以ke,一个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 value you started with.

def clean_status(self):
    return self.instance.status

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

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