本文介绍了添加按钮以导出到 Wagtail 仪表板上的 csv/xlsx 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试此堆栈溢出帖子中提到的解决方案(将按钮添加到 Wagtail仪表板)但是该解决方案可能已经过时,或者至少它对我不起作用,我不确定为什么.

目标:能够将对象的数据导出到 csv

首先,必须稍微调整按钮 HTML 代码才能正确格式化,如下所示:

{% 扩展modeladmin/index.html";%}{% 区块头_extra %}<div class="right"><div class="addbutton";style="margin-left: 2em;">{% 包含modeladmin/includes/button.html";按钮=view.button_helper.export_button %}<a href="#";class=button bicolor icon icon-download">我的按钮</a>

{{ block.super }}{% comment %}显示原始按钮{% endcomment %}{% 结束块 %}

然后我复制并粘贴了视图和辅助函数:

 from django.contrib.auth.decorators import login_required从 django.urls 导入反向从 django.utils.decorators 导入 method_decorator从 django.utils.functional 导入 cached_property从 django.utils.translation 导入 ugettext 为 _从 wagtail.contrib.modeladmin.helpers 导入 AdminURLHelper, ButtonHelper从 wagtail.contrib.modeladmin.views 导入 IndexView类 ExportButtonHelper(ButtonHelper):"这个助手构造了所有必要的属性来创建一个按钮.有很多样板文件只是为了类名是正确的:("export_button_classnames = ['icon', 'icon-download']def export_button(self, classnames_add=None, classnames_exclude=None):如果 classnames_add 为 None:classnames_add = []如果 classnames_exclude 是 None:classnames_exclude = []类名 = self.export_button_classnames + classnames_addcn = self.finalise_classname(classnames, classnames_exclude)text = _('Export {}'.format(self.verbose_name_plural.title()))返回 {'url': self.url_helper.get_action_url('export', query_params=self.request.GET),标签":文本,'类名':cn,标题":文本,}类 ExportAdminURLHelper(AdminURLHelper):"这个助手构建了不同的 url.这主要是为了覆盖默认行为考虑除create"、choose_parent"和index"之外的任何操作作为特定于对象",并将尝试将对象 PK 添加到 url这不是我们想要的 `export` 选项.此外,它还将过滤器附加到操作中."non_object_specific_actions = ('create', 'choose_parent', 'index', 'export')def get_action_url(self, action, *args, **kwargs):query_params = kwargs.pop('query_params', None)url_name = self.get_action_url_name(action)如果在 self.non_object_specific_actions 中操作:url = 反向(url_name)别的:url = 反向(url_name,args=args,kwargs=kwargs)如果查询参数:url += '?{params}'.format(params=query_params.urlencode())返回网址def get_action_url_pattern(self, action):如果在 self.non_object_specific_actions 中操作:返回 self._get_action_url_pattern(action)返回 self._get_object_specific_action_url_pattern(action)类导出视图(索引视图):"一个基于类的视图,它将生成"def export_csv(self):数据 = self.queryset.all()回复 = ...返回响应@method_decorator(login_required)def dispatch(self, request, *args, **kwargs):super().dispatch(request, *args, **kwargs)返回 self.export_csv()类ExportModelAdminMixin(对象):"添加到模型管理员的 mixin,它挂钩了不同的助手,视图并注册新的网址."button_helper_class = ExportButtonHelperurl_helper_class = ExportAdminURLHelperexport_view_class = 导出视图def get_admin_urls_for_registration(self):urls = super().get_admin_urls_for_registration()网址 += (网址(self.url_helper.get_action_url_pattern('export'),self.export_view,name=self.url_helper.get_action_url_name('export')),)返回网址def export_view(self, request):kwargs = {'model_admin': self}view_class = self.export_view_class返回 view_class.as_view(**kwargs)(request)

