先看放在 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啦
总结:可以参照其他相似插件来解决问题