Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django not serving static files

Tags:

python

django

I'm using Django==1.5.5 and My django app is structured as

--project/
----project/
------settings.py
------urls.py
----app1/
------models.py
------views.py
----staticfiles/
------style.css
----static/
------admin/
--------js/
--------css/
------style.css
----templates/
------header.html
------post.html
------footer.html
----manage.py

the /project/settings.py is

import os    
DEBUG = False
TEMPLATE_DEBUG = DEBUG    
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')    
ALLOWED_HOSTS = ['localhost', '127.0.0.1']    
MEDIA_ROOT = ''    
MEDIA_URL = ''    
SITE_ROOT = PROJECT_ROOT    
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')    
STATIC_URL = '/static/'    
STATICFILES_DIRS = (
    os.path.join(SITE_ROOT, 'staticfiles'),
)    
TEMPLATE_DIRS = (
    os.path.join(SITE_ROOT, 'templates'),
)

in header.html i trying use it as:

    <head>
        <title>My Site</title>
        {% load static from staticfiles %}
        <link rel="stylesheet" href="{% static 'style.css' %}">
    </head>

But its not loading mysite.com/static/style.css and giving error 404

I ran python manage.py collectstatic to collect all static file.

Why its loading css file? any configuration missing?

Please suggest.

like image 750
uday.blob Avatar asked Dec 15 '13 11:12

uday.blob


1 Answers

I had the same problem and none of the answers I found worked. It turns out that there are a few parts that must be set up correctly for static files to work. Note: I'm using django 1.6 and this solution is for development not deployment.

Setting up static file dirs

django-admin.py startproject $site_name
mkdir $site_name/static
mkdir $site_name/static/css
mkdir $site_name/static/javascript
mkdir $site_name/static/images

your folder should look like this

$site_name/
    manage.py
    $site_name/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    static/
        css/
        javascript
        images/

edit the $site_name/$site_name/setting.py file and add

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS =( os.path.join(STATIC_ROOT, 'css/'),
                    os.path.join(STATIC_ROOT, 'javascript/'),
                    os.path.join(STATIC_ROOT, 'images/')
                  )

edit $site_name/$site_name/urls.py and add

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

using static urls

{% load staticfiles %}
<a href="{% static "banner.png" %}">
like image 135
lafferc Avatar answered Sep 24 '22 04:09

lafferc