I have a model A with a ForeignKey to a model B. In Django admin, how can I add a link in the admin page of model A next to the ForeignKey field which open the admin page of the model B ?
You can do the following:
models.py (example):
model B(models.Model):
name = models.CharField(max_length=20)
model A(models.Model):
field1 = models.CharField(max_length=20)
Bkey = models.ForeignKey(B)
admin.py
from django.core import urlresolvers
class AAdmin(admin.ModelAdmin):
list_display = ["field1","link_to_B"]
def link_to_B(self, obj):
link=urlresolvers.reverse("admin:yourapp_b_change", args=[obj.B.id]) #model name has to be lowercase
return u'<a href="%s">%s</a>' % (link,obj.B.name)
link_to_B.allow_tags=True
Replace yourapp with the name of your app.
In addition of the accepted answer, in newer versions of Django (1.10, 1.11 and 2.0), the reverse method is now in the package django.urls (cf. this link).
Moreover, you have to use the format_html method to output HTML in the admin. So the allow_tags become useless.
Finally, to add a link to the edit page of a user, I have this function in admin.py:
from django.urls import reverse
from django.utils.html import format_html
class ObjectAdmin(admin.ModelAdmin):
list_display = ('name', 'link_to_user')
def link_to_user(self, obj):
link = reverse("admin:auth_user_change", args=[obj.user.id])
return format_html('<a href="{}">Edit {}</a>', link, obj.user.username)
link_to_user.short_description = 'Edit user'
Django 2.0+ and Python 3.5+:
from django.urls import reverse
from django.utils.html import escape
@admin.register(models.YourModel)
class YourModelAdmin(BaseModelAdmin):
def model_str(self, obj: models.YourModel):
link = reverse("admin:module_model_change", args=[obj.model.id])
return mark_safe(f'<a href="{link}">{escape(obj.model.__str__())}</a>')
model_str.short_description = 'Model'
model_str.admin_order_field = 'model' # Make row sortable
list_display = (
'model_str',
)
There is an easier solution today, with related
being the foreign key field to be linked to:
class YourModelAdmin(model.modelAdmin):
list_display = ["field_one", "field_two", "related"]
list_display_links = ["field_one", "related"]
来源:https://stackoverflow.com/questions/28832897/link-in-django-admin-to-foreign-key-object