11

I use this snippet to show several fields in my admin backend as readonly, but as noticed in the comments, it does not work on stackedinline/tabularinline. Is there any other way to achieve this? I have a list of objects attached to a model and just want to show it in the model's details view without the possibility to change values.

schneck
  • 10,556
  • 11
  • 49
  • 74

3 Answers3

19

If you are running Django 1.3 or later; there's an attribute named ModelAdmin.readonly_fields which you could use.

InlineModelAdmin inherits from ModelAdmin, so you should be able to use it from your inline subclass.

2

I've encountered the same problem today. Here is my solution. This is example of read-only field for the ForeignKey value:

class MySelect(forms.Select):
    def render(self, name, value, attrs=None, choices=()):
        s = Site.objects.get(id=value)
        return s.name

class UserProfileInlineForm(forms.ModelForm):
    site = forms.ModelChoiceField(queryset=Site.objects.all(), widget=MySelect)

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    form = UserProfileInlineForm
Ivan Virabyan
  • 1,666
  • 2
  • 19
  • 25
0

As is the case with JQuery, it seems you can achieve this by changing an attr called "disabled" (works in my Safari, OK we're now in 2013 :-) ). Example below:

def get_form(self, request, obj=None, **kwargs):
        result = super(<your ModelAdmin class here>, self).get_form(request, obj=obj, **kwargs)
        result.base_fields[<the select field you want to disable>].widget.attrs['disabled'] = 'disabled'
        return result
lai
  • 1,163
  • 10
  • 15