修改模型类HeroAdmin
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin):
change_list_template = "entities/heroes_changelist.html"
... # 此处原代码不动,只增加此前后代码
def get_urls(self):
urls = super().get_urls()
my_urls = [
path('immortal/', self.set_immortal),
path('mortal/', self.set_mortal),
]
return my_urls + urls
def set_immortal(self, request):
self.model.objects.all().update(is_immortal=True)
self.message_user(request, "All heroes are now immortal")
return HttpResponseRedirect("../")
def set_mortal(self, request):
self.model.objects.all().update(is_immortal=False)
self.message_user(request, "All heroes are now mortal")
return HttpResponseRedirect("../")
新增目录文件templates/Entities/change_form.html,Entities为应用名。change_form.html代码如下:
{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}
{% block object-tools-items %}
<li>
<a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a>
</li>
<li>
<a href="mylink/" class="historylink">My Link</a>
</li>
{% if has_absolute_url %}
<li>
<a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a>
</li>
{% endif %}
{% endblock %}
显示效果: