python - Django Json 喜欢按钮和计数喜欢不起作用

标签 python html json django

我正在 Django 中使用 JSON 代码制作一个“赞”按钮,但是当我单击“赞”按钮时,它不会增加此产品中的“赞”数量或传递“赞”(因为该猎人喜欢此产品)。我需要在 models.py 中创建一个单独的类,如果是的话,其中应该包含什么。或者是子弹没有以正确的方式设置。在 urls.py 和 models.py 中,我显示了所有代码,在views.py 中仅显示了“like”按钮和导入的方法,在detail.html 中仅显示了“like”按钮和JSON 脚本的HTML 标记。我正在与: 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>

知道应该纠正或添加哪些内容才能使“赞”按钮正常工作。

如果可以的话请说清楚!!!

最佳答案

$(this) inside of AJAX success not working

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

我要么做 var self = this;在 ajax 或 $('#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')```

关于python - Django Json 喜欢按钮和计数喜欢不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580425/

相关文章:

html - 居中的内容和每边的线条填充剩余空间

java - 使用 AWS API 网关 + lambda 函数 + RequestHandler

json - node.js http.request 获取json,json前面未定义

python - s.replace string方法,循环遍历字符串

python - 我怎样才能使这个生成器循环?

html - CSS表格单元格在div上有空间

JavaScript 在数组中使用 Indexof 搜索名称

python 日志记录格式 : how to add bracket

python - 这个过程的逻辑是什么

html - 需要有关滚动条按钮的帮助