Opened 5 months ago

Last modified 5 months ago

#35544 closed New feature

Readonly Widget Template — at Version 1

Reported by: Sven R. Kunze Owned by: nobody
Component: Forms Version: dev
Severity: Normal Keywords: widget readonly admin
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Sven R. Kunze)

Hi everyone, recently I came across the following issue which already saw some attention on StackOverflow.

All solutions I've seen so far circumvent a limitation of Django widgets: these are not really aware of a readonly situation. There are specialized readonly widgets for certain situations however there is no generic path for a Widget designer to specify how a readonly version of a widget would look like. Additionally there's is no easy way to override that behavior (see my last response on the SO issue) in admin.

Admin, however, is just part of Django, so I would rather see a more general approach here. Therefore, I propose the following.

Couldn't we define a ReadonlyAwareInput that allows the following:

class ReadonlyAwareInput(Input):
    template_name = "django/forms/widgets/input.html"
    readonly_template_name = "django/forms/widgets/readonly_input.html"  # new

    def __init__(self, attrs=None, is_readonly=False):
        self.is_readonly= is_readonly
        if attrs is not None:
            attrs = attrs.copy()
            self.input_type = attrs.pop("type", self.input_type)
        super().__init__(attrs)

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context["widget"]["type"] = self.input_type
        context["is_readonly"] = self.is_readonly  # new for usage in template as well
        return context

    def render(self, name, value, attrs=None, renderer=None):
        """Render the widget as an HTML string."""
        context = self.get_context(name, value, attrs)
        if self.is_readonly:
            return self._render(self.readonly_template_name, context, renderer)
        return self._render(self.template_name, context, renderer)


class PreviewFileInput(ReadonlyAwareInput):
    template_name = "django/forms/widgets/preview_file.html"
    readonly_template_name = "django/forms/widgets/readonly_preview_file.html"  # override new readonly_template_name

    def get_context(self, name, value, attrs):
        .... # as usual

I am not sure if Admin's display_for_field could be replaced completely by such a system. I my gut feeling is that it would allow customizing a lot more.

What do you think about that solution?

Also see

Change History (1)

comment:1 by Sven R. Kunze, 5 months ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top