Django: static file image URL paths breaks except

2019-08-11 20:45发布

I'm trying to setup my static file in development. I have an image located in polls/static/images/banner.jpg. When I navigate to 127.0.0.1:8000/ the banner shows up, but when I go to something like 127.0.0.1:8000/2ndpage the banner breaks.

my index (URL: 127.0.0.1:8000/) template contains:

{% include 'polls/header.html' %}

The URL for the banner http://127.0.0.1:8000/static/images/banner.jpg

my 2ndpage template also contains:

{% include 'polls/header.html' %}

But the URL for the banner changes to http://127.0.0.1:8000/2ndpage/images/banner.jpg

my polls/header.html template:

<img src="{{ STATIC_URL }}images/gcs_banner.jpg" />

urls.py

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns('polls.views',
    url(r'^$', 'index'),
    url(r'^2ndpage/$', '2ndindex'))

views.py

def index(request):
    ...
    return render_to_response('polls/index.html', {'latest_people_list':     latest_people_list,}, context_instance = RequestContext(request))

def 2ndpage(request, people_id):
    ...
    return render_to_response('index/detail.html', {'people': p}, context_instance = RequestContext(request))

Why does the URL change from ../static/.. to ../2ndpage/..? How do I fix this so that when I use {% include 'polls/header.html' %} the banner always shows up?

1条回答
手持菜刀,她持情操
2楼-- · 2019-08-11 21:27

I think that in the second page, {{ STATIC_URL }} is not defined. Thus, src ends up with images/gcs_banner.jpg. Which is a relative url because it's not prefixed with a slash. It is then converted to a absolute path using the current absolute url: /2ndpage/images/gcs_banner.jpg.

{{ STATIC_URL }} is probably set by a context processor - at least that how it works in my projects. Context processors are actually a feature from RequestContext. When a view returns response without RequestContext then the context processors are not run, e.g.:

from django import shortcuts 
# ....
    return shortcuts.render_to_response(template_name, context)

This is an example of explicit usage of RequestContext with render_to_response():

from django import shortcuts 
from django import template
# ....
    return shortcuts.render_to_response(template_name, context, 
        context_instance=template.RequestContext(request))

That said, Django 1.3 provides a better shortcut with implicit usage of RequestContext, render():

from django import shortcuts 
# ....
    return shortcuts.render(request, template_name, context)
查看更多
登录 后发表回答