Reputation: 64699
How do you lookup the admin change url for an arbitrary model?
If I know the model, I can get the url by doing something like:
>>> print urlresolvers.reverse('admin:myapp_mymodel_change', args=(obj.id,))
/admin/myapp/mymodel/123/
I have a generic foreign key on a model, and I'd like to provide a link in admin to the object's corresponding change page. Since it can be any type of model, I can't easily use reverse(). Is there some way I could simply this to the following?
>>> get_admin_change_url(obj)
/admin/myapp/mymodel/123/
Upvotes: 4
Views: 1122
Reputation: 239200
Once you have the object, you can access its app label and name on its _meta
class, then construct the name of the admin change url dynamically.
app_label = obj._meta.app_label
model = obj._meta.module_name
reverse('admin:%s_%s_change' % (app_label, model), args=(obj.id,))
Upvotes: 6