Dalancer
Dalancer

Reputation: 1

Django admin list display with list of callable

I have a django project which create lots of reports, and each user has different permissions to view different report. And now I have a admin page which summarize all the user permissions for all reports, and I did it by sth similar to this:

class userAdmin(admin.ModelAdmin):
    def report1_perm(self, user):
        return user.has_perm('report1')
    def report2_perm(self, user):
        return user.has_perm('report2')
    list_display=['report1_perm', 'report2_perm']

Now instead of having to def a diff method for each report, I want to make callables from the list of reports I have, so sth like this

class userAdmin(admin.ModelAdmin):
    def get_list_display(self, request):
        def make_f(report):
            def report_perm(self, user):
                return user.has_perm(report)
            return report_perm
        list_display = []
        for report in reports:
            list_display.append(make_f(report))
        return list_display

However I am gettingTypeError: report_perm() missing 1 required positional argument: 'user' which I do not know how to fix. I wonder am I on the right path or there is a better solution than this

Upvotes: 0

Views: 600

Answers (1)

Skratt
Skratt

Reputation: 408

It appears you are calling it when you do make_f(report).

I guess you need to build this differently

To retain partly your structure, one solution could be to call only once with both report & user at the same time:

 class userAdmin(admin.ModelAdmin):
    def get_list_display(self, request, user):
        def make_f(report, user):
           ...
        list_display = []
        for report in reports:
            list_display.append(make_f(report, user))
        return list_display

Upvotes: 1

Related Questions