Readonly fields in the django admin/inline

后端 未结 3 941
逝去的感伤
逝去的感伤 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
    

提交回复
热议问题