Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 971
Ayub Khan Avatar asked Aug 27 '15 11:08

Ayub Khan


People also ask

How do you make a field Uneditable in Django?

The disabled boolean argument, when set to True , disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.

What is formset in Django?

A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let's say you have the following form: >>> from django import forms >>> class ArticleForm(forms.

What is widget in Django?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .


1 Answers

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
like image 181
François Constant Avatar answered Sep 23 '22 11:09

François Constant