A
A
Alexander Bondarenko2019-11-23 13:02:46
Django
Alexander Bondarenko, 2019-11-23 13:02:46

Why is the image not being added via ImageField?

Doesn't find the image in the given path, writes that the file was not found.
5dd901b65bcdd690646329.jpeg
File: settings.py

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'news/image')

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'media'),)

urls.py file
from django.contrib import admin
from django.urls import path, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('mainApp.urls')),
    path('news/', include('news.urls')),
    path('webexample/', include('webexample.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

models.py file
from django.db import models

class Articles(models.Model):
    title=models.CharField(max_length=120)
    body=models.TextField()
    har=models.TextField(null=True)
    main_photo = models.ImageField(upload_to='image/', blank=True, height_field=None, width_field=None, max_length=100,null=True)
    date=models.DateTimeField()

    def __str__(self):
        return self.title

Image output:
{% extends "main/wrapper.html" %}
{% block content %}
  <h2 class="text-info">{{articles.title}}</h2>
  <h6 class="text-info">Опубликовано: {{articles.date|date:"Y-m-d в H:i:s"}} </h6>
  <p>{{articles.body|safe|linebreaks}}</p>
  <img src="{{articles.main_photo.url}}" alt="">
  <div>
    <h3>Характеристики:</h3>
    <p>{{articles.har|safe|linebreaks}}</p>
  </div>
{% endblock %}

The folder itself is created at the given path, and the picture is also there, but the path is written
127.0.0.1:8000/media/image/silver-imac-displaying-...
and writes file not found

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Bondarenko, 2019-11-23
@bond_1013

I replaced urlpatterns in the urls.py file with the following code and it all worked

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('mainApp.urls')),
    path('news/', include('news.urls')),
    path('webexample/', include('webexample.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question