<p>要将您的用户模型与前端连接,我们需要将数据(音乐id)从UI推送到后端</p>
<p>如果要使用django模板执行此操作,则可以使用django表单</p>
<p><a href="https://docs.djangoproject.com/en/3.0/topics/forms/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.0/topics/forms/</a></p>
<p>但是,如果您想继续进行一些基于事件的操作,例如单击,请执行以下步骤</p>
<p>要做到这一点,需要做几件事</p>
<ol>
<li>Wishlist存储Wishlist音乐所需的附加型号</li>
<li>views.py验证输入并保存愿望列表</li>
<li>url调度程序url->;视图(您的业务逻辑)——>;模型(保存数据,在您的案例中列出愿望)</li>
<li>对django后端的post调用(使用ajax,因为您希望在单击图标时使用存储数据)</li>
</ol>
<p><strong>1。型号定义</strong></p>
<pre><code>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)
</code></pre>
<p><strong>2。views.py</strong></p>
<pre><code>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
</code></pre>
<p>使用@csrf_-emption是因为我们将使用ajax发布调用,django提供跨站点请求伪造保护,但不建议在生产环境中使用@csrf_-emption。
有关<a href="https://docs.djangoproject.com/en/3.0/ref/csrf/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.0/ref/csrf/</a>的更多详细信息</p>
<p><strong>3。URL调度程序/路径</strong>
在这里,我们在音乐应用程序下有模型和视图,所以在url.py下面有重定向/音乐url到音乐应用程序url的链接</p>
<p>对于refr。我的项目结构为
<a href="https://i.stack.imgur.com/aIjGT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aIjGT.png" alt="enter image description here"/></a></p>
<p>项目名称->;音乐曲目</p>
<pre><code>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)),
]
</code></pre>
<p>音乐/url.py</p>
<pre><code>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
]
</code></pre>
<p><strong>4。将API调用从前端发送到django。</strong></p>
<p>js</p>
<pre><code>$(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
}
})
});
});
</code></pre>
<p>我刚刚在html中添加了一个ui元素(类似于类span)来保存音乐的主键,这是在模型中添加wishlist所需的,因为我们在WishlistMusic模型中将music_id设置为外键</p>
<p>.html</p>
<pre><code>........
<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>
.......
</code></pre>
<p>以下是参考资料,你可以通过进一步的细节</p>
<p><a href="https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html" rel="nofollow noreferrer">https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html</a>
<a href="https://docs.djangoproject.com/en/3.0/ref/urls/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.0/ref/urls/</a></p>