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 ?
François Constant
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
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.
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