3
votes

In Django - Overriding get_form to customize admin forms based on request the problem is to select a different form based on the permissions of the user in the request object by hooking the get_form() method.

I would like to actually invoke a method on the object during iteration that uses the request context to output some information.

The documentation lists four ways to hook the form display.

But the function signatures don't include the request object. If they did, you could write something like (note that request is not in fact an argument):

class CustomAdmin(admin.ModelAdmin):
    list_display       = [ 'name', 'user_specific', ]
    #
    def user_specific(self, obj, request):
        return obj.func1(request)
    #
    output.short_description = 'UserSpecific'

Overriding get_form() would not be thread safe if used to store the state... So what would be the best way?

1
As I ponder this, I expect that someone will point out that the user information ought to be put into the model with a ForeignKey. That refactoring doesn't always apply. - Traveler

1 Answers

2
votes

In your case, I feel that maybe writing your own view is a better choice than hacking django's admin site.

But if you insist, you can override changelist_view and record the request.

class CustomAdmin(admin.ModelAdmin):
    list_display       = [ 'name', 'user_specific', ]

    def changelist_view(self, request, extra_context=None):
        self.request = request
        return super(admin.ModelAdmin, self).changelist_view(self, request, extra_context)

    def user_specific(self, obj):
        return obj.func1(self.request)

    output.short_description = 'UserSpecific'