然后我将 ModelAdmin 添加到钩子中.我能够看到该按钮,但它无法正常工作(导出 csv).事实上,它完全没有任何作用(毕竟href 是#),我觉得我错过了一些步骤.

解决方案

我使用了与您相同的实现.我猜你在 def export_csv(self) 方法中遇到了问题这是我的实现

from djqscsv.djqscsv import render_to_csv_response类导出视图(索引视图):model_admin = 无def export_csv(self) ->字典:if (self.model_admin is None) or not hasattr(self.model_admin,csv_export_fields";):数据 = self.queryset.all().values()别的:数据 = self.queryset.all().values(*self.model_admin.csv_export_fields)返回 render_to_csv_response(data)@method_decorator(login_required)def dispatch(self, request: HttpRequest, *args: list, **kwargs: dict) ->字典:super().dispatch(request, *args, **kwargs)返回 self.export_csv()

csv_export_fields 可以添加到您的模型管理员以指定您要导出的字段

这里我要添加 HTML 文件:

{% extends "modeladmin/index.html";%}{% 区块头_额外 %}{% 包含 'modeladmin/includes/button.html' 和 button=view.button_helper.export_button %}{{ block.super }}{% 结束块 %}

您的 admin.py

class MyModelAdmin(ModelAdmin, ExportModelAdminMixin):模型 = 我的模型menu_icon = '标签'menu_order = 200index_template_name = "wagtailadmin/export_csv.html";csv_export_fields = [ field_name", field_name_1", ]list_display = ('first_name', 'last_name'')search_fields = ('first_name', 'last_name',)

I am attempting the solution mentioned in this stack overflow post (Adding a button to Wagtail Dashboard) however the solution might be outdated, or at least it doesn't work for me and I'm unsure why.

Goal: Be able to export a object's data to csv

First, the button HTML code had to be slightly adjusted to be formatted correctly like so:

{% extends "modeladmin/index.html" %}
{% block header_extra %}
    <div class="right">
        <div class="addbutton" style="margin-left: 2em;">
            {% include "modeladmin/includes/button.html" with button=view.button_helper.export_button %}
            <a href="#" class="button bicolor icon icon-download">My button</a>
        </div>
    </div>
    {{ block.super }}{% comment %}Display the original buttons {% endcomment %}
{% endblock %}

and then I copied and pasted the views and helper functions:

from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from wagtail.contrib.modeladmin.helpers import AdminURLHelper, ButtonHelper
from wagtail.contrib.modeladmin.views import IndexView


class ExportButtonHelper(ButtonHelper):
    """
    This helper constructs all the necessary attributes to create a button.

    There is a lot of boilerplate just for the classnames to be right :(
    """

    export_button_classnames = ['icon', 'icon-download']

    def export_button(self, classnames_add=None, classnames_exclude=None):
        if classnames_add is None:
            classnames_add = []
        if classnames_exclude is None:
            classnames_exclude = []

        classnames = self.export_button_classnames + classnames_add
        cn = self.finalise_classname(classnames, classnames_exclude)
        text = _('Export {}'.format(self.verbose_name_plural.title()))

        return {
            'url': self.url_helper.get_action_url('export', query_params=self.request.GET),
            'label': text,
            'classname': cn,
            'title': text,
        }


class ExportAdminURLHelper(AdminURLHelper):
    """
    This helper constructs the different urls.

    This is mostly just to overwrite the default behaviour
    which consider any action other than 'create', 'choose_parent' and 'index'
    as `object specific` and will try to add the object PK to the url
    which is not what we want for the `export` option.

    In addition, it appends the filters to the action.
    """

    non_object_specific_actions = ('create', 'choose_parent', 'index', 'export')

    def get_action_url(self, action, *args, **kwargs):
        query_params = kwargs.pop('query_params', None)

        url_name = self.get_action_url_name(action)
        if action in self.non_object_specific_actions:
            url = reverse(url_name)
        else:
            url = reverse(url_name, args=args, kwargs=kwargs)

        if query_params:
            url += '?{params}'.format(params=query_params.urlencode())

        return url

    def get_action_url_pattern(self, action):
        if action in self.non_object_specific_actions:
            return self._get_action_url_pattern(action)

        return self._get_object_specific_action_url_pattern(action)


class ExportView(IndexView):
    """
    A Class Based View which will generate
    """

    def export_csv(self):
        data = self.queryset.all()
        response = ...
        return response


    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        super().dispatch(request, *args, **kwargs)
        return self.export_csv()


class ExportModelAdminMixin(object):
    """
    A mixin to add to your model admin which hooks the different helpers, the view
    and register the new urls.
    """

    button_helper_class = ExportButtonHelper
    url_helper_class = ExportAdminURLHelper

    export_view_class = ExportView

    def get_admin_urls_for_registration(self):
        urls = super().get_admin_urls_for_registration()
        urls += (
            url(
                self.url_helper.get_action_url_pattern('export'),
                self.export_view,
                name=self.url_helper.get_action_url_name('export')
            ),
        )

        return urls

    def export_view(self, request):
        kwargs = {'model_admin': self}
        view_class = self.export_view_class
        return view_class.as_view(**kwargs)(request)

and then I added the ModelAdmin to the hooks. I'm able to see the button however it doesn't function as it's supposed to (exporting the csv). In fact, it does absolutely nothing (the href is # after all) and I feel like I'm missing some steps.

解决方案

I used the same implementation as you.I guess that you are having problems in the def export_csv(self) methodhere my implementation

from djqscsv.djqscsv import render_to_csv_response


class ExportView(IndexView):
    model_admin = None

    def export_csv(self) -> dict:
        if (self.model_admin is None) or not hasattr(
            self.model_admin, "csv_export_fields"
        ):
            data = self.queryset.all().values()
        else:
            data = self.queryset.all().values(*self.model_admin.csv_export_fields)
        return render_to_csv_response(data)

    @method_decorator(login_required)
    def dispatch(self, request: HttpRequest, *args: list, **kwargs: dict) -> dict:
        super().dispatch(request, *args, **kwargs)
        return self.export_csv()

csv_export_fields can be added to your model admin to specify which fields you want to export

here I am adding the HTML file:

{% extends "modeladmin/index.html" %}

{% block header_extra %}
    {% include 'modeladmin/includes/button.html' with button=view.button_helper.export_button %}
    {{ block.super }}
{% endblock %}

your admin.py

class MyModelAdmin(ModelAdmin, ExportModelAdminMixin):
    model = MyModel
    menu_icon = 'tag'
    menu_order = 200
    index_template_name = "wagtailadmin/export_csv.html"
    csv_export_fields = [ "field_name","field_name_1", ]
    list_display = ('first_name', 'last_name'')
    search_fields = ('first_name', 'last_name',)

这篇关于添加按钮以导出到 Wagtail 仪表板上的 csv/xlsx 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 04:53