简体   繁体   English

.css不会影响我在Django中的模板

[英].css won't affect my template in django

I am currently writing my first django-app and are encountering a few problems, as expected. 我目前正在编写我的第一个django应用程序,并且遇到了一些预期的问题。

The problem I am struggeling with at this moment is linking css to my template files. 我目前正在努力的问题是将CSS链接到我的模板文件。 I've been searching around stackoverflow, but nothing of what I find seems to work. 我一直在寻找stackoverflow,但我发现似乎没有任何作用。

I am currently running django 1.4.2 我目前正在运行Django 1.4.2

In my settings, I have staticfiles app and staticfiles_finders enabled. 在我的设置中,我启用了staticfiles应用程序和staticfiles_finders。 My staticfiles_dirs looks like this: 我的staticfiles_dirs看起来像这样:

STATICFILES_DIRS = (
    '/home/user/project/static/',
)

Inside my static folder I have a css folder where I store my css files. 在我的静态文件夹中,我有一个css文件夹,用于存储css文件。 In this case the path to my css file is this. 在这种情况下,我的css文件的路径就是这个。

/home/user/project/static/css/index.css

In my template for my app, I've linked to the css file like this. 在我的应用程序模板中,我已经这样链接到css文件。

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/index.css />

However, the css does not seem to affect my page. 但是,css似乎不会影响我的页面。 The css does however work if I write it directly in my template file so I assume I've linked it wrong? 但是,如果我直接在模板文件中写css,它就可以工作,所以我认为链接错误了吗?

Help would be much appreciated. 帮助将不胜感激。

Django 1.4+ Django 1.4以上

{% static %}

<link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}"/>

Note: If this code is not working, you should check your settings and urlconf. 注意:如果此代码不起作用,则应检查设置和urlconf。 And I also notice some bad practice in your codes. 而且我还注意到您的代码中存在一些不良做法。

You can try another way : 您可以尝试另一种方式:

Edit these variables in the file settings.py 在文件settings.py中编辑这些变量

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC_URL = os.path.join(PROJECT_URL, 'static')

They are refering to absolute path to folders on your system, for example : 它们是指系统上文件夹的绝对路径,例如:

  • PROJECT_ROOT --> /home/user/project PROJECT_ROOT-> / home / user / project
  • STATIC_URL --> /home/user/project/static STATIC_URL-> / home / user / project / static

Expand url from STATIC_URL variables : 展开STATIC_URL变量中的网址:

  • {{ STATIC_URL }} --> h ttp://(your_host)/static/ {{STATIC_URL}}-> h ttp://(您的主机)/ static /
  • {{ STATIC_URL }}/css --> h ttp://(your_host)/static/css {{STATIC_URL}} / css-> h ttp://(您的主机)/ static / css

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM