猿问

将项目添加到愿望清单

我有这个系统,我想在其中添加一个收藏功能,当有人点击卡片上的“喜欢”按钮时,它会被保存并显示在 port/wishlist.html 但无法解决它,这是我的Github Repository和一些主要代码。

models.py


from django.db import models

from django.contrib.auth.models import User

import datetime


YEAR_CHOICES = []

for r in range(1980, (datetime.datetime.now().year + 1)):

    YEAR_CHOICES.append((r, r))


class Music(models.Model):

    song = models.CharField(max_length=50, blank=False)

    pic = models.ImageField(blank=False, null=True)

    published_year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)

    description = models.CharField(max_length=80)


    def __str__(self):

        return self.song


class Wishlist(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE,null=True)

    music = models.ForeignKey(Music, on_delete=models.DO_NOTHING)

views.py


@login_required

def liked(request):

    if request.method == "POST":

        if user.is_authenticated:

            # takes in the specific card id that is been liked and saves it and displays on Port/wishlist.html

            music.save()

        else:

            return HttpResponse("Your card is Invalid")

    else:

        return HttpResponse("Your request is Invalid")


    return render(request, template_name='main/wishlist.html', context={"wishlist": Wishlist.objects.all})

喜欢.js


$(document).ready(function(){

    $(".like").click(function(){

        $(this).toggleClass("heart");

    });

});


繁花不似锦
浏览 125回答 2
2回答

慕勒3428872

