Django中的收藏夹系统

2024-05-23 23:01:51 发布

您现在位置:Python中文网/ 问答频道 /正文

形象

enter image description here

$(document).ready(function(){ $(".like").click(function(){ $(this).toggleClass("heart"); }); });
.like {
  padding-right: 6px;
  color: #00000030;
  font-size: 1.6em;
  padding-top: 5px;
  animation: like 0.5s linear;
}

.heart {
  color: #FF0000;
  animation: heart 0.5s linear;
}
{% for m in musicl %}
  <div class="card">
        <div class="top">
          <div class="year">{{m.Year}}</div>
          <span class="like"><i class="fa fa-heart"></i></span>
        </div>

        <div class="middle">
          <a href="https://google.com" id="link" target="_blank">
            <div class="img-container"><img src="{{ m.Image.url }}"></div>
          </a>
        </div>

        <a href="https://google.com" id="link" target="_blank">
          <div class="bottom">
            <div class="title">{{m.Name}}</div>
            <div class="genre">{{m.Genre}}</div>
          </div>
        </a>
  </div>
{% endfor %}

models.py

class Music(models.Model):
    Name = models.CharField(max_length=100, blank=False)
    Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    Genre = MultiSelectField(choices=GENRE_CHOICES)
    Image = models.ImageField(blank=False, null=True)

    def __str__(self):
        return self.Name

Views.py

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


def wishlist(request, id):
    pass

如何将用户模型连接到此收藏夹系统,并在视图功能(wishlist)中跟踪收藏夹列表,换句话说,当有人单击fav图标时,我希望将特定卡保存到对应于该用户模型的wishlist视图中


Tags: namedividmodelsrequestdeffunctionyear
2条回答

要将您的用户模型与前端连接,我们需要将数据(音乐id)从UI推送到后端

如果要使用django模板执行此操作,则可以使用django表单

https://docs.djangoproject.com/en/3.0/topics/forms/

但是,如果您想继续进行一些基于事件的操作,例如单击,请执行以下步骤

要做到这一点,需要做几件事

  1. Wishlist存储Wishlist音乐所需的附加型号
  2. views.py验证输入并保存愿望列表
  3. url调度程序url->;视图(您的业务逻辑)——>;模型(保存数据,在您的案例中列出愿望)
  4. 对django后端的post调用(使用ajax,因为您希望在单击图标时使用存储数据)

1。型号定义

class Music(models.Model):
    Name = models.CharField(max_length=100, blank=False)
    Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    Genre = MultiSelectField(choices=GENRE_CHOICES)
    Image = models.ImageField(blank=False, null=True)

    def __str__(self):
        return self.Name

class WishlistMusic(models.Model):
    ## this can be depend on your choice eg (user_id, guest_id etc)
    some_id = models.IntegerField(('some_id'))
    ## relation to Music
    music = models.ForeignKey(Music, on_delete=models.DO_NOTHING)

2。views.py

from music.models import Music, WishlistMusic
from django.core.exceptions import ObjectDoesNotExist

from django.http import HttpResponse

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def wishlist(request):
    music_id = request.POST.get('music_id')
    if not music_id:
        raise ValueError("Required music_id to set wishlist")
    ## can be set user id once authentication is set
    ##some_id = request.user.pk
    some_id = 3 ## Say
    try:
        music = Music.objects.get(pk=music_id)
        wishlist_obj = {
            'some_id': some_id,
            'music': music
        }
        WishlistMusic(**wishlist_obj).save()
    except ObjectDoesNotExist:
        ## Your action
        ## raise or Return HTTP response with failure status_code
        return HttpResponse('Some error occured, unable to add to wishlist') ## or can set for render
        
    return HttpResponse('Added to wishlist') ## or can set for render

使用@csrf_-emption是因为我们将使用ajax发布调用,django提供跨站点请求伪造保护,但不建议在生产环境中使用@csrf_-emption。 有关https://docs.djangoproject.com/en/3.0/ref/csrf/的更多详细信息

3。URL调度程序/路径 在这里,我们在音乐应用程序下有模型和视图,所以在url.py下面有重定向/音乐url到音乐应用程序url的链接

对于refr。我的项目结构为 enter image description here

项目名称->;音乐曲目

from django.contrib import admin
from django.urls import path, include
from music import urls as music_urls    

urlpatterns = [
    path('admin/', admin.site.urls),
    path('music/', include(music_urls)),
]

音乐/url.py

from django.contrib import admin
from django.urls import path
from music import views

urlpatterns = [
    path('mymusic/', views.home),  ## IP:PORT/mymusic your homepage
    path('wishlist/', views.wishlist),  ## IP:PORT/mymusic your post api to save wishlist
]

4。将API调用从前端发送到django。

js

$(document).ready(function(){
    $(".like").click(function(){
        $(this).toggleClass("heart");
        var pk = $(this).find('input[id="abc"]').val();
        var data = {
            'music_id': pk
            };
        $.ajax({
                     type: 'POST',
                     url: '../wishlist/',
                     data: data,
                     success: function(json) {
                         alert(json); // your actions after save, you can just pop-up some ui element that added to wishlist
                     }
                 })
    });
});

我刚刚在html中添加了一个ui元素(类似于类span)来保存音乐的主键,这是在模型中添加wishlist所需的,因为我们在WishlistMusic模型中将music_id设置为外键

.html

........
<a href="https://google.com" id="link" target="_blank">
          <div class="bottom">
            <div class="title" id="title">{{m.Name}}</div>
            <div class="genre" id="genre">{{m.Genre}}</div>
          </div>
          
        </a>
         <span class="like" id="abc"><input type="hidden", id="abc", value="{{m.pk}}"/>aa<i class="fa fa-heart"></i></span>
 .......

以下是参考资料,你可以通过进一步的细节

https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.htmlhttps://docs.djangoproject.com/en/3.0/ref/urls/

我认为您可以做的最好的事情是在类似这样的脚本中手动在music对象中创建一个新行,并将其放在JavaScript单击事件后面:

from app.models import Music

Music.objects.create(Name=name_variable, Year=year_variable, Genre=genre_variable, Image=image_variable)
Music.save()

相关问题 更多 >