Receiving 404 error when trying to load static urls directly in Django

♀尐吖头ヾ 提交于 2019-12-24 15:25:26

问题


When I visit the url of my static files (http://127.0.0.1:8000/site_media/static/css/site_base.css) I receive a 404 error message.

404 from the log

[27/Oct/2012 14:14:54] "GET /site_media/static/js/libs/modernizr-2.5.2.min.js HTTP/1.1" 404 1716
[27/Oct/2012 14:34:20] "GET /site_media/static/css/site_base.css HTTP/1.1" 404 1677

Directory Structure

mysite
    |-- manage.py
    |-- mysite
         |-- settings
             |-- base.py
             |-- dev.py
             |-- prod.py
    |-- site_media
       |-- static
           |-- css
               |-- site_base.css

site_base.html

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

settings

TEMPLATE_CONTEXT_PROCESSORS = [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.static",
]

STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
]

STATIC_URL = "/site_media/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")

Updated:

urls.py

from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^profile/', include('profiles.urls')),
)

urlpatterns += staticfiles_urlpatterns()

回答1:


Short answer

Django does not serve STATIC_ROOT on STATIC_URL, unless you tell it too.

Long answer

This should be a FAQ, here's an article about using django.contrib.staticfiles right (disclamer: written by me, feedback appreciated). It's like the documentation but tries to be shorter and more pragmatic.




回答2:


use <link rel="stylesheet" href="{{ STATIC_URL }}css/site_base.css" /> instead of

<link href="{%static 'css/style.css'%}" rel="stylesheet"> and make sure your value is STATIC_URL = '/static/' in the settings.py



来源:https://stackoverflow.com/questions/13103138/receiving-404-error-when-trying-to-load-static-urls-directly-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!