8

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 necessary settings in settings.py file. But unfortunately my code is unable to serve the css file, i mean the concept of serving css files is not working. I googled a lot and gone through the django main doc tutorials and made changes according to them,and still doesn't works so approached SO and pasted my entire code below

Structure of project folder

 personnel_blog
      |____personnel_blog
      |____manage.py  |  
                      |____media
                      |____static
                      |       |____css
                      |             |____personnel_blog_hm.css 
                      |____template 
                      |        |____home_page.html
                      |____settings.py
                      |____urls.py
                      |____views.py
                      |____wsgi.py         

Some of my settings.py file settings are below

settings.py

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

STATICFILES_DIRS = (
                    os.path.join(PROJECT_DIR,'static'),
    # 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.
)
TEMPLATE_DIRS = (
                 os.path.join(PROJECT_DIR,'templates')
)
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
)

urls.py

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

urlpatterns = patterns('',
     url(r'^$', 'personnel_blog.views.home_page'),
     url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),
        url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True }),

)

views.py

from django.shortcuts import render_to_response

def home_page(request):
    return render_to_response("home_page.html")

home_page.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
  <head>
    <link rel="stylesheet" href="{{ STATIC_URL }}css/personnel_blog_hm.css" type="text/css">
  </head>
  <body>
   <p>Hello !</p>
   <a href="/" target="_top">Home</a>
  </body> 
</html>  

personnel_blog_hm.css

body { background-color:green; }
p {color:blue;background-color:green;padding-left:20px;}

So above is my code, can anyone please let me know whats wrong in the settigns.py file or other py files ?

Whether need to do any other additional settings in the above code ?

so can anyone please adjust my code and make necessary changes so that i cam move forward and make my first step in web designing ..... :)

LtWorf
  • 7,286
  • 6
  • 31
  • 45
Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313

5 Answers5

12

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()
catherine
  • 22,492
  • 12
  • 61
  • 85
  • Exception Type: NameError Exception Value: name 'static' is not defined – Shiva Krishna Bavandla Feb 26 '13 at 06:04
  • yeah now after importing,i am not getting the error, but css is not working as same – Shiva Krishna Bavandla Feb 26 '13 at 06:09
  • settings file is same in the directory where static folder exists as i have mentioned in the project structue above, yes i have edited PROJECT_DIR with your code – Shiva Krishna Bavandla Feb 26 '13 at 06:16
  • this is my terminal response : Django version 1.4.3, using settings 'personnel_blog.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [26/Feb/2013 11:39:59] "GET / HTTP/1.1" 200 938 [26/Feb/2013 11:39:59] "GET /css/personnel_blog_hm.css HTTP/1.1" 404 2334 [26/Feb/2013 11:40:00] "GET / HTTP/1.1" 200 938 [26/Feb/2013 11:40:01] "GET /css/personnel_blog_hm.css HTTP/1.1" 404 2334 – Shiva Krishna Bavandla Feb 26 '13 at 06:19
  • ok I noticed now, you didn't put something in STATICFILES_DIRS – catherine Feb 26 '13 at 06:38
  • these are the setting STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static'), ) – Shiva Krishna Bavandla Feb 26 '13 at 06:39
  • it must be staticfiles not static – catherine Feb 26 '13 at 06:41
  • I am extremely sorry i dint get you , what to do now in these situation ? – Shiva Krishna Bavandla Feb 26 '13 at 06:42
  • change static folder to staticfiles because Django has default static folder for collectstatic so don't name your folder as static – catherine Feb 26 '13 at 06:42
  • k i changed the static folder to staticfiles in all the settings where static exists like below STATIC_ROOT = os.path.join(PROJECT_DIR,'staticfiles'), STATIC_URL = '/staticfiles/', STATICFILES_DIRS = (os.path.join(PROJECT_DIR,'staticfiles'),) and i hti the browser but not working as usually – Shiva Krishna Bavandla Feb 26 '13 at 06:47
  • no, just change only STATICFILES_DIRS. We are not understanding here. Just change only the STATICFILES_DIRS, do not change your static and media – catherine Feb 26 '13 at 06:48
  • k i have changed as you instructed, static and media folder names remains same and changed only the STATICFILES_DIRS as (os.path.join(PROJECT_DIR,'staticfiles'),) – Shiva Krishna Bavandla Feb 26 '13 at 06:52
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25122/discussion-between-shiva-krishna-and-catherine) – Shiva Krishna Bavandla Feb 26 '13 at 06:56
  • catherin is it working for u ? after updating the base.html file ?, i am not seeing any result here, also i am getting 500 template does n't exist after running the server from the folder inside that has sent by you – Shiva Krishna Bavandla Feb 26 '13 at 07:36
  • yeah, its working on me, "background:green". did you copy all the files? because I change something in the settings and I rename the folder into staticfiles – catherine Feb 26 '13 at 07:38
  • yeah i had copied entire folder that has sent by you at some other place and run the server directly inside from it – Shiva Krishna Bavandla Feb 26 '13 at 07:39
  • Oh wait did you change the database settings because I change it to sqlite3 – catherine Feb 26 '13 at 07:41
  • no no i dint changed anything, just copied and run the server from inside the folder personnel_blog and receiving the raise TemplateDoesNotExist(name) TemplateDoesNotExist: 500.html error – Shiva Krishna Bavandla Feb 26 '13 at 07:45
  • DEBUG=True and change the database settings like yours. – catherine Feb 26 '13 at 07:46
  • Sorry, your getting that error because you don't have 404 template. I think I change something on the DEBUG – catherine Feb 26 '13 at 07:47
  • 1
    Yup finally it worked after changing Debug value false to true and really thanks after for supporting by sparing your time – Shiva Krishna Bavandla Feb 26 '13 at 08:00
  • These settings are working for css files but when i tried to insert an image in home_page.html as Smiley face ... its showing a broken image and when i inspected the image path using firebug the path is /static/images/log.jpg which is correct, but y i am seeing broken image ? – Shiva Krishna Bavandla Feb 26 '13 at 10:14
1

Try changing your STATICFILES_DIRS setting to

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR,'static'),
)
arulmr
  • 8,620
  • 9
  • 54
  • 69
0

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

Alireza Savand
  • 3,462
  • 3
  • 26
  • 36
Frantz Romain
  • 836
  • 1
  • 6
  • 14
0

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

def home_page(request):
    return render_to_response("home_page.html", {}, context_instance=RequestContext(request))
Jack Shedd
  • 3,501
  • 20
  • 27
  • :k i have tried and edited my views file with the above code and still same result(css not working body color is not changed). Sorry many are trying to help me, but this is really wierd issue that not working and frustating me actually, whether this problem will be caused due to any installation errors/problems too ? – Shiva Krishna Bavandla Feb 26 '13 at 07:20
  • If you've done the above, check the generated HTML and make sure that {{ STATIC_URL }} is being replaced correctly. If it is, look at what happens when you visit http://127.0.0.1:8000/static/ in your browser. Does it generate a 500 error? – Jack Shedd Feb 26 '13 at 07:22
  • this is the line in html and reponse Page not found (404) Request Method: GET Request URL: http://localhost:8000/static/ – Shiva Krishna Bavandla Feb 26 '13 at 07:26
  • No, the HTML as seen when you visit with your web browser. – Jack Shedd Feb 26 '13 at 07:28
0

Try running this $ python manage.py collectstatic

You can check documentation here

Made4uo
  • 76
  • 2