Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Inline form in Django

My Django ModelAdmin shows different forms in dependency on user permissions. I've solved it with ModelForm's (get_form, get_fieldsets), but what to do with inlines?

class NewsAdmin(admin.ModelAdmin):
    form = NewsAdminForm
    writing_form = NewsWritingForm

    inlines = (LinkInline, FileInline)

ModelAdmin initializes them in ModelAdmin.__init__() before getting request object. The only way seems to use CSS to hide them.

like image 276
San4ez Avatar asked May 03 '11 09:05

San4ez


2 Answers

You can use ModelAdmin get_inline_instances function. Following code removes inlines from add_view:

from django.contrib import admin
from models import FooModel

class FooInline(admin.StackedInline):
    model = FooModel

class MyModelAdmin(admin.ModelAdmin):
    inlines = [FooInline]

    def get_inline_instances(self, request, obj=None):
        return obj and super(MyModelAdmin, self).get_inline_instances(request, obj) or []
like image 174
Roman Suprotkin Avatar answered Sep 19 '22 09:09

Roman Suprotkin


ModelAdmin.__init__() takes the classes in ModelAdmin.inlines, instantiates them, and stores the results in ModelAdmin.inline_instances. You can set ModelAdmin.inline_instances to an empty list after __init__ to remove the inlines.

See line 243 of django/contrib/admin/options.py

like image 28
Chris Pratt Avatar answered Sep 22 '22 09:09

Chris Pratt