Django Admin消息定製

Django admin 真是一個強大的東西,輕輕鬆鬆就能搭好一個網站的後臺,大部分的功能都能知足。它也自帶了操做後的消息提醒。具體能夠查看文檔Admin actions。文檔中有很是簡單的給用戶發送消息的方法,即:python

self.message_user(request, message)

可是這樣的消息都是「操做成功」的消息,消息前面帶的是一個綠色勾的圖標。而不少時候須要對錯誤的操做和未成功的操做給出提示,這也的提示消息顯然不行。django

這也很簡單,Django中帶有messages模塊,能夠作出各類消息定製。Django真是一個大而全的框架。app

直接上代碼:框架

from django.contrib import admin
 from models import Category, Group, Topic, Report, Applicant 
 from django.contrib import messages
 class ApplicantAdmin(admin.ModelAdmin):
    list_display = ('applicant', 'group', 'reason', 'join_type', 'status')
    list_filter = ('group', 'join_type', 'status')
    actions = ['pass_apply', 'reject_apply']  

    def pass_apply(self, request, queryset):
        """ 經過申請 @fanlintao """
        can_treat = True
        for q in queryset:
            if q.status != 'processing':
                can_treat = False
                continue
        if can_treat:
            for q in queryset:
                if q.join_type == "manager":
                    q.group.manager.add(q.applicant)  # 將申請人加進小組管理員
                    q.status = "pass"
                    q.save()
                elif q.join_type == "member":
                    q.group.member.add(q.applicant)   # 將申請人加進組員
                    q.status = "pass"
                    q.save()
            msg = u"已經經過全部申請"
            self.message_user(request, msg)
        else:
            msg = u"只有狀態爲processing的記錄能操做,請確認!"
            messages.add_message(request, messages.ERROR, msg)
    pass_apply.short_description = u"經過申請"  

    def reject_apply(self, request, queryset):
        """ 拒絕申請 @fanlintao """
        can_treat = True
        for q in queryset:
            if q.status != 'processing':
                can_treat = False
                continue
        if can_treat:
            queryset.update(status="reject")
            msg = u"已經駁回全部申請"
            self.message_user(request, msg)
        else:
            msg = u"只有狀態爲processing的記錄能操做,請確認!"
            messages.add_message(request, messages.ERROR, msg)

    reject_apply.short_description = u"拒絕申請"
admin.site.register(Applicant, ApplicantAdmin)

使用定製的add_message方法就能完成一個錯誤的消息提醒啦。雖然仍是比較簡陋,只是消息前換了個紅色的圖標,但對於後臺也夠用啦。網站

PS:看來還要好好看看Django的messages模塊了。code

相關文章
相關標籤/搜索