忽略Django管理站点的DEFAULT_CONTENT_TYPE?

时间:2010-07-22 02:19:11

标签: xhtml django-admin

将Django管理站点应用中的视图返回的所有HttpResponse对象强制使用“text / html”作为其内容类型的最佳方法是什么,无论{{1 }} 设置?我的项目设置为“application / xhtml + xml”,虽然管理员应用程序生成的内容声称是有效的XHTML(查看其doctype声明),但事实并非如此。 Ticket #5704是一个主要问题,我发现了内联表单的一些问题(即自由使用DEFAULT_CONTENT_TYPE,它不是XHTML中的命名实体)。 Ticket #11684中的评论表明管理站点可能需要一段时间才能完全支持XHTML,因此我需要弄清楚如何使用“text / html”作为管理站点,同时将默认值保留为“应用程序” / XHTML + XML“。

1 个答案:

答案 0 :(得分:1)

我不确定这是否是最佳方式,但我最终通过继承AdminSite并覆盖admin_view方法实现了我的目标:

class HTMLAdminSite(admin.AdminSite):
    '''Django AdminSite that forces response content-types to be text/html

    This class overrides the default Django AdminSite `admin_view` method. It
    decorates the view function passed and sets the "Content-Type" header of
    the response to 'text/html; charset=utf-8'.
    '''

    def _force_html(self, view):
        def force_html(*arguments, **keywords):
            response = view(*arguments, **keywords)
            response['Content-Type'] = 'text/html; charset=utf-8'
            return response
        return force_html

    def admin_view(self, view, *arguments, **keywords):
        return super(HTMLAdminSite, self).admin_view(self._force_html(view),
                                                     *arguments, **keywords)

然后,在我的根URLconf中,在调用admin.autodiscover()之前,我将admin.site设置为此HTMLAdminSite类的实例。它似乎工作正常,但如果有更好的方法,我会很高兴听到它。

相关问题