简体   繁体   中英

Django's STATIC_URL and Ajax requests

My web page makes an AJAX call to the server to dynamically select an image for display. The problem I've run into is that the STATIC_URL variable evaluates to an empty string, and so the image fails to load.

This is the code I'm using the render the path to the image.

text = "<img src=\"{{ STATIC_URL }}/images/%s\"> %s" % (ball_file, val)
t = Template(text)
tt = t.render(Context())

Any help would be much appreciated.

Why even use Template ? Wouldn't this work ?

from django.conf import settings

text = u'<img src="%simages/%s"> %s' % (settings.STATIC_URL, ball_file, val)

Note that STATIC_URL should contain the trailing slash, hence %simages in this example instead of %s/images .

You haven't supplied any context for that template, so naturally all variables including STATIC_URL will resolve to empty. If you use a RequestContext, then the context processors will be run first, and therefore extra items like the static URL (and the user, and various other things) will be available.

However I agree with jpic, you'd be better off doing this directly in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM