Django Json like 按钮和点赞数不起作用

Posted

技术标签:

【中文标题】Django Json like 按钮和点赞数不起作用【英文标题】:Django Json like button and counting likes isn't working 【发布时间】:2020-04-22 03:02:55 【问题描述】:

我在 Django 中使用 JSON 代码制作了一个赞按钮,但是当我单击赞按钮时,它不会增加该产品中赞的数量或传递赞(因为这个猎人喜欢这个产品)。我需要在models.py中为like创建一个单独的类,如果是的话应该在里面。或者是蛞蝓没有设置正确的方式。在 urls.py 和 models.py 中,我显示了所有代码,在 views.py 中仅显示了点赞按钮和导入的方法,在 detail.html 中仅显示了点赞按钮的 HTML 标记和 JSON 脚本。我正在与: Django 版本:2.2.9 Python 版本:3.7.4。

应用“产品”中的models.py:

from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.urls import reverse

class Product(models.Model):
    title = models.CharField(max_length = 80)
    pub_date =  models.DateTimeField()
    body = models.TextField()
    url = models.TextField()
    image = models.ImageField(upload_to = 'images/')
    icon = models.ImageField(upload_to = 'icon/')
    votes_total = models.IntegerField(default=1)
    slug = models.SlugField(null=False, unique=True)
    likes = models.ManyToManyField(User, blank=True, related_name='likes')
    hunter = models.ForeignKey(User, on_delete = models.CASCADE)

    def __str__(self):
        return self.title
    def summary(self):
        return self.body[:100] + "..."
    def pub_date_pretty(self):
        return self.pub_date.strftime("%b %e %Y")

    def save(self, *args, **kwargs):
         #if not self.slug:
            #self.slug = slugify(self.title)

        if not self.slug:
            slug = slugify(self.title)
            while True:
                try:
                    product = Product.objects.get(slug=slug)
                    if article == self:
                        self.slug = slug
                        break
                    else:
                        slug = slug + '-'
                except:
                    self.slug = slug
                    break
        return super(Product, self).save(*args, **kwargs)
    @property
    def total_likes(self):
        return self.likes.count()

应用“产品”中的views.py:

from django.http import HttpResponse
try:
    from django.utils import simplejson as json
except ImportError:
    import json
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Product
from django.contrib.auth.models import User
from django.utils import timezone
from django.views.decorators.http import require_POST


def home(request):
    products = Product.objects
    return render(request, 'products/home.html', 'products':products)

@login_required(login_url = '/accounts/signup')
def create(request):
    if request.method == 'POST':
        if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']:
            product = Product()
            product.title = request.POST['title']
            product.body = request.POST['body']
            if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
                product.url = request.POST['url']
            else:
                product.url = 'http://' + request.POST['url']
            product.icon = request.FILES['icon']
            product.image = request.FILES['image']
            product.pub_date = timezone.datetime.now()
            product.hunter = request.user
            product.save()
            return redirect('/products/' + str(product.id))
        else:
            return render(request, 'products/create.html', 'error':'All fields are required.')
    else:
        return render(request, 'products/create.html')

def detail(request, product_id):
    detail_product = get_object_or_404(Product, pk = product_id)
    return render(request, 'products/detail.html', 'product' : detail_product)

@login_required(login_url = '/accounts/signup')
@require_POST
def like(request):
    if request.method == 'POST':
        hunter = request.user
        slug = request.POST.get('slug', None)
        product = get_object_or_404(Product, slug = slug)

        if product.likes.filter(hunter_id = hunter.id).exists():
            # user has already liked this company
            # remove like/user
            product.likes.remove(hunter)
            message = 'You disliked this'
            product.save()
        else:
            # add a new like for a company
            product.likes.add(hunter)
            message = 'You liked this'
            product.save()

    ctx = 'likes_count': product.total_likes, 'message': message
    # use mimetype instead of content_type if django < 5
    return HttpResponse(json.dumps(ctx), content_type='application/json')

产品应用中的 urls.py:

from django.urls import path, include
from . import views

urlpatterns = [
    path('create', views.create, name = 'create'),
    path('<int:product_id>/', views.detail, name = 'detail'),
    path('<int:product_id>/upvote', views.upvote, name = 'upvote'),
    path('user/<int:fk>', views.hunterhunts, name = 'hunterhunts'),
    path('<slug:slug>', views.like, name='like'),
]

“产品”应用中的 HTML 文件 detail.html:

<input type="button" id="like" name=" product.slug " value="Like" />
                    <script>
                    $('#like').click(function() 
                      $.ajax(
                        type: "POST",
                        url: "% url 'like' product.slug %",
                        data: 
                          'slug': $(this).attr('name'),
                          'csrfmiddlewaretoken': ' csrf_token '
                        ,
                        dataType: "json",
                        success: function(response) 
                          alert(response.message);
                          alert('Product likes count is now ' + response.likes_count);
                        ,
                        error: function(rs, e) 
                          alert(rs.responseText);
                        
                      );
                    );
                  </script>

知道应该更正或添加什么以使“赞”按钮起作用。

如果可以,请明确说明!!!

【问题讨论】:

【参考方案1】:

$(this) inside of AJAX success not working

'slug': $(this).attr('name'),

我会选择var self = this; before ajax or $('#like').attr('name')

    product = get_object_or_404(Product, slug=slug)
    if request.method == 'POST':
        hunter = request.user
        if product.likes.exists():
            if product.likes.filter(username=hunter.username).exists():
                product.likes.remove(hunter)
                message = 'You disliked this'
                product.save()
            else:
                product.likes.add(hunter)
                message = 'You liked this'
                product.save()
        else:
            product.likes.add(hunter)
            message = 'You liked this'
            product.save()

    ctx = 'likes_count': product.total_likes, 'message': message
    return HttpResponse(json.dumps(ctx), content_type='application/json')```

【讨论】:

我尝试了您刚才建议的两种方法,但均无效。任何想法 import jsonfrom django.shortcuts import render, redirect, get_object_or_404 不确定这是错字,但这里有错误。 是的,当我提交代码时这是一个错字,在我的代码中导入 json 后的所有内容都在另一行 点赞按钮的问题仍然存在,我愿意接受任何建议 编辑了我的答案以修复类似视图。

以上是关于Django Json like 按钮和点赞数不起作用的主要内容,如果未能解决你的问题,请参考以下文章

使用 Jquery 的 Django ajax 'like' 按钮?

python 微信公众号文章抓取阅读数和点赞数

我如何管理应用程序 ios 上的观看次数和点赞数

Facebook 图形 API 用于获取带有评论数和点赞数的 Facebook 订阅源

(rails) 按网站上的点赞数排序

如何在 swift tableviewCell 中集成“喜欢”按钮