django2.2 TypeError: render() got an unexpected keyword argument 'renderer'

2023-02-18 14:49:13 浏览数 (1)

从Django 1.11 迁移到 Django 2.2 后 AdminFileWidget 的 render 报错了:

代码语言:javascript复制
TypeError: render() got an unexpected keyword argument 'renderer'
(41 additional frame(s) were not displayed)
...
  File "django/template/base.py", line 993, in render
    return render_value_in_context(output, context)
  File "django/template/base.py", line 972, in render_value_in_context
    value = str(value)
  File "django/utils/html.py", line 388, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "django/forms/boundfield.py", line 33, in __str__
    return self.as_widget()
  File "django/forms/boundfield.py", line 93, in as_widget
    renderer=self.form.renderer,

解决办法:

代码语言:javascript复制
class AdminImageWidget(AdminFileWidget):
    # django 2.2
    # def render(self, name, value, attrs=None, renderer=None):
    #     """Render the widget as an HTML string."""
    #     context = self.get_context(name, value, attrs)
    #     return self._render(self.template_name, context, renderer)

    # def render(self, name, value, attrs=None):  # django 1.11
    def render(self, name, value, attrs=None, renderer=None):  # django 2.2
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            # output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" /></a> %s ' % 
            #               (image_url, image_url, file_name, _('Change:')))
            output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" /></a>' % 
                          (image_url, image_url, file_name))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

widgets.py 的路径:

../lib/python3.6/site-packages/django/forms/widgets.py  -> 239 行左右

0 人点赞