Skip to content Skip to sidebar Skip to footer

Setting Up Django For Css File

I am a newbie to django and trying to create a personal tech blog. I am hosting on webfaction. I have setup the blog using this video. But the stylesheets are not working. I follo

Solution 1:

STATIC_ROOT needs to have a prepending slash /, i.e. /home...nothome...

DO NOT add the static directory to STATICFILES_DIRS. You have my permission to smack whomever advised you to do that with the nearest blunt object. The static directory should not exist at all in development, and in production it should only ever be created or modified via python manage.py collectstatic.

DO store your static resources in either each app's individual static directory or an entirely different project-level directory, i.e. this directory should not be the same as that for MEDIA_ROOT or STATIC_ROOT. Then, add this directory to STATICFILES_DIRS.

In Django 1.4+ you should use the {% static %} template tag in your templates:

{% load staticfrom staticfiles %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />

This will automatically append the STATIC_URL portion of the URL for you, so the path parameter you provide should be relative to that.

In Django 1.3, you'd use {{ STATIC_URL }} after ensuring that 'django.core.context_processors.static' appears somewhere in your TEMPLATE_CONTEXT_PROCESSORS setting. Your views will also need to utilize RequestContext, which means using either class-based views, the render method, or passing context_instance=RequestContext(request) to render_to_response.

If you want Django to serve static files in development for ease, you can add the following to the end of your urls.py:

from django.contrib.staticfiles.urlsimport staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

This will not work in a production enviroment (DEBUG=False). For production, you need to run python manage.py collectstatic and then have your frontend webserver (nginx, Apache, etc.) serve the directory at STATIC_URL.

Solution 2:

You have defined STATIC_URL in settings; you should use it in your html templates

<link rel="stylesheet"type="text/css" href="{{ STATIC_URL }}/style/style.css">

That should work as long as you haven't removed anything from TEMPLATE_CONTEXT_PROCESSORS in settings.

You could also look into using an asset manager to generate all of the JS and CSS links in your templates for you, rather than writing them yourself. django-pipeline is really good, and can handle things like JS and CSS concatenation and compression for you as well.

Post a Comment for "Setting Up Django For Css File"