L
L
Lopus2016-04-01 11:22:47
Django
Lopus, 2016-04-01 11:22:47

How to include styles (css) of applications in a django template?

added 'django.contrib.staticfiles' to INSTALLED_APPS
in base template base.html: {% load staticfiles %}
created in app (news) static/news/css/styles.css
I want pages, /news/, /news/ .... this file was connected.
Are there any tools out of the box or already worked out tools for this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2016-04-01
@Lopus

Better to use template functionality

proj/
└── templates
    ├── base.html
    └── news.html

base
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="{% static main.css %}">
    {% block additional_media1 %}{% endblock %}
    {% block additional_media2 %}
        <link rel="stylesheet" href="{% static else.css %}">
    {% endblock %}
</head>
<body>

{% block body1 %}{% endblock %}

{% block body2 %}{% endblock %}
</body>
</html>

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

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

{% block additional_media2 %}
    {{ block.super }} 
    <link rel="stylesheet" href="{% static else2.css %}">
{% endblock %}

{% block body1 %}lorem{% endblock %}

{% block body2 %}ipsum{% endblock %}

V
Vladimir Kuts, 2016-04-01
@fox_12

In the view class Media:

....
    class Media:
        js = ('js/my.js', )
        css = {'all': ('css/settings_styles.css', )}

or as a procedure (if we use conditions for example) - an example from customizing the admin panel using small style inserts directly into the template, for ordinary views - the essence is the same:
import embedded_media as emb

@admin.register(MyModel)
class MyModelAdmin(ReadOnlyAdmin):
    ...
    @property
    def media(self):
        media = super(MyModelAdmin, self).media
        js = (
            '/admin/jsi18n/',
            '/static/admin/js/calendar.js',
            '/static/admin/js/admin/DateTimeShortcuts.js' )
        if self.read_only:
            css = { 'all': (emb.CSS('.save-box { display: none; }'),) }
            media.add_css(css)
        media.add_js(js)
        return media

Well, in templates, you can connect by itself, or using templatetags for example

V
Viktor Melnikov, 2016-04-01
@Viteran33

More options:
make a block in the base template where you will include additional css files, make a template for news and redefine this block in it.
The second way is to add logic to the base template and write a condition if there is news in the url, then output css, but there is no need for extra logic in the template.
the path you will most likely

<link rel="stylesheet" href="{% static "news/css/styles.css" %}" type="text/css">
don't forget to collect static.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question