简体   繁体   中英

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.

HTML

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. You have set that explicitly in the HTML template, eg

{% 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.

Django Form

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 .

View

By adding the FormMixin you get the form_valid() method, which you'll want to override to save the like:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM