Ayub Khan
Ayub Khan

Reputation: 896

How to make a Django Model form Readonly?

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 ?

Upvotes: 7

Views: 6785

Answers (4)

PapaSmurf
PapaSmurf

Reputation: 2475

in Django 4.1, override the get_context_data with

def get_context_data(self, *, object_list=None, **kwargs):
    context = super().get_context_data(object_list=None, **kwargs)

    form = AddressForm(instance=self.get_object())
    for name, field in form.fields.items():
        field.disabled = True
    context["form"] = form
    return context

Upvotes: -1

François Constant
François Constant

Reputation: 5496

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

Upvotes: 15

Ayub Khan
Ayub Khan

Reputation: 896

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

Upvotes: 0

Animesh Sharma
Animesh Sharma

Reputation: 3386

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.

Upvotes: 1

Related Questions