Как загрузить статический файл модели в html-шаблоны

У меня статическая структура файлов выглядит так -----> static/images/article_images/images.png

вот мой settings.py

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
    # '/css/',
    # 'images/article_image/',
]

вот что я попробовал:

{% extends "base.html" %}

{% block content %}
 {% load static %} ---> i have this in my base.html
    <div class="article-block" method="GET">
        {% for article in articles %}

        <!-- <img src="{{ article.image }}" alt="Article image"> -->
        <img src="{% static '{{article.image}}' %}" alt="Article image">
        <h2>{{ article.title }}</h2>
        <p>{{ article.content }}</p>
        {% endfor %}
    </div>
{% endblock %}

вот моя модель.

from django.db import models
from django.conf import settings

def article_image_path(instance, filename):
    return f"static/images/article_image/{filename}"

class Article(models.Model):
    title = models.CharField(max_length=250)
    content = models.CharField(max_length=1000)
    image = models.ImageField(default='', upload_to=article_image_path)

    def __str__(self):
        return self.title

Статические файлы не связаны model. В своих шаблонах вы должны использовать:

 {% extends "base.html" %}
{% load static %} ---> include this line after extends in every template that require static files.
 {% block content %}
 
<div class="article-block" method="GET">
    {% for article in articles %}

    <img src="{{ article.image }}" alt="Article image"/> <-- Use this if image is stored inside article model

    <img src="{% static 'images/image_name.png' %}"   alt="Article image"/> <--use this if your image is stored statically
    
    <h2>{{ article.title }}</h2>
    <p>{{ article.content }}</p>
    {% endfor %}
</div>
{% endblock %}

Просто удалите функцию article_image_path из моделей.

Затем добавьте path name непосредственно в изображение поля модели.

Например:

image = models.ImageField(default='', upload_to='images/') #path added here. uploaded images will store in this images folder. images folder will be created inside media folder automatically in your project root.

И в файле settings.py просто добавьте настройки медиа:

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

В вашем главном urls.py файле просто добавьте следующее:

+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) 

EX:

urlpatterns = [
 
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) #Added here

Примечание: не забудьте мигрировать модель после внесения изменений в поле image.

Вернуться на верх