У меня возникла проблема с получением номера вишлиста и отображением этого?

Следующая ошибка... У меня проблемы с получением количества лайков для товаров и удалением лайков из списка избранного. В базе данных лайки корректно ставятся (добавляются в избранное), но я не знаю, как получить их количество и сделать его динамическим в JavaScript-кодах с помощью Ajax.

Можете ли вы взглянуть на мои коды и дать мне необходимые указания, что я должен добавить или убрать? Спасибо!

favorite.py

from apps.comment_scoring_favorites.models import Favorite
class favoriteProduct:
    def __init__(self,request) -> None:
        self.session=request.session
        favorite_product=self.session.get('favorite_product')
        if not favorite_product:
            favorite_product=self.session['favorite_product']=[]
        self.favorite_product=favorite_product
        self.count=Favorite.count_favorites_by_session()


    def __iter__(self):
        favorite_product=self.favorite_product.copy()
        for item in favorite_product:
            yield item

    def add_to_favorite_product(self,productId):
        productId=int(productId)
        if productId  not in self.favorite_product:
            self.favorite_product.append(productId)
        self.count=Favorite.count_favorites_by_session()
        self.session.modified=True

    def delete_from_favorite_product(self, productId):
        productId=int(productId)
        self.favorite_product.remove(productId)
        self.count=Favorite.count_favorites_by_session()
        self.session.modified=True

middleware.py

import threading
class RequestMiddleware:
    def __init__(self,get_response,thread_local=threading.local()):
        self.get_response=get_response
        self.thread_local=thread_local

    def __call__(self,request):
        self.thread_local.current_request=request
        response=self.get_response(request)
        return response

models.py

from middlewares.middleware import RequestMiddleware
class Favorite(models.Model):
    product=models.ForeignKey(Product,on_delete=models.CASCADE,related_name='favorite_product',verbose_name='کالا')
    favorite_user=models.ForeignKey(CustomUser, on_delete=models.CASCADE,related_name='favorite_user1',verbose_name='کاربر علاقه مند')
    register_date=models.DateTimeField(auto_now_add=True,verbose_name='تاریخ درج')

    def __str__(self) -> str:
        return f"{self.product} - {self.favorite_user}"
    
    
    class Meta:
        verbose_name='علاقه'
        verbose_name_plural='علایق'

    
    def count_favorites_by_session(self):
        request=RequestMiddleware(get_response=None)
        request=request.thread_local.current_reques
        session=request.session
        favorite_product_ids =session.get('favorite_product')
        return self.objects.filter(product__id__in=favorite_product_ids).count()

views.py

class ShowFavoriteListView(View):
    def get(self,request,*args,**kwargs):
        favorite_list=favoriteProduct(request)
        context={
            'favorite_list':favorite_list,
        }
        return render(request,'csf_app/partials/create_favorites.html',context)
    

def statuse_of_favorite_list(request):
    favoriteList=favoriteProduct(request)
    return HttpResponse(favoriteList.count)

def add_to_favorite(request):
    productId=request.GET.get('productId')
    product=Product.objects.get(id=productId)
    flag=Favorite.objects.filter(
        Q(favorite_user_id=request.user.id) &
        Q(product_id=productId)).exists()
    if(not flag):
        Favorite.objects.create(
            product=product,
            favorite_user=request.user,
        )
        return HttpResponse('added to favorite lists')
    return HttpResponse('it was in favorite')

def delete_from_favorite(request):
    productId=request.GET.get('productId')
    favoriteList=favoriteProduct(request)
    favoriteList.delete_from_favorite_product(productId)
    return redirect('csf:user_favorite_list')

class UserFavoriteView(View):
    def get(self,request,*args,**kwargs):
        user_favorite_products=Favorite.objects.filter(Q(favorite_user_id=request.user.id))
        return render(request,'csf_app/user_favorite.html',{'user_favorite_products':user_favorite_products})

urls.py

from django.urls import path
from . import views
app_name='csf'
urlpatterns = [
    path('create_comment/<slug:slug>/',views.CommentView.as_view(),name='create_comment'),  
    path('add_score/',views.add_score,name='add_score'),  
    path('add_to_favorite/',views.add_to_favorite,name='add_to_favorite'),
    path('user_favorite_list/',views.UserFavoriteView.as_view(),name='user_favorite_list'),  
    path('delete_from_favorite/',views.delete_from_favorite,name='delete_from_favorite'),  
    path('statuse_of_favorite_list/',views.statuse_of_favorite_list,name='statuse_of_favorite_list'),     
]

myscript.js

statuse_of_favorite_list();
function statuse_of_favorite_list(){
    $.ajax({
        type:"GET",
        url:"/csf/statuse_of_favorite_list/",
        success: function(res){
            $('#favorite_count_icon').show();
            $('#favorite_count').text(res);
        }
    });
}

function addToFavorite(productId){
    $.ajax({
        type:"GET",
        url:"/csf/add_to_favorite/",
        data:{
            productId: productId,
        },
        success: function(res){
            alert(res)
            statuse_of_favorite_list();

        }
    });
}

function deleteFromFavorite(product_id){
    $.ajax({
        type:"GET",
        url:"/csf/delete_from_favorite/",
        data:{
            product_id:product_id,
        },
        success:function(res){
            alert('deleted!');    
            $("#favorite_list").html(res);
            statuse_of_favorite_list();           

        }
    });
}

createfavorites.html

{% load render_partial %}
{% load humanize %}
{% block titile %}
 
{% endblock titile %}
{% block content %}
    <div id="favorite_list">
        {% render_partial 'csf:user_favorite_list' %}
    </div>
{% endblock %}

usre_favorite.html

Вернуться на верх