首页 > 解决方案 > 带有ajax的Django Like函数

问题描述

首先:我已经检查了所有相关的答案和问题....他们没有帮助我

所以我试图用多个用户和多个对象或帖子创建基于 ajax 的按钮,我尝试了很多,但它们都不起作用,但我有基础

模型.py:

class BlogPost(models.Model):
    #some fields

class Like (models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(BlogPost)

视图.py

from .models import Like
def PostLikeToggle(request):
    #here i want to capture the request check if the user liked the post or
    # no by sending user.username and post.title to the endpoint like.html
    #and then update his status
    return render(request, 'like.html')

网址.py

from plateform import views as plateform
urlpatterns = [
    #other urls
    url(r'^like/', plateform.PostLikeToggle,  name='PostLikeToggle'),]

喜欢.html

 {% if liked == 'false' %}
    false
  {% elif liked == 'true' %}
    true
  {% endif %}

blogpost.html

#ajax

  $('.thumb').click(function () {
            $.ajax({
                type: 'POST',
                url: '/like/',
                data: {
                    'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
                },
                success: LikePost,
                dataType: 'html'
            });

            function LikePost(data, jqXHR) {
                    console.log(data)
                }
        });

更新 我试图弄清楚所以我添加了一些东西

楷模:

class BlogPost(models.Model):
        #some fields
        liked = models.ManyToManyField(User, related_name='PostLikeToggle')

    #REMOVED class Like (models.Model)

意见:

def PostLikeToggle(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST['post_id']
        post = get_object_or_404(posts, id=post_id)
        _liked = user in post.liked.all()
        if _liked :
            post.liked.remove(user)
        else:
            post.liked.add(user)

    return JsonResponse({'liked':_liked})

那我走对了吗??

标签: pythonajaxdjangodjango-viewsendpoint

解决方案


好的,我将发布我的答案....这很简单,但我有点小气...

在模型文件中,我添加了带有用户关系的 ManytoMany 字段(许多用户+许多帖子)

class BlogPost(models.Model):
    #more fields
    liked = models.ManyToManyField(User, related_name='PostLikeToggle')

在视图中,我创建了视图,它将接受来自 blogpost 视图的请求并检查用户是否已经喜欢该帖子(如果喜欢,则将用户添加到喜欢的字段,如果喜欢返回 true,则删除它,如果 ....)

def PostLikeToggle(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST['post_id']
        post = get_object_or_404(posts, id=post_id)
        _liked = user in post.liked.all()
        if _liked :
            post.liked.remove(user)
        else:
            post.liked.add(user)

    return JsonResponse({'liked':_liked})

此视图与我们将获得响应的 url 相关联:

url(r'^like/', plateform.PostLikeToggle,  name='PostLikeToggle') 

在您的博客文章模板中,您将需要链接 Jquery 并添加此 Ajax 函数(不要忘记使用您自己的变量类、url 自定义它...

$('.thumb').click(function () {
            $.ajax({
                type: 'POST',
                url: {% url 'PostLikeToggle' %},
                data: {
                    'post_id': {{ post_slug.id }},
                    'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
                },
                success: LikePost,
                dataType: 'html'
            });

            function LikePost(data, jqXHR) {
                var data = $.parseJSON(data)
                if (data['liked']) {
                    $('.thumb').removeClass("fas fa-thumbs-up").addClass('far fa-thumbs-up')
                }
                else
                    {
                        $('.thumb').removeClass("far fa-thumbs-up").addClass('fas fa-thumbs-up')
                    }


            }
        });

如果有任何异常或者你有更好的方法只是发布它,我会标记它

注意:您必须检查用户是否在模板中通过身份验证以隐藏喜欢按钮或将他重定向到登录 ....


推荐阅读