Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin different inlines for change and add view

I need separate views for add and change page. In add page I'd like to exclude some fields from inline formset. I've prepared two TabularInline classes, one of them contains property 'exclude'. I tried to use them as follows:

class BoxAdmin(admin.ModelAdmin):
    def change_view(self, request, obj_id):
        self.inlines=[ItemChangeInline,]
        return super(BoxAdmin, self).change_view(self.request, obj_id)
    def add_view(self, request):
        self.inlines=[ItemAddInline,]
        return super(BoxAdmin, self).add_view(self, request)

with no effect (no inline is shown at all).

like image 921
alekwisnia Avatar asked Feb 10 '10 08:02

alekwisnia


3 Answers

It works with Django 1.5+ and seems fine & elegant:

// admin.py
class BoxAdmin(ModelAdmin):

    inlines = ()

    def change_view(self, request, object_id, form_url='', extra_context=None):
        self.inlines = (ItemChangeInline, )
        return super(BoxAdmin, self).change_view(request, object_id)

    def add_view(self, request, form_url='', extra_context=None):
        self.inlines = (ItemAddInline, )
        return super(BoxAdmin, self).add_view(request)

hope it can be useful for anyone

like image 168
Andrea Rabbaglietti Avatar answered Oct 02 '22 17:10

Andrea Rabbaglietti


Here is the code that seems to be working:

class BoxAdmin(admin.ModelAdmin):
   def change_view(self, request, obj_id):
        self.inlines=[ItemChangeInline,]
        for inline_class in self.inlines:
            inline_instance = inline_class(self.model, self.admin_site)
            self.inline_instances.append(inline_instance)
        return super(BoxAdmin, self).change_view(request, obj_id)
    def add_view(self, request):
        self.inlines=[ItemAddInline,]
        for inline_class in self.inlines:
            inline_instance = inline_class(self.model, self.admin_site)
            self.inline_instances.append(inline_instance)
        return super(BoxAdmin, self).add_view(request)

However, this looks inelegant, cause this part:

            for inline_class in self.inlines:
            inline_instance = inline_class(self.model, self.admin_site)
            self.inline_instances.append(inline_instance)

is a copy-paste from init method of admin.ModelAdmin (so it is run twice).

like image 41
alekwisnia Avatar answered Oct 02 '22 16:10

alekwisnia


Why in add_view you have .add_view(self, request) and in change view you have .change_view(self.request, ..)? I believe, you don't need self in add_view, since you use super.

like image 45
gruszczy Avatar answered Oct 02 '22 15:10

gruszczy