djangodjango-admindjango-csrfdjango-modeladmindjango-admin-actions

How can i use csrf token in customised django model admin?


I am working in a simple Django project, and i want to add a button for every model object in admin and i am able to create it by using this:
in admin.py

class RegistrationAdmin(admin.ModelAdmin):
    def button(self, obj):
        isreg = obj.username
        return format_html('<form action="/validate/" method="post">{% csrf_token %}<script>x={{isreg}};</script><button class="btn btn--pill btn--green"'
         ' type="submit">Validate</button></form>', {'isreg': isreg})

    button.short_description = 'Action'
    button.allow_tags = True
    list_display = ['username', 'button']

But when i excute it it gives key error:

KeyError at /admin/myapp/registration/
'% csrf_token %'

so how can resolve this error? or is there any other way to add functionality to my validate button?


Solution

  • If you are talking about creating a new action for every instance, you can do something like this:

    from django.conf.urls import url
    from django.contrib import admin
    from django.http import HttpResponseRedirect
    from django.utils.html import format_html
    
    class RegistrationAdmin(admin.ModelAdmin):
        list_display = ['username', 'button']
    
        def button(self, obj):
            return format_html('<a href="new-action/{}">{}</a>', obj.id, obj.username)
    
        def get_urls(self):
            urls = super().get_urls()
            my_urls = [
                url(r'^new-action/(?P<id>[0-9]+)$', self.new_action)
            ]
            return my_urls + urls
    
        def new_action(self, request, id):
            if request.user.is_authenticated:
                # your stuff
                self.message_user(request, 'ID {} successfully processed'.format(id))
            return HttpResponseRedirect('/admin')