beautiful.drifter
beautiful.drifter

Reputation: 311

Django Admin - Dynamically pick list_display fields (user defined)

Some of my models have a lot of fields and the user may not need to see all of them at any given point in time. I am trying to add functionality to allow the user to select which fields are displayed from the front end without having to change the list_display definition in the admin.py file. I also don't want to just dump all of the fields out there for them either.

I am hoping someone may be able to point me at something on github or give me some advice on how to go about doing this.

Thanks in advance.

I am not refering to role based views. What I am talking about is users defining the fields on demand from the front end. So if I have fields A, B, C and D. I can say only show me A and D from the admin UI. Then tomorrow I may want to add the C field. I use JavaScript outside of the admin to accomplish this, but didn’t want to get into the mess of overriding the admin templates if I didn’t have to.

Upvotes: 2

Views: 1100

Answers (1)

Leopd
Leopd

Reputation: 42769

Here's a pointer towards a generic solution that gives you a bunch of control. This doesn't do anything very useful, but shows you how to dynamically change pretty much everything about the columns at runtime by looking at the list of objects that are being displayed. Combine this with request.session and I think you can do what you want... Change the number of columns to display, change the headers of the columns, and the contents, all at runtime.

class DynamicColumn():

    def __init__(self, qs:QuerySet):
        self.qs = qs
        # Analyze the queryset to decide what to show
        self.__name__ = "Dynamic column title"

    def __call__(self, widget:Widget) -> str:
        # Take the model instance and return something to display
        return f"This QS has {len(self.qs)} items"


class WidgetAdmin(admin.ModelAdmin):
    list_display = (
        'name',
        'price',
        'stock',
    )

    def get_list_display(self, request):
        qs = self.get_queryset(request)
        dc = DynamicColumn(qs)
        out = list(self.list_display)
        out.append(dc)  # Add multiple different instances if you want
        return out

Upvotes: 1

Related Questions