Readonly fields in the django admin/inline

后端 未结 3 940
逝去的感伤
逝去的感伤 2021-02-08 09:24

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 wa

相关标签:
3条回答
  • 2021-02-08 10:06

    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
    
    0 讨论(0)
  • 2021-02-08 10:22

    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.

    0 讨论(0)
  • 2021-02-08 10:23

    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
    
    0 讨论(0)
提交回复
热议问题