0

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?

vkswhy
  • 78
  • 8

2 Answers2

1

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')
Danilo Akamine
  • 705
  • 7
  • 13
1

solution provided by @Danilo Akamine has worked comletely fine for me. but those who have same problem may require there: url method in:

        my_urls = [
            url(r'^new-action/(?P<id>[0-9]+)$', self.new_action)
        ]

belongs to django.conf.urls so add this line to admin.py:

from django.conf.urls import url

or you can also use path method from django.urls as:

  my_urls = [
            path('new-action/<int:id>', self.new_action)
        ]

for more info: visit https://docs.djangoproject.com/en/2.2/topics/http/urls/

vkswhy
  • 78
  • 8