Python 如何禁用 django 表单中的模型字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4945802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:17:33  来源:igfitidea点击:

How can I disable a model field in a django form

pythondjangodjango-forms

提问by jammon

I have a model like this:

我有一个这样的模型:

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?

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

采纳答案by Yuji 'Tomita' Tomita

Step 1: Disable the frontend widget

第 1 步:禁用前端小部件

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

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

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

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

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

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

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

Step 2: Ensure the field is effectively disabled on backend

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

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.

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

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

回答by darren

Have you tried using the exclude function?

您是否尝试过使用排除功能?

something like this

像这样的东西

class PartialAuthorForm(ModelForm):
class Meta:
    model = Author
    fields = ('name', 'title')

class PartialAuthorForm(ModelForm):
class Meta:
    model = Author
    exclude = ('birth_date',)

Reference Here

参考这里

回答by T. Christiansen

Just customize the widget instance for the status field:

只需为状态字段自定义小部件实例:

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):
    status =  forms.CharField(widget=forms.TextInput(attrs={'readonly':'True'}))

    class Meta:
        model = models.MyModel

see: Django Documentation

请参阅:Django 文档

回答by xleon

From django 1.9:

从 Django 1.9 开始:

from django.forms import Textarea

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {'my_field_in_my_model': Textarea(attrs={'cols':80,'rows':1}),}             

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['my_field_in_my_model'].disabled = True

回答by Rishabh

There is a very easy way of doing it:

有一个非常简单的方法:

class GenerateCertificate(models.Model):

    field_name = models.CharField(
        max_length=15,
        editable=False)
    def __unicode__(self):
        return unicode(self.field_name)

The editable=Falsewill make the field disabled for editing.

editable=False会为编辑禁止的领域。