我建议做这样的事情:在这里我们创建一个新的 url 以添加到 wishlist( add_to_wishlist)。通过.如果用户登录,则将用户的心愿单产品显示为红色的心形符号like.js。您可以通过模板中的链接显示愿望清单产品。您可以理解我的代码中的所有其他内容。请试试这个。谢谢。music_idajaxPOSTurls.pyfrom django.urls import pathfrom main import viewsapp_name = 'main'urlpatterns = [&nbsp; &nbsp; path('', views.home, name='home'),&nbsp; &nbsp; path('signup/', views.signup, name='signup'),&nbsp; &nbsp; path('wishlist/', views.liked, name='liked'),&nbsp; &nbsp; path('login/', views.login_req, name='login'),&nbsp; &nbsp; path('logout/', views.logout_req, name='logout'),&nbsp; &nbsp; path('add-to-wishlist/', views.add_to_wishlist, name='add_to_wishlist'), # For add to wishlist]views.pydef home(request):&nbsp; &nbsp; wishlisted_list =[]&nbsp; &nbsp; if request.user.is_authenticated:&nbsp; &nbsp; &nbsp; &nbsp; wishlisted_list = list(Wishlist.objects.filter(user_id=request.user).values_list('music_id',flat=True).order_by('music_id'))&nbsp; &nbsp; return render(request, template_name='main/home.html', context={"music": Music.objects.all(),'wishlisted_list':wishlisted_list})@login_requireddef liked(request):&nbsp; &nbsp; wishlist = {}&nbsp; &nbsp; if request.method == "GET":&nbsp; &nbsp; &nbsp; &nbsp; if request.user.is_authenticated:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wishlist = Wishlist.objects.filter(user_id_id=request.user.pk)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Please login")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return HttpResponse("login")&nbsp; &nbsp; return render(request, template_name='main/wishlist.html', context={"wishlist": wishlist})@login_requireddef add_to_wishlist(request):&nbsp; &nbsp; if request.is_ajax() and request.POST and 'attr_id' in request.POST:&nbsp; &nbsp; &nbsp; &nbsp; if request.user.is_authenticated:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data = Wishlist.objects.filter(user_id_id = request.user.pk,music_id_id = int(request.POST['attr_id']))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if data.exists():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.delete()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Wishlist.objects.create(user_id_id = request.user.pk,music_id_id = int(request.POST['attr_id']))&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("No Product is Found")&nbsp; &nbsp; return redirect("main:home")喜欢.js$(document).ready(function(){&nbsp; &nbsp; $(".like").click(function(){&nbsp; &nbsp; &nbsp; &nbsp; var attr_id = $(this).attr('attr_id')&nbsp; &nbsp; &nbsp; &nbsp; var action_url = $(this).attr('action_url')&nbsp; &nbsp; &nbsp; &nbsp; var that = $(this)&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: action_url,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: {'attr_id': attr_id },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; headers: { "X-CSRFToken": $.cookie("csrftoken") },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function (result) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Success")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; that.toggleClass("heart");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error: function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Please login");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });});主页.html{% load static %}<link rel="stylesheet" href="{% static 'main/home.css' %}" type="text/css"><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous"><meta name="viewport" content="width=device-width, initial-scale=1.0">Hey there,{% if user.is_authenticated %}<h1>{{user.username}}</h1>{% else %}<h1>unknown</h1>{% endif %}<a href="{% url 'main:liked' %}" >Wishlist</a><section class="cards">&nbsp; &nbsp; {% for m in music %}&nbsp; &nbsp; <div class="card">&nbsp; &nbsp; &nbsp; &nbsp; <div class="top">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="label1">{{m.song}}</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {% if m.pk in wishlisted_list %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {% for i in wishlisted_list %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {% if m.pk is i %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="like heart" id="id" attr_id="{{m.pk}}" action_url="{% url 'main:add_to_wishlist' %}"><i class="fa fa-heart"></i></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {% endif %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {% endfor %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {% else %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="like" id="id" attr_id="{{m.pk}}" action_url="{% url 'main:add_to_wishlist' %}"><i class="fa fa-heart"></i></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {% endif %}&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="middle">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href="https://google.com" id="link" target="_blank">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="img-container"><img src="{{ m.pic.url }}"></div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <a href="https://google.com" id="link" target="_blank">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="bottom">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="label4">{{m.description}}</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; </div>&nbsp; &nbsp; {% endfor %}&nbsp; &nbsp; <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>&nbsp; &nbsp; <script src="{% static 'main/js/like.js' %}" type="text/javascript"></script>&nbsp; &nbsp; <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script></section>wishlist.html{% load static %}<link rel="stylesheet" href="{% static 'main/home.css' %}" type="text/css"><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous"><meta name="viewport" content="width=device-width, initial-scale=1.0">Hey there,{% if user.is_authenticated %}<h1>{{user.username}}</h1>{% else %}<h1>unknown</h1>{% endif %}<a href="{% url 'main:home' %}" >Go to Home</a><section class="cards">&nbsp; &nbsp; {% if wishlist %}&nbsp; &nbsp; {% for m in wishlist %}&nbsp; &nbsp; <div class="card">&nbsp; &nbsp; &nbsp; &nbsp; <div class="top">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="label1">{{m.music_id}}</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="like" id="id" attr_id="{{m.music_id.pk}}" action_url="{% url 'main:add_to_wishlist' %}"></span>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="middle">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href="https://google.com" id="link" target="_blank">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="img-container"><img src="{{ m.music_id.pic.url }}"></div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <a href="https://google.com" id="link" target="_blank">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="bottom">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="label4">{{m.music_id.description}}</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; </div>&nbsp; &nbsp; {% endfor %}&nbsp; &nbsp; {% else %}&nbsp; &nbsp; <div class="card">&nbsp; &nbsp; &nbsp; &nbsp; <div class="middle">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="label1">Your Wishlist is empty...!</div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="bottom">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="label4"><a href="/">Go to Shop</a></div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; &nbsp; {% endif %}</section>

萧十郎

首先,您需要在 Music 表中添加一个主键,假设您将其命名为id在该like.js文件中,您需要进行 Ajax 调用以将音乐 ID 发送到 Django。渲染时将音乐 ID 传递给模板,以便在 Ajax 调用期间将其传回喜欢.js$.ajax(path, {&nbsp; &nbsp; &nbsp; &nbsp; data: {"music_id": 12345},&nbsp; &nbsp; &nbsp; &nbsp; method: "POST",&nbsp; &nbsp; &nbsp; &nbsp; success: function (data, textStatus, jqXHR) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(selector).toggleClass("heart");&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Something went wrong");}现在,在你看来,你可以有这样的东西 view.pydef add_to_wishlist(request):&nbsp; &nbsp; data = json.loads(request.body.decode("utf-8"))&nbsp; &nbsp; user_id = request.user.id&nbsp; &nbsp; music_id = data.get('domain_name'))&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; wishlist = Wishlist()&nbsp; &nbsp; wishlist.user_id = user_id&nbsp; &nbsp; wishlist.music_id = music_id&nbsp; &nbsp; wishlist.save()
随时随地看视频慕课网APP

相关分类

Python
我要回答