How to make a Django Model form Readonly?

给你一囗甜甜゛ 提交于 2019-11-28 01:19:01

问题


I have a django form name "SampleForm". Which i use to take input from user. Now i want to use same form to show this information to user on a different page. But form is editable I want to make the form read only. Is there any way to make whole form Readonly ?


回答1:


pseudo-code (not tested):

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



回答2:


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

Just this should make the entire form readonly whenever an instance is available for the form.




回答3:


Working Code

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


来源:https://stackoverflow.com/questions/32248575/how-to-make-a-django-model-form-readonly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!