V
V
Vladislav2019-04-04 16:48:39
Django
Vladislav, 2019-04-04 16:48:39

Why doesn't Django show media on localhost?

Everything is spelled out, the pillow is installed. Saving an image to a folder is no problem. But when I try to display the uploaded image on the page, I get "Not Found: /media/img.jpg" in the terminal.

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

models.py
class Post(models.Model):
  title = models.CharField(max_length=150, db_index=True)
  slug = models.SlugField(max_length=150, blank=True, unique=True)
  body = models.TextField(blank=True, db_index=True)
  tags = models.ManyToManyField('Tag', blank=True, related_name='posts')
  image = models.ImageField(blank=True)

Everything is written in url.py
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In template
{%extends 'blog/base_blog.html'%}
{%block content%}
  <h1 class="mt-5">
    {{post.title}}
  </h1>
  <p>{{post.body}}</p>
    {{post.image.url}}
    <img src="{{post.image.url}}"/>
{%endblock%}

If you simply write in the template
{{post.image.url}}
Then, the exact path to the /media/img.jpg file is displayed on the page
. I don’t understand the reason at all. The internet didn't help. Everywhere they do it like mine.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2019-04-05
@nitron_5

So, the error turned out to be rather stupid. I misread the documentation.
Line
was registered in the url.py of the application, but it was necessary to register it in the root url.py.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question