如何在django中启用/ static / css URL enable

时间:2012-03-06 21:33:47

标签: django django-urls django-settings django-1.3 django-static

当我使用MEDIA_URL或STATIC_URL指向/ static /当前将MEDIA_URL设置为/ static /  并在CSS文件的路径中使用它,如:

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

它指向/static/css.css,但尝试http://localhost/static/css.css会出现404错误。

我有设置:

.....
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = 'D:/programming/django_projects/ecomstore/'
.....

在urls.py中我指的是这样的静态:

url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
     {'document_root':'D:/programming/django_projects/ecomstore/'}

那么问题出在哪里?为什么显示404,我是否需要为静态文件创建一些视图?或者我的设置或urls.py还有其他问题吗?任何回应都将受到赞赏,因为我是django的新手。

提前致谢

1 个答案:

答案 0 :(得分:6)

您需要更密切地重新阅读文档:https://docs.djangoproject.com/en/dev/howto/static-files/

以下是需要注意的事项:

  1. MEDIA_URLMEDIA_ROOT适用于用户上传(模型上的FileFieldImageField)。它应该是它自己的文件夹; “媒体”很常见。

  2. STATIC_URLSTATIC_ROOT用于您的静态资源。它也应该是它自己的文件夹; “静态”很常见。

  3. 实际上是否在STATIC_ROOT中添加了任何内容。此目录仅用于生产中collectstatic管理命令的输出。

  4. 您的静态资源应该放在应用的“静态”文件夹一个全新的不同目录中(即不是MEDIA_ROOTSTATIC_ROOT)。然后,将该目录的路径添加到STATICFILES_DIRS

  5. 不要向urls.py添加任何内容。在开发过程中,Django将自动为您的应用程序“静态”目录或STATICFILES_DIRS中的任何目录提供任何服务。在制作中,您的网络服务器将负责提供这些文件。