简体   繁体   English

使django只读字段在管理员上可见

[英]Make a django readonly field visible on the admin

I'm developing a Django project in which I want to allow users to edit a specific field only on add_view. 我正在开发一个Django项目,其中我希望允许用户仅在add_view上编辑特定字段。 So I've overridden the change_view method on the admin.py so it can set my readonly_fields there. 因此,我在admin.py上覆盖了change_view方法,以便可以在此处设置我的readonly_fields。 However Django won't display readonly_fields. 但是Django不会显示readonly_fields。

It seems really wird for me that a readonly field is not displayed. 对我来说似乎真的很奇怪,没有显示只读字段。 I mean, if it's readonly, where is the part of it where it says read? 我的意思是,如果它是只读的,它说读的部分在哪里? It should be readable (only), and not ediable. 它应该是可读的(仅),而不是可编辑的。 If I wanted to hide it, there should be an option called hidden_fields or something. 如果我想隐藏它,应该有一个名为hidden_​​fields之类的选项。 Don't you guys agree? 你们不同意吗?

I wonder if is there any straighforward way of make readonly_fields visible on my admin, but not ediable. 我想知道是否有任何让我的管理员可以看到readonly_fields的简便方法,但不是可编辑的。

my admin.py looks like this: 我的admin.py看起来像这样:

from django.contrib import admin from core.models import Box 从django.contrib从core.models导入框导入管理员

class BoxAdmin(admin.ModelAdmin):
    def change_view(self, request, object_id, form_url='', extra_context=None):
        self.readonly_fields = ('colour',)
        return super(BoxAdmin, self).change_view(request, object_id)

    def add_view(self, request, form_url='', extra_context=None):
        self.readonly_fields = []
        return super(BoxAdmin, self).add_view(request, extra_context=c)

Instead of setting self.readonly_fields , you should override get_readonly_fields . 代替设置self.readonly_fields ,您应该覆盖get_readonly_fields

def get_readonly_fields(request, obj=None):
    if obj is None:  # add form
        return []
    else:
        return ['colour']

I figured out the problem and it happens to be with my lack of attention. 我发现了问题,而恰好是由于我缺乏注意力。 Actually Django does display readonly_fields but I couldn't see it because they are displayed on the bottom of the form. 实际上Django确实显示了readonly_fields,但我看不到它,因为它们显示在表单的底部。 When you don't set the ModelForm.fields attribute they go to the bottom, which was pretty much my case. 当您不设置ModelForm.fields属性时,它们将移至最底下,这在我的情况下几乎是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM