0

I am trying to render a transparent image, from one of my views in django.

Here is the HTML -

// other html stuff
< img src="{% url 'minor_url_test' }" alt="Smiley face"  height="1" width="1">
// other html stuff

urls.py -

url(r'^minor_image_url/$', 'minor_url_test', name='minor_url_test')

views.py -

def minor_url_test(request):
    TRANSPARENT_1_PIXEL_GIF = "\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b"

    import ipdb
    ipdb.set_trace()
    return HttpResponse(TRANSPARENT_1_PIXEL_GIF, content_type='image/gif')

I serve the html file, from a different view, all the html contents are served properly, but not the image. and the minor_url_test view is never hit.

What am I doing wrong?

Ram Kumar
  • 590
  • 2
  • 10
  • 27

1 Answers1

0

The code you posted seems to be fine, however, it has a few minor issues:

  • Don't put a space between < and img. It should be: <img ...> instead.
  • Image files should always end with a proper extension. The URL should thus be: minor_image_url.gif, however, most modern browsers don't care.
  • The view is most likely imported improperly. You will need to provide the full path (e.g. my_app.views.minor_url_test. However, I prefer to import the view:

Code

from my_app import views
urlpatterns = patterns('',
    # ...
    url(r'^minor_image_url/$', views.minor_url_test, name='minor_url_test'),
)

This has the advantage, that the console will print an error in case the view doesn't exist or couldn't be found.

If none of my solutions has helped you, please improve your question:

  • Show the HTML code the web browser get. Almost all browsers have "show source" or "inspect source" option. The code the web browser gets should be <img src="/minor_image_url/" alt="Smiley face" height="1" width="1">
  • Restart the web server (press crtl + C and type ./manage runserver on linux/mac), visit the webpage, that has the IMG tag in it (and only this), and post the complete console output.
  • Visit http://your_server/minor_image_url/ manually. If a django error page appears, it'll help you fix your problem. If you don't understand it, post what it said. Make also sure your browser somehow highlights images (for example, firefox will show a gray background instead of a white page. That way, you can be sure you're dealing with an image and not an empty page).
Community
  • 1
  • 1
Matt3o12
  • 4,192
  • 6
  • 32
  • 47