[英]How to get the image id via a button to use it in views.py?
我对Django和Generall编码还很陌生,我正在尝试构建Instagram克隆..所以我的问题是..我如何评论newsfeed上的帖子(每个用户上传的所有图片的列表) ,而不离开新闻源?
所以我的方法是给每个发送按钮一个ID? 或名字? 并以某种方式在我的views.py中使用它
views.py:
def newsfeed(request):
images = Image.objects.all().order_by('-pub_date')
if request.method == 'POST':
c_form = CommentForm(request.POST)
if c_form.is_valid():
new_comment = c_form.save(commit=False)
new_comment.owner = request.user
new_comment.image = #here should be something that points to the image i'm commenting on
c_form.save()
return redirect('upload_img:newsfeed')
else:
c_form = CommentForm()
context = {'images_temp': images, 'c_form': c_form}
return render(request, 'newsfeed.html', context)
models.py:
class Comment(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
image = models.ForeignKey(Image, on_delete=models.CASCADE, default=1)
text = models.CharField(max_length=225)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s comments on %s image' % (self.owner, self.image.owner)
newsfeed.html:
{% for image in images_temp %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ c_form|crispy }}
<button name="{{ image.image }}" type="submit" class="btn btn-primary"><i class="fas fa-paper-plane"></i></button>
</form>
{% endfor %}
您可以将ID添加到每个评论中,使其具有独特性,例如添加帖子pk和帖子中评论的数量,例如
POST 6
comment-1
comment-2
comment-3 <-- This comment would have the id P6C3
然后,在重定向功能中,您只需
redirect(newsfeed + '#' + comment_id)
这将滚动到新评论中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.