Reputation: 11248
I've got a model method _get_admin_url
and want to construct the url dynamically.
class Person(models.Model):
...
def _get_admin_url(self):
"Returns the admin url."
# return '/admin/some_app/person/%d' %self.id
return '/admin/%s/%s/%d/' %(..., ..., d)
admin_url = property(_get_admin_url)
How can I get the values for app_label and class name? Or is there a better way?
Upvotes: 0
Views: 546
Reputation: 11248
It's also possible to set app_name and model_name with ContentType see: https://stackoverflow.com/a/11395481/991572
So I ended up doing this in webapp/models.py
:
from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
class Base(models.Model):
title = models.CharField(max_length=100)
def _get_admin_url(self):
"Returns the admin change view url."
content_type = ContentType.objects.get_for_model(self.__class__)
view_name = "admin:%s_%s_change" % (content_type.app_label, content_type.model)
url = urlresolvers.reverse(view_name, args=(self.id,))
return url
admin_url = property(_get_admin_url)
class Book(Base):
something = models.CharField(max_length=100)
Register Base and Book to the admin site, created some entries and in shell:
In [1]: from webapp.models import *
In [2]: Base.objects.get(pk=1).admin_url
Out[2]: '/admin/webapp/base/1/'
In [3]: Book.objects.get(pk=2).admin_url
Out[3]: '/admin/webapp/book/2/'
Upvotes: 0
Reputation: 99680
You can use the Reversing admin URLs
feature
from django.core import urlresolvers
c = Choice.objects.get(...)
change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,))
If you wish to refer the change_list page, you would do
urlresolvers.reverse('admin:%s_%s_changelist' % (app_label, model_name))
Upvotes: 1