'How to add an image along with a post in Django from the admin panel so it'll show in my templates
I created a model for the post, I don't have issues with the body(blog post)but with the images how should I do it such that it'll reflect at the template
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.CharField(max_length=1000000)
created_at = models.DateTimeField(default=datetime.now, blank=True)
posted_by = models.CharField(max_length=50, default=False)
image1 = models.ImageField(upload_to='images/', default=False)
image2 = models.ImageField(upload_to='images/', default=False)
image3 = models.ImageField(upload_to='images/', default=False)
def __str__(self):
return str(self.title)
This is my views page, I'm still confused how I'll relate the Class with the image1,image2, image3 variable .....Pls help Though I came up with this
def postpage(request, pk):
indPost = Post.objects.get(id=pk)
comment = indPost.comments.filter(active=True)
imageone = Post.objects.fifth()
imagetwo = Post.objects.sixth()
imagethree = Post.objects.seventh()
new_comment = None
path = settings.MEDIA_ROOT
img_list = os.listdir(path + '/images')
context = {'imageone': imageone, 'imagetwo': imagetwo, 'imagethree': imagethree}
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.indPost = indPost
new_comment.save()
return HttpResponseRedirect('/success')
else:
comment_form = CommentForm()
return render(request, 'postpage.html', {'indpost': indPost, 'comments': comment, 'comment_form': comment_form})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
