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

会有一股神秘感。 提交于 2019-12-02 04:24:32

CSS/JS are usually managed in the template itself and not in the view. See https://docs.djangoproject.com/en/1.10/howto/static-files/

For example, use 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>

and extend it with 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 %}

Django Sekizai is meant for this:

Here is the example from their documentation:

{% 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>

This example shows everything in one template, but - of course - you can split that into multiple templates either by inheritance or includes and use the addtoblock directives in any of the partial templates.

A more complex, real life example is also in their documentation.

Here is a small mixin class that can help you add Media to views based on CreateView, UpdateView, and DeleteView:

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

Example:

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

    class Media:
        css = {
            'all': ('pretty.css',)
        }
        js = ('animations.js', 'actions.js')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!