xadmin excel导入问题:TypeError: render_to_string() got an unexpected keyword argument 'context_instance'

先看放在 xadmin/plugins/excel.py中的问题代码:

# excel 导入
class ListImportExcelPlugin(BaseAdminPlugin):
    import_excel = False

    def init_request(self, *args, **kwargs):
        return bool(self.import_excel)

    def block_top_toolbar(self, context, nodes):
        nodes.append(
            loader.render_to_string('xadmin/excel/model_list.top_toolbar.import.html', context_instance=context)) 
            
xadmin.site.register_plugin(ListImportExcelPlugin, ListAdminView)

接着就会报TypeError: render_to_string() got an unexpected keyword argument 'context_instance’
这是因为render_to_string这个函数的参数改变了,去源代码看,会发现context_instance换成了context

def render_to_string(template_name, context=None, request=None, using=None):
    """
    Loads a template and renders it with a context. Returns a string.

    template_name may be a string or a list of strings.
    """
    if isinstance(template_name, (list, tuple)):
        template = select_template(template_name, using=using)
    else:
        template = get_template(template_name, using=using)
    return template.render(context, request)

然后改成

loader.render_to_string('xadmin/excel/model_list.top_toolbar.import.html', context=context))

是不是一开始很开心以为ok了呢,但这时又会报个新错误
TypeError: context must be a dict rather than RequestContext
一开始我也是烦了很久不知道怎么弄,但是后来看了一下别的插件就懂了
我们需要引进一个新的方法来转换

from xadmin.plugins.utils import get_context_dict

    def block_top_toolbar(self, context, nodes):
        context = get_context_dict(context or {}) # 用此方法来转换
        nodes.append(
            loader.render_to_string('xadmin/excel/model_list.top_toolbar.import.html', context=context))

然后就OK啦
总结:可以参照其他相似插件来解决问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值