如何在Django 1.4中为本地开发提供静态文件

jp4*_*p42 7 css django static

我刚下载了最新的Django版本(1.4.1),在使用runserver进行本地开发时,我无法弄清楚如何提供css文件.我已经阅读了关于静态文件的相关Django文档以及许多很多问题和答案......听起来它应该或多或少是自动的,但它对我不起作用.

我正在从教程中处理民意调查应用程序.

来自日志的404

[27/Apr/2012 01:04:09] "GET /polls/ HTTP/1.1" 200 210
[27/Apr/2012 01:04:09] "GET /polls/css/styles.css HTTP/1.1" 404 2596 
Run Code Online (Sandbox Code Playgroud)

目录结构

mysite
|-- manage.py
|-- mysite
    |-- __init__.py
    |-- settings.py
    |-- urls.py
    |-- wsgi.py
|-- polls
    |-- __init__.py
    |-- models.py
    |-- tests.py
    |-- views.py
    |-- static
        |-- css
            |-- styles.css
|-- templates
    |-- polls
        |-- index.html
Run Code Online (Sandbox Code Playgroud)

的index.html

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/styles.css">
Run Code Online (Sandbox Code Playgroud)

settings.py

MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
'django.core.context_processors.static',
)
Run Code Online (Sandbox Code Playgroud)

^^^当我启动项目并且不得不手动添加时,我在settings.py中没有TEMPLATE_CONTEXT_PROCESSORS变量 - 我应该担心吗?

STATICFILES_DIRS是空的,因为css文件位于polls app中名为static的目录中,这是Django自动查找的目标 - 对吗?

我的INSTALLED_APPS中也有django.contrib.staticfiles.

urls.py

我在文档中看到,该解决方案适用于本地开发服务器比的runserver -听起来这不应该是必要的,否则,对不对?(我现在已经注释掉了.)

编辑:我取消注释这些行,但没有看到更改 - 仍然在css文件上获得相同的404

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Run Code Online (Sandbox Code Playgroud)

我的目录结构设置错了吗?我在settings.py中缺少必要的设置吗?任何帮助将非常感谢!谢谢!


编辑:

我接受了Mark的建议并阅读了RequestContext.改变我的看法:

return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
Run Code Online (Sandbox Code Playgroud)

from django.template import RequestContext
...
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

得到/ static/url注册:

[27/Apr/2012 13:56:55] "GET /static/css/styles.css HTTP/1.1" 200 19
Run Code Online (Sandbox Code Playgroud)

这解决了这个问题.

Mar*_*vin 10

为了使用STATIC_URL模板,你需要确保你使用的是RequestContext同一起加入'django.core.context_processors.static'TEMPLATE_CONTEXT_PROCESSORS.如果您使用render快捷方式,这将为您完成.如果您不使用a,RequestContext则可以使用模板标记库中{% get_static_prefix %}staticfiles模板标记.这在以下文档中有详细说明:https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#other-helpers