How to add readonly inline on django admin

[亡魂溺海] 提交于 2021-02-05 19:06:42

问题


I am using django 1.4 and I have a many2many field, so when creating the admin site I wanted to add this field as an inline, here is some code:

class SummaryInline(admin.TabularInline):
    model = ParserError.summaries.through


class MyClassAdmin(admin.ModelAdmin):
    list_display = ('classifier', 'name', 'err_count', 'supported')
    fields = ('classifier', 'name', 'err_count', 'err_classifier', 'supported')
    inlines = (SummaryInline,)
    readonly_fields = ('classifier', 'err_count')

So my question is, how can I make the inline field readonly?


回答1:


After a while of trying to find the name I figured out thanks to this answer, so I checked the names at self.opts.local_fields and found the name of the middle table and added it to readonly_fields, setting can_delete to False.

class SummaryInline(admin.TabularInline):
    model = ParserError.summaries.through
    readonly_fields = ('myclasssummary',)
    can_delete = False

pretty simple but took me a while so I figured out it was a good idea to add it here.




回答2:


Additionally, if you do not want the ability to add/delete the rows, you can add these definitions.

def has_add_permission(self, request, obj=None):
    return False

def has_delete_permission(self, request, obj=None):
    return False



回答3:


You can make the entire inline readonly by adding:

class UnitsInline(admin.TabularInline):

    def has_change_permission(self, request, obj=None):
        return False

This will prevent anyone from editing the entry from the admin.

Another example that prevents, adding, deletion and displays all the inline fields as readonly:

class ReadOnlyInline(admin.TabularInline):
    def has_change_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def get_readonly_fields(self, request, obj=None):
        return list(super().get_fields(request, obj))



回答4:


Thanks Keval Prabhu

class UnitsInline(admin.TabularInline):
    model = Units
    extra = 0
    verbose_name = 'Units'
    verbose_name_plural = 'Units of company'

    **def has_add_permission(self, request, obj=None):
        return False
    def has_delete_permission(self, request, obj=None):
        return False**


来源:https://stackoverflow.com/questions/17118320/how-to-add-readonly-inline-on-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!