﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35544	Readonly Widget Template	Sven R. Kunze	nobody	"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
- https://forum.djangoproject.com/t/feature-request-discussion-custom-rendering-for-readonly-fields-in-admin/32009
- https://code.djangoproject.com/ticket/30577
- https://stackoverflow.com/questions/14832739/django-admin-how-to-display-widget-on-readonly-field"	New feature	closed	Forms	dev	Normal	duplicate	widget readonly admin		Unreviewed	0	0	0	0	0	0
