Django xadmin 后台自定义action 动作

adminx.py

from xadmin import views
from .models import *
# 自定义动作所需
from django import forms, VERSION as django_version
from django.core.exceptions import PermissionDenied
from django.db import router
from django.template.response import TemplateResponse
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.contrib.admin.utils import get_deleted_objects
from xadmin.util import model_ngettext
from xadmin.views.base import filter_hook

ACTION_CHECKBOX_NAME = '_selected_action'
checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)
print(checkbox)

def action_checkbox(obj):
    return checkbox.render(ACTION_CHECKBOX_NAME, force_text(obj.pk))


action_checkbox.short_description = mark_safe(
    '')
action_checkbox.allow_tags = True
action_checkbox.allow_export = False
action_checkbox.is_column = False

# 继承基本动作模板
from xadmin.plugins.actions import BaseActionView

class MySelectedAction(BaseActionView):

    # 这个是执行函数名
    action_name = "update_selected"
    # 这个是显示的名字
    description = "更新所選項"

    # 这里是是否启用自定义模板
    delete_confirmation_template = None
    delete_selected_confirmation_template = None

    delete_models_batch = True

    model_perm = 'delete'
    icon = 'fa fa-times'

    @filter_hook
    # 对数据的操作
    def update_models(self, queryset):
        print(self.request.POST.get('waiter_id'))
        print(self.request.POST.get('post'))
        print(type(queryset))
        print(queryset)
        n = queryset.count()
        if n:
            if self.delete_models_batch:
                self.log('update', _('Batch delete %(count)d %(items)s.') % {"count": n, "items": model_ngettext(self.opts, n)})
                queryset.update(waiter_id=self.request.POST.get('waiter_id'))
            else:
                for obj in queryset:
                    self.log('update', '', obj)
                    obj.update(waiter_id=self.request.POST.get('waiter_id'))
            self.message_user(_("Successfully deleted %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success')

    @filter_hook
    def do_action(self, queryset):
        # Check that the user has delete permission for the actual model
        if not self.has_delete_permission():
            raise PermissionDenied

        using = router.db_for_write(self.model)

        if django_version > (2, 0):
            setattr(self.admin_site._registry[self.model], 'has_delete_permission', self.has_delete_permission)

        # Populate deletable_objects, a data structure of all related objects that
        # will also be deleted.

        if django_version > (2, 0):
            deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
                queryset, self.opts, self.admin_site)
        else:
            deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
                queryset, self.opts, self.user, self.admin_site, using)

        # The user has already confirmed the deletion.
        # Do the deletion and return a None to display the change list view again.
        if self.request.POST.get('post'):
            # 这里输出yes
            # print(self.request.POST.get('post'))
            if perms_needed:
                raise PermissionDenied
            self.update_models(queryset)
            # Return None to display the change list page again.
            return None

        if len(queryset) == 1:
            objects_name = force_text(self.opts.verbose_name)
        else:
            objects_name = force_text(self.opts.verbose_name_plural)

        if perms_needed or protected:
            title = _("Cannot delete %(name)s") % {"name": objects_name}
        else:
            title = _("Are you sure?")

        import pymysql
        # 打开数据库连接
        db = pymysql.connect(host="*", user="*",
                             password="*", db="*", port=3306)

        cur = db.cursor()

        sql = "*"
        try:
            cur.execute(sql)  # 执行sql语句
            results = cur.fetchall()  # 获取查询的所有记录

        except Exception as e:
            raise e
        finally:
            db.close()  # 关闭连接

        context = self.get_context()

        # 展现到页面的内容
        print(type(results))
        print(type(queryset))
        print(results)
        print(queryset)
        context.update({
            "title": title,
            "objects_name": objects_name,
            "deletable_objects": [deletable_objects],
            'queryset': queryset,
            'results':results,
            "perms_lacking": perms_needed,
            "protected": protected,
            "opts": self.opts,
            "app_label": self.app_label,
            'action_checkbox_name': ACTION_CHECKBOX_NAME,
        })

        # Display the confirmation page
        # 确认页的相关参数
        return TemplateResponse(self.request, self.delete_selected_confirmation_template or
                                self.get_template_list('views/youji_update.html'), context)



#使用主题
class BaseSeting(object):
    enable_themes = True
    use_bootswatch = True
xadmin.site.register(views.BaseAdminView,BaseSeting)

# 设置头部底部
class GlobaleSettings(object):
    site_title = 'title'
    site_footer = 'footer'
    menu_style = 'accordion'
xadmin.site.register(views.CommAdminView,GlobaleSettings)

class TxhAdmin(object):
    # 搜索项
    search_fields = ['name','addtime']
    # 过滤项
    list_filter=['addtime']
    # 显示的列
    list_display=('name','phone','sex','is_reg','addtime','visit_type_content','waiter_id')
    actions=[MySelectedAction,]


# 注册使之显示在后台中
xadmin.site.register(white_list,TxhAdmin)

你可能感兴趣的:(Django xadmin 后台自定义action 动作)