Search code examples
djangodjango-class-based-viewsdjango-media

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


I am updating old django code from method-based views to class-based views.

I know how to include media (css/js) in forms via the Media class

How can I use the media class if my class based view does not contain any forms?


Solution

  • 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 %}