如何使用指向用户或任何其他对象的可点击字段链接来使admin change_view?
像:<a href="/admin/user/{{owner.id}}/change">{{owner.fullname}}</a>
当前只有带有ID的简单文本。
from django.contrib import admin
from django.contrib.auth.models import User
from django.db import models
class Car(models.Model):
owner = models.ForeignKey(User, related_name="cars", null=True, blank=True)
class CarAdmin(admin.ModelAdmin):
pass
admin.site.register(Car, CarAdmin)
找到了很多list_view的示例,但没有change_view的示例。
UPD:试图将以下方法添加到CarAdmin中,但无济于事。
from django.utils.html import format_html
class CarAdmin(admin.ModelAdmin):
def owner_change_url(self, obj):
return format_html('<a href="/admin/base/user/%s/change/">%s</a>' % (obj.owner.id, obj.owner.full_name))
owner_change_url.short_description = 'Owner'
答案 0 :(得分:0)
您可以创建一个链接到您的用户的只读字段。在您的CarAdmin
类中:
from django.utils.safestring import mark_safe
class CarAdmin(admin.ModelAdmin):
readonly_fields = ('user_link', )
@mark_safe
def user_link(self, car):
url = reverse('admin:user_user_change', args=(car.owner.id, ))
return '<a href="{url}">{user}</a>'.format(
url=url,
user=car.owner.fullname
)
user_link.short_description = "Edit car owner"