So i'm trying to render an image from a model. The model is created successfully with the image but when I try to render it in template/home.html it doesn't show up for some reason can anybody please help me with this I would really appreciate it!
models/Post.py
import uuid
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=255)
image = models.ImageField(upload_to='images')
body = models.TextField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.ManyToManyField(User, related_name="posts")
createdAt = models.DateField(auto_now_add=True)
updatedAt = models.DateField(auto_now=True)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta:
ordering = ['-createdAt', '-updatedAt']
def __str__(self):
return str(self.title)
views.py
from django.views import generic
from base.models import Post
# Create your views here.
class HomeView(generic.ListView):
model = Post
template_name = 'home.html'
templates/home.html
{% load static %}
<h1>Posts</h1>
{% for post in object_list %}
<p>{{post.title}}</p>
<img src={{post.image}} alt="Image">
<p>{{post.description}}</p>
{% endfor %}
settings.py
...
...
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Base url to serve media files
MEDIA_URL = '/media/'
# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
STATIC_URL = '/static/'
I do not know what is happening and I would appreicete any sort of help.
CodePudding user response:
<img src={{post.image}} alt="Image"> -> <img src="{{post.image}}" alt="Image">
There should be double quotes.
CodePudding user response:
<img src={{post.image}} alt="Image">
is missing double quotes around the tags.
The correct code would be something like:
<img src="{{post.image}}" alt="Image">