Django:在基于 Class 的视图中包含媒体 (css/js)

Django: Include Media (css/js) in Class-Based Views

我正在将旧的 django 代码从基于方法的视图更新为基于 class 的视图。

我知道如何通过 Media class

在表单中包含媒体 (css/js)

如果基于 class 的视图不包含任何表单,我如何使用媒体 class?

Django Sekizai 用于此:

这是他们文档中的示例:

{% load sekizai_tags %}

<html>
<head>
{% render_block "css" %}
</head>
<body>
Your content comes here.
Maybe you want to throw in some css:
{% addtoblock "css" %}
<link href="/media/css/stylesheet.css" media="screen" rel="stylesheet" type="text/css" />
{% endaddtoblock %}
Some more content here.
{% addtoblock "js" %}
<script type="text/javascript">
alert("Hello django-sekizai");
</script>
{% endaddtoblock %}
And even more content.
{% render_block "js" %}
</body>
</html>

此示例显示了一个模板中的所有内容,但是 - 当然 - 您可以通过继承或包含将其拆分为多个模板,并在任何部分模板中使用 addtoblock 指令。

一个更复杂的现实生活中的例子也是 in their documentation

这是一个小的 mixin class,可以帮助您将媒体添加到基于 CreateViewUpdateViewDeleteView 的视图中:

class InjectFormMediaMixin(object):
    def get_form_class(self):
        form_class = super(InjectFormMediaMixin, self).get_form_class()
        if hasattr(self, 'Media') and not hasattr(form_class, 'Media'):
            form_class.Media = self.Media
        return form_class

示例:

class CreateFooView(InjectFormMediaMixin, CreateView):
    model = models.Foo
    fields = (
        'name',
    )

    class Media:
        css = {
            'all': ('pretty.css',)
        }
        js = ('animations.js', 'actions.js')

CSS/JS 通常在模板本身而不是在视图中进行管理。参见 https://docs.djangoproject.com/en/1.10/howto/static-files/

例如,使用base.html:

<!DOCTYPE html>
<html>
    <head>

        <title>
            {% block page_title %}{{ page_title }}{% endblock %}
        </title>

        {% block css %}
        {% endblock %}

    </head>
    <body>

        {% block main %}
        {% endblock %}

        {% block scripts %}
        {% endblock %}

    </body>
</html>

并用 my_page.html 扩展它:

{% extends "base.html" %}
{% load staticfiles %}

{% block page_title %}
Hello!
{% endblock %}

{% block css %}
    <link href="{% static "page.css" %}" rel="stylesheet"/>
{% endblock %}

{% block main %}
Yo!
{% endblock %}

{% block scripts %}
    <script src="{% static 'my_scripts.js' %}"></script>
{% endblock %}