0

For a couple of days now I have been trying to setup my django project to run my html-template with an external css-file. So far, no succes....

I have installed staticfiles ( Im using django 1.2.4.) and put the 'staticfiles' in INSTALLED_APPS within settings.py and added the following code:

STATIC_ROOT=os.path.join(os.path.abspath(os.path.dirname(file)), "static")

STATIC_URL='/static/'

My css-file is located under /static/css/stylesheet.css

My html-template has the link

link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/stylesheet"

After running the server, the page loads just fine. However django cant find my stylesheet...

What am I doing wrong here?

3 Answers 3

1

The static root and url doesn't actually host the files. The static serve option (in the urls.py) mentioned previously is a good option for development and learning, but if you move to a deployment server you should use the static hosting provided by your webserver.

The way the static folders is intended to work is that you add the path locations for each app, project, etc to the static directories setting in settings.py. Then, when you run the command "django-admin.py collectstatic" django pulls all of your directories into your static root. After the first time you run collectstatic, only files that have changed will be copied again. This consolidates multiple static directories into one common place.

Static files documentation

Sign up to request clarification or add additional context in comments.

Comments

0

You need to pass the RequestContext to the view, so it will run through the staticfiles' CONTEXT_PROCESSORS (which includes the STATIC_URL variable).

from django.template.context import RequestContext

context = {'my_other_context': 1}
render_to_response('your_template.html',
                   context_instance=RequestContext(request, context))

2 Comments

Thank you for your response, but I dont understand this. Where is the CONTEXT_PROCESSORS supposed to be placed? 'my_other_context'...what does this mean?
In your settings.py you should have a CONTEXT_PROCESSORS setting which will include the path to the staticfiles context processor. The my_other_context is just an example of some additional context you may want to pass to the template.
0

I would recommend you to just use a django.views.static.serve instance like this in the url.py file:

(r'^(?P<path>.*)$', 'django.views.static.serve',{'document_root': '/path/to/css/'}),

2 Comments

Thanks. When I use this, do I have to remove the 'staticfiles' from my INSTALLED_APPS ?
Yes you can remove it if you want, because django.views.static.serve takes care of what is needed to serve the static content

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.