简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM