答案 0 :(得分:5)
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 %}
答案 1 :(得分:3)
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。
答案 2 :(得分:1)
这是一个小型的mixin类,可以帮助您根据CreateView
,UpdateView
和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
示例:
class CreateFooView(InjectFormMediaMixin, CreateView):
model = models.Foo
fields = (
'name',
)
class Media:
css = {
'all': ('pretty.css',)
}
js = ('animations.js', 'actions.js')