问题
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 ?
回答1:
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.
回答2:
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'
回答3:
Django 2.0+ and Python 3.5+:
from django.urls import reverse
from django.utils.html import escape, mark_safe
@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',
)
回答4:
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"]
回答5:
I created mixin, that does this + similar thing to many-to-many relations (there it shows count of related objects and links to changelist with apropriate filter). Based on gist I've forked from:
https://gist.github.com/hovi/2e3a216ecc4be685ec9e0d23b0eb7901
Tested on django 1.1.x and 1.0.x
来源:https://stackoverflow.com/questions/28832897/link-in-django-admin-to-foreign-key-object