Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change list display link in django admin

I am trying to change the link for an object in the django admin list display. Here is what I have so far:

class FooModelAdmin(admin.ModelAdmin):     fields = ('foo','bar')     list_display = ('foo_link','bar')      def foo_link(self,obj):         return u'<a href="/foos/%s/">%s</a>' % (obj.foo,obj)     domain_link.allow_tags = True     domain_link.short_description = "foo" 

This produces another link within the original list display link e.g.

<a href="/admin/app/model/pk/"><a href="/foos/foo/">Foo</a></a> 
like image 774
tomfmason Avatar asked Oct 22 '10 16:10

tomfmason


2 Answers

The solution was to override the init and set the list_display_links to None e.g.

class FooModelAdmin(admin.ModelAdmin):     fields = ('foo','bar')     list_display = ('foo_link','bar')      def foo_link(self,obj):         return u'<a href="/foos/%s/">%s</a>' % (obj.foo,obj)     foo_link.allow_tags = True     foo_link.short_description = "foo"     def __init__(self,*args,**kwargs):         super(FooModelAdmin, self).__init__(*args, **kwargs)         self.list_display_links = (None, ) 
like image 64
tomfmason Avatar answered Sep 30 '22 15:09

tomfmason


I believe the correct way of doing it, is subclassing ChangeList and override the url_for_result method to create the correct change url you want.

Override the get_changelist in the admin.ModelAdmin subclass to return the new class:

from django.contrib.admin.views.main import ChangeList from django.contrib.admin.util import quote  class FooChangeList(ChangeList):     def url_for_result(self, result):         pk = getattr(result, self.pk_attname)         return '/foos/foo/%d/' % (quote(pk))  class FooAdmin(admin.ModelAdmin):     def get_changelist(self, request, **kwargs):         return FooChangeList 
like image 39
Fred Avatar answered Sep 30 '22 15:09

Fred