在Django表单中,我如何使字段只读(或禁用)?

当使用表单创建新条目时,应该启用所有字段——但当记录处于更新模式时,某些字段需要为只读。

例如,当创建一个新的Item模型时,所有字段都必须是可编辑的,但是在更新记录时,是否有一种方法禁用sku字段,使其可见,但不能编辑?

class Item(models.Model):
    sku = models.CharField(max_length=50)
    description = models.CharField(max_length=200)
    added_by = models.ForeignKey(User)


class ItemForm(ModelForm):
    class Meta:
        model = Item
        exclude = ('added_by')

def new_item_view(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        # Validate and save
    else:
            form = ItemForm()
    # Render the view

ItemForm类可以重用吗?ItemForm或Item模型类需要做哪些更改?我是否需要编写另一个类“ItemUpdateForm”来更新项目?

def update_item_view(request):
    if request.method == 'POST':
        form = ItemUpdateForm(request.POST)
        # Validate and save
    else:
        form = ItemUpdateForm()

当前回答

基于@paeduardo的回答(这是多余的),你可以在表单类初始化器中禁用一个字段:

class RecordForm(ModelForm):

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

其他回答

我认为你最好的选择是在你的模板中包含readonly属性,在<span>或<p>中呈现,而不是在表单中包含它,如果它是readonly的话。

表单用于收集数据,而不是显示数据。也就是说,在只读小部件中显示和清除POST数据的选项是很好的解决方案。

对于Django 1.2+,你可以像这样重写字段:

sku = forms.CharField(widget = forms.TextInput(attrs={'readonly':'readonly'}))

从禁用字段mixin开始:

class ModelAllDisabledFormMixin(forms.ModelForm):
    def __init__(self, *args, **kwargs):
    '''
    This mixin to ModelForm disables all fields. Useful to have detail view based on model
    '''
    super().__init__(*args, **kwargs)
    form_fields = self.fields
    for key in form_fields.keys():
        form_fields[key].disabled = True

然后:

class MyModelAllDisabledForm(ModelAllDisabledFormMixin, forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'

准备视图:

class MyModelDetailView(LoginRequiredMixin, UpdateView):
    model = MyModel
    template_name = 'my_model_detail.html'
    form_class = MyModelAllDisabledForm

把它放在my_model_detail.html模板中:

  <div class="form">
     <form method="POST" enctype="multipart/form-data">
         {% csrf_token %}
         {{ form | crispy }}
     </form>
  </div>

您将获得与更新视图中相同的表单,但禁用了所有字段。

另外两种(类似的)方法和一个通用的例子:

1)第一种方法-删除save()方法中的字段,例如(未测试;)):

def save(self, *args, **kwargs):
    for fname in self.readonly_fields:
        if fname in self.cleaned_data:
            del self.cleaned_data[fname]
    return super(<form-name>, self).save(*args,**kwargs)

2)第二种方法-在clean方法中将字段重置为初始值:

def clean_<fieldname>(self):
    return self.initial[<fieldname>] # or getattr(self.instance, fieldname)

基于第二种方法,我将其概括为:

from functools                 import partial

class <Form-name>(...):

    def __init__(self, ...):
        ...
        super(<Form-name>, self).__init__(*args, **kwargs)
        ...
        for i, (fname, field) in enumerate(self.fields.iteritems()):
            if fname in self.readonly_fields:
                field.widget.attrs['readonly'] = "readonly"
                field.required = False
                # set clean method to reset value back
                clean_method_name = "clean_%s" % fname
                assert clean_method_name not in dir(self)
                setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))

    def _clean_for_readonly_field(self, fname):
        """ will reset value to initial - nothing will be changed 
            needs to be added dynamically - partial, see init_fields
        """
        return self.initial[fname] # or getattr(self.instance, fieldname)

在小部件上设置readonly只会使浏览器中的输入变为只读。添加一个返回实例的clean_sku。Sku确保字段值不会在表单级别上改变。

def clean_sku(self):
    if self.instance: 
        return self.instance.sku
    else: 
        return self.fields['sku']

这样您就可以使用model的(未修改的保存)并避免获得字段所需的错误。