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)

修改后,后台顯示如下。

返回目錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM