[英]How can i add a "like" button in a Django class ListView
我正在尝试在我网站的帖子应用程序中添加一个“喜欢”按钮,但因为我想将它添加到包含其余帖子条目的 ListView 中,并且每个人都可以选择评论我有添加了一个 Formixin 来这样做,所以,现在我无法为类似按钮添加另一个表单,因为这意味着两个帖子请求......所以我没有找到明确的解决方案......我在这里和那里阅读了有关使用 AJAX 的内容或 Json 技术,但作为我的新编程,我有点卡在其中……有人可以提供任何提示吗?
While using AJAX (javascript XHR requests) would be the proper way so the page doesn't need to be refreshed when just clicking a like button, you can do it without AJAX.虽然使用 AJAX(javascript XHR 请求)将是正确的方法,因此只需单击一个喜欢按钮就不需要刷新页面,但您可以在没有 AJAX 的情况下进行。
On the HTML side of things, you can have multiple forms ( <form>
), one for each post, which have a hidden input field that's the post's id.在 HTML 方面,您可以有多个表单 ( <form>
),每个帖子一个,它们有一个隐藏的输入字段,即帖子的 id。 You have set that explicitly in the HTML template, eg您已在 HTML 模板中明确设置,例如
{% for post in post_list %}
<h3>{{ post.title }}</h3>
<p>{{ post.summary }}</p>
<form method="post">
{% csrf_token %}
<input type="hidden" value="{{ post.id }}" name="{{ form.id.html_name }}">
<input type="submit">Like</input>
</form>
{% endfor %}
So basically you're reusing the form multiple times, changing the "value" attribute to match the post.所以基本上你多次重复使用表单,更改“值”属性以匹配帖子。
Adding the FormMixin
to your view is the right step, just use the form_class
to a custom LikeForm
with just one field that's an IntegerField called id
.将FormMixin
添加到您的视图是正确的步骤,只需将form_class
用于自定义LikeForm
其中只有一个名为id
的 IntegerField 字段。
By adding the FormMixin
you get the form_valid()
method, which you'll want to override to save the like:通过添加FormMixin
您将获得form_valid()
方法,您需要重写该方法以保存类似内容:
def form_valid(self, form):
id = form.cleaned_data['id']
try:
post = Post.objects.get(id=id)
except Post.DoesNotExist:
raise Http404
post.likes.add(self.request.user) # assuming likes is a m2m relation to user
return redirect('post_list') # this list view
Hopefully I am not so late, I had similar challenges trying to implement the same functionalities on my website.希望我没有那么晚,我在尝试在我的网站上实现相同的功能时遇到了类似的挑战。 I came to realize that each button id should be unique (Preferably the post id if blog), but the classes can be the same.我开始意识到每个按钮 id 应该是唯一的(如果是博客,最好是帖子 id),但类可以相同。 I was able to solve it.我能够解决它。 Here is an article I wrote on medium recently on the steps I followed to so get this working you can check it out here这是我最近在媒体上写的一篇关于我遵循的步骤的文章,因此您可以在此处查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.