Saturday, May 5, 2012

[Django] Add CSS files

I can't find any tutorial that specifically tells what how to add CSS files on Django project so after a long adventure and a lot of readings and trial and errors here how I did it:

1. open your and locate the MEDIA_ROOT and MEDIA_URL
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'

If you're wondering what is os.path.join and PROJECT_ROOT then I'll explain it.

On top of the file ( add the following code:
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

so based on the codes above, os.path.join and PROJECT_ROOT gets the current path where your project was located in your drive/server/etc.

The "media" is simple the folder where your css files will be saved.

moving on...

2. open your template. in my case my template name is base.html
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/style.css" />

3. open your the one inside your project not on your app
from mysite import settings

urlpatterns += patterns('',
    url(r'(?:.*?/)?(?P(css)/.+)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),

The "mysite" is the name of the folder of your project. Remember that it's case sensitive. If your folder is "MySite" then it should be "from MySite import settings"


that's it! if you experience some errors feel free to leave a comment. i might forget to include other settings or code because I'm still new to Django.

have a good day!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...