Skip to content Skip to sidebar Skip to footer

Unable To Serve Static Files Like Css, Js In Django Python

I am very new to django, and gone through tutorial for many days , i have started building a small website using django and trying to serve a css file by arranging all the necessar

Solution 1:

base.html

{% load static %}

<link rel="stylesheet" href="{% static 'css/personnel_blog_hm.css' %}"type="text/css">

settings

PROJECT_DIR  = os.path.dirname(__file__) 

MEDIA_ROOT = os.path.join(PROJECT_DIR,'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR,'static')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    # Put strings here, like"/home/html/static"or"C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

url

from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
     url(r'^$', 'personnel_blog.views.home_page'),
     url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

Solution 2:

Try changing your STATICFILES_DIRS setting to

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR,'static'),
)

Solution 3:

Your problem is related to this line:

return render_to_response("home_page.html")

Django's template engine requires two things to properly render a template.

  1. The template name
  2. A context variable

The context variable is a key/value dictionary listing all of the variables available to the template.

The render_to_response shortcut actually accepts two different context variable parameters.

You're missing both.

Without these variables, the template doesn't have ANY variables available to it. So your {{ STATIC_URL }} template variable is probably blank.

To correct, try this:

from django.shortcuts import render_to_response
from django.template import RequestContext

defhome_page(request):
    return render_to_response("home_page.html", {}, context_instance=RequestContext(request))

Solution 4:

in settings.py try.

PROJECT_DIR  = os.path.dirname(__file__)
...
MEDIA_ROOT = os.path.join(PROJECT_DIR,'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR,'static')
STATIC_URL = '/static/'

my settings.py file is usually in same directory as static directory

Post a Comment for "Unable To Serve Static Files Like Css, Js In Django Python"