Question

I'm really confused. I'm using Django 1.4 and I've been searching for this the whole day, and it seems like that everything has changed in the latest version of Django and the documentation isn't helpful at all (at least to me). Please help me attach a CSS file to my template.

So, this is my settings.py file

STATIC_ROOT = 'F:/Django/mysite/mysite/static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    "F:/Django/mysite/mysite/static/",
)

Here's my urls

from django.conf.urls.defaults import *
from myste.views import hello, home
from django.views.static import *
from django.conf import settings

urlpatterns = patterns('',
    ('^home/$', home)
)

This is the views

def home(request):
    return render_to_response('home.html', locals(),context_instance=RequestContext(request))

And finally this is the template (home.html)

url: {{ STATIC_URL }}

Oh, and I'm not sure what I should put in my TEMPLATE_CONTEXT_PROCESSORS but this is it so far.

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
)

And this is the output I get when running the server

url:

I know there might be some huge mistakes in these codes, but that's because I've been reading different sources for different django versions. And yes, I've read the documentations but as I said it didn't help me that much.

Was it helpful?

Solution

You don't seem to have read the instructions at all. The two important things to do are 1) ensure the static processor is in TEMPLATE_CONTEXT_PROCESSORS and 2) define some URLs to actually serve your static files in development.

None of this has "changed in the latest version". There were some improvements in the previous version, 1.3, but the basic principle is the same.

OTHER TIPS

STATIC_URL isn't in your local scope, so passing through locals() as your dictionary isn't going to help.

def home(request):
return render_to_response('home.html', {'STATIC_URL': settings.STATIC_URL},context_instance=RequestContext(request))

or you can use the new static tag available in 1.4 and avoid this particular problem in the template:

{% load static from staticfiles %}
url: {% static "/" %}

'django.core.context_processors.media', 'django.core.context_processors.static',

Those should both be in your TEMPLATE_CONTEXT_PROCESSORS as per this. This makes the STATIC_URL available in all contexts that use request context. If you really read the docs, and make sure you've set them to 1.4, you'll avoid a lot of these types of questions, and save yourself lots of headaches.

You may want to use render to save yourself some headaches and typing. I usually have just have it swapped out for render_to_request(blah) with render(request, context, template) which in this case would be render(request, locals(), 'home.html').

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top