Reputation: 13
Currently using Django 1.9. Image files in my model are uploading properly to
project\media\FILEPATH.jpg
However, images are attempting to be displayed using the filepath without \media. For example, when I go to my localhost http://127.0.0.1:8000/media/FILEPATH.jpg in my browser, I get a 404 because Django's get request is looking for:
project\FILEPATH.jpg
How do I get django to serve my media files properly with \media\?
More information if it may be of any use:
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.dirname(os.path.join(BASE_DIR, 'media'))
model:
image = models.ImageField(upload_to='media', blank='true')
project urls.py I have the following after urlpatterns as per the documentation:
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Thank you for any help!
models.py
class Post(models.Model):
ptype = models.ForeignKey('blog.Type', related_name='posts')
title = models.CharField(max_length = 100)
text = models.TextField()
published_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
class Image(models.Model):
post = models.ForeignKey('blog.Post', related_name='images')
image = models.ImageField(upload_to='media', blank='true')
views.py
class Posts(generic.ListView):
model = Post
context_object_name = 'posts'
template_name = 'blog/posts.html'
posts.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<p><a href = "{% url 'blog:postdetail' pk=post.pk %}">{{post.title}}</a></p>
<p>{{post.text}}</p>
{% for image in post.image_set.all %}
<img src="{{ image.image.url }}">
{% endfor %}
{% endfor %}
{% endblock %}
Upvotes: 1
Views: 2547
Reputation: 46
Ok
When your declare the upload on the model, Django detect automatically that your route of media is BASE_DIR/media, when you put somthing in upload_to on the model you are declare that this image have to saved on BASE_DIR/media/something
Example: if I want to save the user's images into media I have to make this on the model
image = models.ImageField(upload_to='users/', blank='true')
and my image will saved on localhost/media/users/FILEPATH.jpg
All this url after media/ is saved on your field of 'image' so your image field will say just 'users/FILEPATH.jpg' but not the localhost/media/
Thats why you need to write the /media/ in you src
<img src="/media/{{ image.image }}">
and if you save the image on the field named 'image' your will not need the .url.
Try it.
Upvotes: 3