Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django Json类按钮和计数类按钮是';行不通_Python_Html_Json_Django - Fatal编程技术网

Python Django Json类按钮和计数类按钮是';行不通

Python Django Json类按钮和计数类按钮是';行不通,python,html,json,django,Python,Html,Json,Django,我正在用JSON代码在Django中创建一个like按钮,但当我单击like按钮时,它不会增加此产品中的like数量或传递like(因为此hunter喜欢此产品)。我是否需要在models.py中为like创建单独的类,如果需要,其中应该包含什么。或者是鼻涕虫的设置方式不对。在url.py和models.py中,我展示了所有代码,在views.py中,我只展示了like按钮和导入的方法,在detail.html中,我只展示了like按钮和JSON脚本的html标记。我的工作对象是: Django

我正在用JSON代码在Django中创建一个like按钮,但当我单击like按钮时,它不会增加此产品中的like数量或传递like(因为此hunter喜欢此产品)。我是否需要在models.py中为like创建单独的类,如果需要,其中应该包含什么。或者是鼻涕虫的设置方式不对。在url.py和models.py中,我展示了所有代码,在views.py中,我只展示了like按钮和导入的方法,在detail.html中,我只展示了like按钮和JSON脚本的html标记。我的工作对象是: Django版本:2.2.9 Python版本:3.7.4

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

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

从django.http导入HttpResponse
尝试:
从django.utils将simplejson导入为json
除恐怖外:
导入json
从django.shortcuts导入渲染、重定向、获取对象或404
从django.contrib.auth.decorators导入所需的登录名
从。模型进口产品
从django.contrib.auth.models导入用户
从django.utils导入时区
从django.views.decorators.http导入需要\u POST
def home(请求):
products=Product.objects
返回呈现(请求'products/home.html',{'products':products})
@需要登录(登录url='/accounts/signup')
def创建(请求):
如果request.method==“POST”:
如果request.POST['title']和request.POST['body']和request.POST['url']和request.FILES['icon']和request.FILES['image']:
产品=产品()
product.title=request.POST['title']
product.body=request.POST['body']
如果request.POST['url'].startswith('http://')或request.POST['url'].startswith('https://'):
product.url=request.POST['url']
其他:
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()
返回重定向('/products/'+str(product.id))
其他:
返回呈现(请求'products/create.html',{'error':'All fields required'})
其他:
返回呈现(请求'products/create.html')
def详细信息(请求、产品id):
详细信息产品=获取对象或404(产品,主键=产品id)
返回呈现(请求'products/detail.html',{'product':detail\u product})
@需要登录(登录url='/accounts/signup')
@需要职位
def like(请求):
如果request.method==“POST”:
hunter=request.user
slug=request.POST.get('slug',None)
产品=获取对象或404(产品,段塞=段塞)
如果product.likes.filter(hunter\u id=hunter.id).exists():
#用户已经喜欢上了这家公司
#删除类/用户
product.likes.remove(猎人)
message='您不喜欢这个'
product.save()
其他:
#为公司添加一个新的相似项
product.likes.add(猎人)
message='你喜欢这个'
product.save()
ctx={'likes\u count':product.total\u likes,'message':message}
#如果django<5,则使用mimetype而不是content_type
返回HttpResponse(json.dumps(ctx),content_type='application/json')
产品应用程序中的URL.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'),
]
从django.url导入路径,包括
从…起导入视图
URL模式=[
路径('create',views.create,name='create'),
路径(“/”,views.detail,name='detail'),
路径('/upvote',views.upvote,name='upvote'),
路径('user/',views.hunterhunts,name='hunterhunts'),
路径(“”,views.like,name='like'),
]
“产品”应用程序中的HTML文件detail.HTML:


$('#like')。单击(函数(){
$.ajax({
类型:“POST”,
url:“{%url'类似于'product.slug%}”,
数据:{
'slug':$(this.attr('name'),
“csrfmiddlewaretoken”:“{csrf_令牌}”
},
数据类型:“json”,
成功:功能(响应){
警报(response.message);
警报(‘产品喜欢次数现在是’+响应。喜欢次数);
},
错误:函数(rs,e){
警报(rs.responseText);
}
});
});
任何想法应该纠正或添加什么样的按钮才能工作

如果可以,请明确说明

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

我要么做
var self=this;在ajax或$('#like').attr('name')之前

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

我要么做
var self=this;在ajax或$('#like').attr('name')之前


我试了你刚才的建议,两个都没用。任何想法
import json from django.shortcuts import render,redirect,get_object_或_404
都不确定这是错别字,但这里有错误。是的,我提交代码时是错别字,在导入json后的代码中,所有内容都在另一行中like按钮的问题仍然存在,我愿意接受任何建议修改我的答案来修正类似的观点。我尝试了你刚才的建议,两个都没有用。任何想法
import json from django.shortcuts import render,redirect,get_object_或_404
都不确定这是错别字,但这里有错误。是的,我提交代码时是错别字,在导入json后的代码中,所有内容都在另一行中like按钮的问题仍然存在,我愿意接受任何建议,修改我的答案来修正类似的观点。
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')
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'),
]
<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>
    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')```