如何通过按钮获取图像ID以在views.py中使用它?

时间:2019-01-28 04:08:23

标签: python html django

我对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 %}

1 个答案:

答案 0 :(得分:0)

您可以将id添加到每个评论中,使其独特,例如添加帖子pk和帖子中的评论数(例如

POST 6
comment-1
comment-2
comment-3 <-- This comment would have the id P6C3

然后在您的重定向功能中,您只需执行

redirect(newsfeed + '#' + comment_id)

这将滚动到新注释中。