This is my Model Post where i want to uplaod multiple pictures for a specific post,so i have created foreign key from PostPicture to Post .
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
# image = models.FileField(null = True, blank=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
#code for Thumbnail
# image = models.ImageField(upload_to = "media", default='DEFAULT VALUE')
image_thumbnail = ProcessedImageField(upload_to = "thumbnail",
processors = [ResizeToFill(100,50)],format = 'JPEG',options = {'quality':60},default='DEFAULT VALUE')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
#code for uploading multiple images
class PostPicture(models.Model):
picture =models.ImageField(upload_to="blog_images", blank=True)
postid =models.ForeignKey(Post,on_delete=models.CASCADE,related_name='pictures')
This is my template code where i am iterating through the pictures and trying to show them.
{% for i in post.pictures.all %}
<img src = "{{ post.pictures.url }}" height = "200", width="200"/>
{% endfor %}
This is the views.py
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form}
)
I am using admin to add the blog post , attaching ss to have a look at the admin.![ ]1
This is the output on the UI, i am not getting the images to show up here.
I am also adding screenshot of directory : Can anyone help me ,where i am going wrong
The template is not right.
You're using the incorrect variable for src
inside the for-loop:
{% for i in post.pictures.all %}
<img src = "{{ i.picture.url }}" height = "200", width="200"/>
{% endfor %}