Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly View for 10 Django Class Based Views

I have 10 Django Class Based Views and I want to display them read-only to the user.

I want the whole form to be read-only, not only some values. Submitting the form should be disabled on the client (HTML) and a second time on the server (POST not allowed).

Is there a MixIn or an other simple solution?

like image 437
guettli Avatar asked Dec 24 '22 06:12

guettli


1 Answers

Here's a mixin that does two simple things:

  • Sets html attributes for all fields in form for disabled andreadonly.

  • Overrides the form_valid method of your CBV so that no model saving ever happens; instead, the template is rendered (just as if there was no submitted data). The user, this way, does not cause any action if they submitted the form.

Form field errors may appear next to disabled fields if you are rendering the full form in your template; solve this by either erasing the form's error dictionary or by rendering each field individually without errors.

from django.views.generic.edit import FormMixin, ModelFormMixin

class ReadOnlyModelFormMixin(ModelFormMixin):

    def get_form(self, form_class=None):

        form = super(ReadOnlyModelFormMixin, self).get_form()

        for field in form.fields:
            # Set html attributes as needed for all fields
            form.fields[field].widget.attrs['readonly'] = 'readonly'          
            form.fields[field].widget.attrs['disabled'] = 'disabled'

        return form

    def form_valid(self, form): 
        """
        Called when form is submitted and form.is_valid()
        """
        return self.form_invalid(form)

Extending this concept for a non-model FormView is pretty simple; inherit from class FormMixin instead. :)

like image 175
Ian Price Avatar answered Dec 28 '22 07:12

Ian Price