Django Admin Cookbook-37如何向Django更改视图页面添加自定义按钮

37.如何向Django更改视图页面添加自定义按钮?

Villain模型有一个名为is_unique的字段:

class Villain(Entity):
    ...
    is_unique = models.BooleanField(default=True)

你想在Villain对象修改页面上添加一个名为“Make Unique”的按钮,从而使此该对象唯一,并删除其他同名的对象。

你可以通过扩展change_form来添加一个新按钮。

{% extends 'admin/change_form.html' %}
{% block submit_buttons_bottom %}
    {{ block.super }}
    <div class="submit-row">
            <input type="submit" value="Make Unique" name="_make-unique">
    </div>
{% endblock %}

然后,覆盖response_change模板并将其连接到VillainAdmin管理模型:

@admin.register(Villain)
class VillainAdmin(admin.ModelAdmin, ExportCsvMixin):
    ...
    change_form_template = "entities/villain_changeform.html"
    def response_change(self, request, obj):
        if "_make-unique" in request.POST:
            matching_names_except_this = self.get_queryset(request).filter(name=obj.name).exclude(pk=obj.id)
            matching_names_except_this.delete()
            obj.is_unique = True
            obj.save()
            self.message_user(request, "This villain is now unique")
            return HttpResponseRedirect(".")
        return super().response_change(request, obj)

修改后,后台显示如下。

返回目录

原文地址:https://www.cnblogs.com/superhin/p/12192335.html