B
B
bituke2020-09-08 18:55:42
Django
bituke, 2020-09-08 18:55:42

Why aren't images shown from CharField in django?

The problem is this:
The folder where images are uploaded by a potential user is the media folder.

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    ]

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

And the folder from which images can be uploaded is just the static folder.
The problem is that I cannot display an image from the media folder in the template, because it is loaded only from the static folder. I tried adding this line to the root urls.py of the project:
from django.conf import settings
from django.conf.urls.static import static

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


But nothing helped.
Here's what it looks like in the template:

{% if latest_categories %}
    {% for a in latest_categories %}
      <a href="#">{{a.name_category}}</a>
      <img src="{{a.img_category.url}}">
    {% endfor %}
  {% else %}
    Категории не найдены.
  {% endif %}


The category name is displayed and the url of the image is correct, but django sees it as not a static file, which is why it does not display it. Here's what it looks like in the final html code:
<a href="#">fuckmybrain</a>
      <img src="/media/category/backg.jpg">
    
      <a href="#">Кирпичи</a>
      <img src="/media/category/d90f68079558e8edfd1cce75ffa0e04c.jpg">
    
      <a href="#">Металлопрокат</a>
      <img src="/media/category/7962256765.jpg">
    
      <a href="#">Пиломатериал</a>
      <img src="/media/category/%D0%9F%D0%B8%D0%BB%D0%BE%D0%BC%D0%B0%D1%82%D0%B5%D1%80%D0%B8%D0%B0%D0%BB.jpg">


Please help, I promise feedback.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tema_sun, 2020-09-08
@bituke

You added a line to urls.py to support STATIC_URL/STATIC_ROOT, but media files need support for MEDIA_URL/MEDIA_ROOT
https://docs.djangoproject.com/en/2.2/howto/static...

D
Dr. Bacon, 2020-09-08
@bacon

It never happened and here again, it makes sense to learn how to read the docks, well, or google https://docs.djangoproject.com/en/3.1/howto/static...
Threat, it remains to find out, what does CharField have to do with it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question