为了账号安全,请及时绑定邮箱和手机立即绑定

将项目添加到愿望清单

将项目添加到愿望清单

繁花不似锦 2023-06-06 10:32:07
我有这个系统,我想在其中添加一个收藏功能,当有人点击卡片上的“喜欢”按钮时,它会被保存并显示在 port/wishlist.html 但无法解决它,这是我的Github Repository和一些主要代码。models.pyfrom django.db import modelsfrom django.contrib.auth.models import Userimport datetimeYEAR_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.songclass 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_requireddef 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");    });});
查看完整描述

2 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

我建议做这样的事情:在这里我们创建一个新的 url 以添加到 wishlist( add_to_wishlist)。通过.如果用户登录,则将用户的心愿单产品显示为红色的心形符号like.js。您可以通过模板中的链接显示愿望清单产品。您可以理解我的代码中的所有其他内容。请试试这个。谢谢。music_idajaxPOST


urls.py


from django.urls import path

from main import views


app_name = 'main'


urlpatterns = [

    path('', views.home, name='home'),

    path('signup/', views.signup, name='signup'),

    path('wishlist/', views.liked, name='liked'),

    path('login/', views.login_req, name='login'),

    path('logout/', views.logout_req, name='logout'),

    path('add-to-wishlist/', views.add_to_wishlist, name='add_to_wishlist'), # For add to wishlist

]

views.py


def home(request):

    wishlisted_list =[]

    if request.user.is_authenticated:

        wishlisted_list = list(Wishlist.objects.filter(user_id=request.user).values_list('music_id',flat=True).order_by('music_id'))

    return render(request, template_name='main/home.html', context={"music": Music.objects.all(),'wishlisted_list':wishlisted_list})


@login_required

def liked(request):

    wishlist = {}

    if request.method == "GET":

        if request.user.is_authenticated:

            wishlist = Wishlist.objects.filter(user_id_id=request.user.pk)

        else:

            print("Please login")

            return HttpResponse("login")


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


@login_required

def add_to_wishlist(request):

    if request.is_ajax() and request.POST and 'attr_id' in request.POST:

        if request.user.is_authenticated:

            data = Wishlist.objects.filter(user_id_id = request.user.pk,music_id_id = int(request.POST['attr_id']))

            if data.exists():

                data.delete()

            else:

                Wishlist.objects.create(user_id_id = request.user.pk,music_id_id = int(request.POST['attr_id']))

    else:

        print("No Product is Found")


    return redirect("main:home")

喜欢.js


$(document).ready(function(){

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

        var attr_id = $(this).attr('attr_id')

        var action_url = $(this).attr('action_url')

        var that = $(this)


        $.ajax({

            url: action_url,

            type: "POST",

            data: {'attr_id': attr_id },

            headers: { "X-CSRFToken": $.cookie("csrftoken") },

            success: function (result) {

                console.log("Success")

                that.toggleClass("heart");

            },

            error: function () {

                alert("Please login");

            }

            

        });

    });

});

主页.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">

    {% for m in music %}


    <div class="card">


        <div class="top">

            <div class="label1">{{m.song}}</div>

            {% if m.pk in wishlisted_list %}

            {% for i in wishlisted_list %}

            {% if m.pk is i %}

            <span class="like heart" id="id" attr_id="{{m.pk}}" action_url="{% url 'main:add_to_wishlist' %}"><i class="fa fa-heart"></i></span>

            {% endif %}

            {% endfor %}

            {% else %}

            <span class="like" id="id" attr_id="{{m.pk}}" action_url="{% url 'main:add_to_wishlist' %}"><i class="fa fa-heart"></i></span>

            {% endif %}

        </div>



        <div class="middle">

            <a href="https://google.com" id="link" target="_blank">

                <div class="img-container"><img src="{{ m.pic.url }}"></div>

            </a>

        </div>


        <a href="https://google.com" id="link" target="_blank">

            <div class="bottom">

                <div class="label4">{{m.description}}</div>

            </div>

        </a>


    </div>

    {% endfor %}

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script src="{% static 'main/js/like.js' %}" type="text/javascript"></script>

    <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">

    {% if wishlist %}

    {% for m in wishlist %}

    <div class="card">

        <div class="top">

            <div class="label1">{{m.music_id}}</div>

            <span class="like" id="id" attr_id="{{m.music_id.pk}}" action_url="{% url 'main:add_to_wishlist' %}"></span>

        </div>

        <div class="middle">

            <a href="https://google.com" id="link" target="_blank">

                <div class="img-container"><img src="{{ m.music_id.pic.url }}"></div>

            </a>

        </div>

        <a href="https://google.com" id="link" target="_blank">

            <div class="bottom">

                <div class="label4">{{m.music_id.description}}</div>

            </div>

        </a>

    </div>

    {% endfor %}

    {% else %}

    <div class="card">

        <div class="middle">

            <div class="label1">Your Wishlist is empty...!</div>

        </div>

        <div class="bottom">

            <div class="label4"><a href="/">Go to Shop</a></div>

        </div>

    </div>

    {% endif %}

</section>



查看完整回答
反对 回复 2023-06-06
?
萧十郎

TA贡献1815条经验 获得超13个赞

首先,您需要在 Music 表中添加一个主键,假设您将其命名为id


在该like.js文件中,您需要进行 Ajax 调用以将音乐 ID 发送到 Django。渲染时将音乐 ID 传递给模板,以便在 Ajax 调用期间将其传回


喜欢.js


$.ajax(path, {

        data: {"music_id": 12345},

        method: "POST",

        success: function (data, textStatus, jqXHR) {

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

        },

        error: function () {

            console.log("Something went wrong");

}

现在,在你看来,你可以有这样的东西 view.py


def add_to_wishlist(request):

    data = json.loads(request.body.decode("utf-8"))


    user_id = request.user.id

    music_id = data.get('domain_name'))

    

    wishlist = Wishlist()

    wishlist.user_id = user_id

    wishlist.music_id = music_id

    wishlist.save()


查看完整回答
反对 回复 2023-06-06
  • 2 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信