2011-02-09 29 views
11

我有这样一个模型:我怎样才能在一个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 

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

什么是真正的方式来完成我后?

回答

33

步骤1:禁用前端部件

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

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

你可以注入通过任意的HTML键值对小工具attrs属性:

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

步骤2:确保该字段上后端

重写为您的字段的清洁方法有效地禁用POST输入的这样不管(有人可以假一POST,编辑原始HTML等)你会得到已经存在的字段值。

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

只读属性是它。谢谢! – jammon 2011-02-09 15:05:00

+2

“self.instance.status”的诀窍非常好。 – jammon 2011-02-09 15:05:55

5

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

像这样

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

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

Reference Here

4

只需定制控件实例状态字段:

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 

见:Django Documentation

2

从Django中1.9:

self.fields['whatever'].disabled = True