abdoBim abdoBim - 1 year ago 232
Python Question

Django admin - add custom link to change list view

Firstly thanks for taking the time to read my problem

I tried to add a custom button to my admin changeList view, but it always gives me Page not found (404)

This my modelAdmin code:

class MyModelAdmin(admin.ModelAdmin):

class Media:

js = ('admin/js/additional_js.js',)

model = MyModel

def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
analyze_url = patterns('',
return analyze_url + urls

def analyze_view(self, request, pk):
# some code here
reverse('admin:myapp_MyModel_change', args=(pk,))

My jQuery code for adding custom link to change list view:

(function($) {
$(document).ready(function($) {
$(".object-tools").append('<li><a href="analyze/" class="link">Analyze</a></li>');

when I click my custom link it gives me this:

MyModel object with primary key '3/change/analyze' does not exist.

I see that the link does not point to the view

Can someone help me fix this issue.



In Django 1.9, the admin change url has changed to /admin/<app>/<model>/<pk>/change/ (release notes).

Therefore, it doesn't make sense to link to href="analyze/" in your html. The relative url is treated as /admin/<app>/<model>/3/change/analyze, not /admin/<app>/<model>/3/analyze as you expect.

You can probably fix the problem by changing the link to:

<a href="../analyze/" ...

Ideally, it would be better to reverse the url rather than having a relative link. I think this would make the code less fragile.

Since you are using Django 1.9, you can update your code to use a list rather than patterns:

from django.conf.urls import url

analyze_url = [
    url(r'^(?P<pk>\d+)/analyze/$', self.admin_site.admin_view(self.analyze_view)),