1

I am sending my images from my web server Django like follows :

localhost:8000/media/images/foo.png 

My question is am I sending the images is the correct way? I think it is not necessary to send the server since I am the only one who serves the photographs. Any ideas, something like this media/images/foo.png. In order that in the img tag of HTML this is a relative path and not a link.

2 Answers 2

4

For serving images in Django,

First make sure that you have your MEDIA_ROOT and MEDIA_URL defined inside the settings.py file.

Now let's say you have a model, models.py

class SomeModel(models.Model): image = models.ImageField(upload_to = 'your_directory_inside_media') #Rest of the fields 

Next inside your views,

model_object = SomeModel.objects.get(...) #get an instance of model which has an ImageField context = {'image' : model_object.image } html = render(request , 'some_html.html' , context) 

And finally inside your HTML,

{% load static %} <img src="{% get_media_prefix %}{{ image.image }}"> 

Hope this helps. Thanks.

Sign up to request clarification or add additional context in comments.

6 Comments

But, I don't use views from django, I create an angular app and send that url to access to image
You can get the url by using "image.name" . It'll give you the complete URL.
but, why I need add {% load static %} If my data is save in media??
It wouldn't work without it. It even uses it in the documentation: docs.djangoproject.com/en/1.11/ref/templates/builtins/… .
You pointed out something interesting. Indeed, even I never though about it. But the original post didn't asked about this, otherwise this is something even I don't know anything about. I couldn't find an answer for this question anywhere, so I posted a question here myself.
|
0

Just some feedback after I struggled with a similar issue for hours. I overlooked a part of the documentation where to actually use{{ MEDIA_URL }} you must add 'django.template.context_processors.media' to the 'context_processors' list in settings.py

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.