1

I want Django to display an image when accessed. For example, I want to display only the image as a response, such as when accessing the image below. And I want to do the URL as a normal URL without using .jpeg or .png.

Sample:

sample

But now, no matter what method you try, it doesn't work.

from django.http import HttpResponse import os from django.core.files import File import codecs def image(request): file_name = os.path.join( os.path.dirname(__file__), '12.jpg' ) try: with open(file_name, "rb") as f: a = f.read() return HttpResponse(a, content_type="image/jpeg") except IOError: red = Image.new('RGBA', (1, 1), (255, 0, 0, 0)) response = HttpResponse(content_type="image/jpeg") red.save(response, "JPEG") return response urlpatterns = [ url('image', image) ] 

With the above code, the following error occurs.

'utf-8' codec can't decode byte 0xff in position 0: invalid start byte 
2
  • 1
    Please post the full traceback, not just its last line Commented Jan 13, 2020 at 10:41
  • 1
    Usernames are the new tags. Commented Jan 13, 2020 at 10:43

2 Answers 2

1

Simply use FileResponse:

from django.http import FileResponse def image(response): img = open('path/to/12.jpg', 'rb') response = FileResponse(img) return response 
Sign up to request clarification or add additional context in comments.

Comments

0

The cause was my own middleware. There was no problem if I commented out. Thanks for those who have comments and those who have answered.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.