Django STATIC_URL is not working

2020-02-09 08:06发布

Django version is 1.4. I had read the official document, and googled my problem.

first I had followed the official document Managing static files added this in settings.py:

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',
)

In my template:

<link href="{{ STATIC_URL }}css/main.css" ...>

but, in my broswer is:

<link href="css/main.css" ...> (Just render `STATIC_URL` as empty)

My settings is:

STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'

in my views

def register(request):
    ...
    return render_to_response('register.html', {'errors':errors})

5条回答
SAY GOODBYE
2楼-- · 2020-02-09 08:29

In Django 1.4 you should use static templatetag1.

Try:

{% load staticfiles %}
<link href="{% static "css/main.css" %} ...>
查看更多
叼着烟拽天下
3楼-- · 2020-02-09 08:34

Unfortunately, Django's render_to_response shortcut by default uses normal template context, which does not include context processors and all their fancy and useful stuff like STATIC_URL. You need to use RequestContext, which does precicely that.

This can be called by using the new render (available since Django 1.3):

from django.shortcuts import render

return render(request, 'register.html', {'errors':errors})

In Django 1.2 and older, you need to supply the context explicitly:

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('register.html', {'errors':errors},
    context_instance=RequestContext(request))
查看更多
▲ chillily
4楼-- · 2020-02-09 08:36

dont you need this in your return statement?:

context_instance=RequestContext(request)

查看更多
该账号已被封号
5楼-- · 2020-02-09 08:47

I realize this has already been answered but I wanted to provide another answer in the event that STATIC_URL still renders as empty even when using RequestContext.

If you are running the development server remember to start the server with the insecure flag to have the server serve your static files:

python manage.py runserver --insecure
查看更多
祖国的老花朵
6楼-- · 2020-02-09 08:48

Change

return render_to_response('register.html', 'errors':errors)

to

return render_to_response('register.html', {'errors': errors}, RequestContext(request))
查看更多
登录 后发表回答