【问题标题】:LIKE button in a Django projectDjango 项目中的 LIKE 按钮
【发布时间】:2022-01-04 14:46:14
【问题描述】:

在 Django 项目(分页博客)中有一个视图负责点赞的工作方式。它有一个缺点:当用户喜欢帖子时,它会被重定向到网站的主页。我该如何解决这个问题,以便用户留在他们喜欢的页面上。

views.py

class AddLikeView(View):
     def post(self, request, *args, **kwargs):
         blog_post_id = int(request.POST.get('blog_post_id'))
         user_id = int(request.POST.get('user_id'))
         url_from = request.POST.get('url_from')

         user_inst = User.objects.get(id=user_id)
         blog_post_inst = News.objects.get(id=blog_post_id)

         try:
             blog_like_inst = BlogLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst)
         except Exception as e:
              blog_like = BlogLikes(blog_post=blog_post_inst,
                          liked_by=user_inst,
                          like=True)
              blog_like.save()
         return redirect(url_from)

模板.py

<form action="{% if not is_liked_bool %}{% url 'add' %}{% else %}{% url 'remove' %}{% endif %}" method="post">
{% csrf_token %}
<input type="hidden" name="blog_post_id" value="{{ blog_post_id }}">
<input type="hidden" name="user_id" value="{% if user.is_authenticated %}{{ request.user.id }}{% else %}None{% endif %}">
<input type="hidden" name="url_from" value="{{ request.path }}">

{% if is_liked_bool %}
    <input type="hidden" name="blog_likes_id" value="{{ blog_likes_id }}">
{% endif %}



<button type="submit" class="btn btn-success">
    {% if not is_liked_bool %}
        <i class="fi-xnluxl-heart">♥</i>
    {% else %}
        <i class="fi-xnluxl-heart-solid">♥</i>
    {% endif %}
    <span class="likes-qty">{{ likes_counter }}</span>
</button>

【问题讨论】:

  • 当点击提交按钮时,您需要阻止默认表单操作并从前端调用 ajax 请求。这将确保您的页面不会在表单提交时重新加载。你可以通过这个stackoverflow.com/questions/7335780/…

标签: python django


【解决方案1】:

我认为您应该先检查url_from 字段。只需打印它,如果有误,您应该更改模板中的{{request.path}} 字段。

你可以试试这个:

{{ request.get_full_path }}

如果我没记错的话,您可以在视图中使用request.path 访问路径,而无需通过模板发送路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2021-05-29
    • 2014-06-21
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多