Home > Software design >  How to load static file of a model in a html templates
How to load static file of a model in a html templates

Time:12-15

I have a static file structure like this -----> static/images/article_images/images.png

here's my settings.py

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

here's what I tried:

{% extends "base.html" %}

{% block content %}
 {% load static %} ---> i have this in my base.html
    <div  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 %}

here's my model.

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

CodePudding user response:

Static files are not bound by model. In your templates you should be using:

 {% extends "base.html" %}
{% load static %} ---> include this line after extends in every template that require static files.
 {% block content %}
 
<div  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 %}

CodePudding user response:

Just remove article_image_path function from models.

And then, add path name in model field image directly.

For ex:

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.

And in settings.py file just add media settings:

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

In your main urls.py file, just add this:

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

EX:

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

Note: don't forget to migrate the model after making changes in image field.

  • Related