如何将CSS附加到我的模板? [英] How to attach CSS to my template?

查看:225
本文介绍了如何将CSS附加到我的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把css附加到Django的模板中。我在我的项目的主文件夹中创建了静态目录,并在settings.py中添加了以下行:

  import os 
ROOT = os.path.dirname(os.path.abspath(__ file__))
path = lambda * a:os.path.join(ROOT,* a)
PROJECT = os.path.basename ROOT)

然后我在settings.py中定义vars

  MEDIA_ROOT = path('media')
MEDIA_URL ='/ media /'
STATIC_ROOT = path('static')
STATIC_URL = '/ static /'
STATICFILES_DIRS = path('static')

在模板中我链接以这样的方式来css:

 < link href ={{STATIC_URL}} css / mycss.css = 样式表 > 

Django生成带有此类源代码的页面:

 < link href =/ static / css / mycss.css =stylesheet> 

如果我尝试访问此链接( http://127.0.0.1 :8000 / static / css / myss.css )从Chrome源代码查看器,它返回:

 发生服务器错误。请联系管理员。 

我做错了什么?感谢提前!

解决方案

在开发中,您必须在网址中的URL中添加特定的URL模式.py



Django文档详细介绍了 here



请注意,应该在生产中禁用此网址。此回答另一个非常相似的问题应该可以帮助您解决这个问题。


I'd like to attach css to my template in Django. I created static dir in the main folder of my project and in settings.py added these lines:

import os
ROOT = os.path.dirname(os.path.abspath(__file__))
path = lambda *a: os.path.join(ROOT, *a)
PROJECT = os.path.basename(ROOT)

Then I defined vars in settings.py

MEDIA_ROOT = path('media')
MEDIA_URL = '/media/'
STATIC_ROOT = path('static')
STATIC_URL = '/static/'
STATICFILES_DIRS = path('static')

In template I link to css in a such way:

<link href="{{ STATIC_URL }}css/mycss.css" rel="stylesheet">

Django generates page with such source code:

<link href="/static/css/mycss.css" rel="stylesheet">

If I try to access this link (http://127.0.0.1:8000/static/css/myss.css) from Chrome source code viewer, it returns:

A server error occurred.  Please contact the administrator.

What am I doing wrong? Thanks in advance!

解决方案

In development you have to add a specific URL pattern to your urls in urls.py.

The Django docs talk about this in detail here.

Note that you should disable this url in production. This answer to another, very similar question should help you fix this.

这篇关于如何将CSS附加到我的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