Home Ask Login Register

Developers Planet

Your answer is one click away!

redzer101 February 2016

Django csrf_token in ModelAdmin

I want to add a form to the list display of my ModelAdmin, but can't get the csrf_token to render properly. I'm using django 1.6. My code looks like this:

class ApplicationAdmin(admin.ModelAdmin):
    model = Application
    list_display = ('applicant', 'approve_or_reject')

    def approve_or_reject(self, obj):
        return '<form method="post" action="/applications/approvals">{% csrf_token %}<input type="submit" class="btn-approve" name="approve" value="Approve"/></form>'

    approve_or_reject.short_description = 'Approve/Reject'
    approve_or_reject.allow_tags = True

admin.site.register(Application, ApplicationAdmin)

I keep getting the error:

KeyError at /management/application/ '% csrf_token %'

How can I properly pass the csrf_token?


Alasdair February 2016

Model admin methods used in list_display like approve_or_reject should return text. If you mark the output as safe, you can return HTML. However, the return value is not treated like Django template language, so using the csrf token tag won't work.

It wouldn't be easy to get the csrf token inside the approve_or_reject method, because you do not have access to the request object. Another issue is that the entire changelist table is already wrapped in a form tag (id="changelist-form"), and form tags should not be nested.

An alternative would be to implement your 'approve or reject' functionality as an admin action. The UI would be different, but it might be good enough.

Post Status

Asked in February 2016
Viewed 3,617 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life