如何使Django模型形成Readonly?

时间:2015-08-27 11:48:12

标签: django django-forms django-views

我有一个django表单名称" SampleForm"。我用来从用户那里获取输入。现在我想使用相同的表单在不同的页面上向用户显示此信息。但表单是可编辑的我想让表单只读。有没有办法让整个形式Readonly?

3 个答案:

答案 0 :(得分:8)

伪代码(未测试):

class ReadOnlyFormMixin(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ReadOnlyFormMixin, self).__init__(*args, **kwargs)
        for key in self.fields.keys():
            self.fields[key].widget.attrs['readonly'] = True

    def save(self, *args, **kwargs):
        # do not do anything
        pass

class SampleReadOnlyForm(ReadOnlyFormMixin, SampleForm):
    pass

答案 1 :(得分:0)

class SampleForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(SampleForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            for field in self.fields.keys():
                self.fields[field].widget.attrs['readonly'] = True

只要表格的实例可用,就应该使整个表单只读。

答案 2 :(得分:0)

工作代码

class ReadOnlySampleForm(SampleForm):
def __init__(self, *args, **kwargs):
    super(SampleForm, self).__init__(*args, **kwargs)
    for key in self.fields.keys():
        self.fields[key].widget.attrs['readonly'] = True