Reputation: 1971
For simplicity, let say that I have model Product and model Parameters. By default, in model Product I want these settings:
class ProductAdmin(ModelAdmin):
list_display = ('name', 'brand', 'sort', 'specific', 'link_to_frontend', 'category_names', 'ean', 'created', 'creator')
list_filter = ('category', 'creator')
search_fields = ('name', 'brand__name', 'sort', 'specific', 'category__name', 'ean')
In Parameters add/edit, I have added Product as raw_id_fields. As I have lot of columns inside default Product list, I would like to do different settings if popup:
class ProductAdmin(ModelAdmin):
list_display = ('name', 'brand', 'sort', 'specific', 'category_names')
list_filter = ()
search_fields = ('name', 'brand__name', 'sort', 'specific', 'category__name')
Any help appreciated.
Upvotes: 2
Views: 1184
Reputation: 1971
Finally, found the solution. I have created an universal own ModelAdmin class, in universal app's admin.py
file:
from django.contrib import admin
from django.contrib.admin.views.main import IS_POPUP_VAR
class YourModelAdmin(admin.ModelAdmin):
popup_list_display = ()
popup_list_filter = ()
def get_list_display(self, request):
if IS_POPUP_VAR in request.GET and self.popup_list_display: # return list_display if not set
return self.popup_list_display
else:
return self.list_display
def get_list_filter(self, request):
if IS_POPUP_VAR in request.GET: # return empty tuple if not set
return self.popup_list_filter
else:
return self.list_filter
And from app's admin, I'm calling:
from django.contrib import admin
from [your-uni-app].admin import YourModelAdmin # not necessary if in same file
class ProductAdmin(YourModelAdmin): # e.g.
list_display = ('name', 'category', 'properties',)
popup_list_display = ('name', 'category',)
# same settings for list_filter and popup_list_filter
admin.register(Product, ProductAdmin)
This solution is also open to conditional list_display based on some user-role (e.g.) or manipulation with list_display before returning (add any column automatically to all lists). Same for list_filter and any function from django.contrib.admin.ModelAdmin (or BaseModelAdmin) if overriden.
Overwrite search_fields
means to create override of django.contrib.admin.ModelAdmin.chagnelist_view
function. For me, it became unnecessary as I need same searching in both, normal and popup view. However, only negative of no ability to overwrite is that you can search by field which is not visible, which seems to be not so big problem...
Hope this will help to anybody.
Upvotes: 4