Reputation: 10827
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.
Upvotes: 11
Views: 15148
Reputation: 1171
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
Upvotes: 0
Reputation:
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.
Upvotes: 19
Reputation: 1686
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
Upvotes: 2