要将您的 UserModel 与前端连接,我们需要将数据 (music_id) 从 UI 推送到后端。
如果你想用 django-template 做这个,那么你可以使用 django-forms。
https://docs.djangoproject.com/en/3.0/topics/forms/
但是,如果您想进行一些基于点击等事件,以下是步骤...
要做到这一点,需要做几件事。
- 存储愿望清单音乐需要愿望清单附加模型
- views.py 验证输入并保存愿望清单
- url-dispatcher url -> 视图(您的业务逻辑)-> 模型(保存数据,您的情况下的愿望清单)
- 对 django-backend 的调用后(使用 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。 view.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_exempt 是因为我们将使用ajax 进行POST 调用,django-提供跨站点请求伪造保护,但是不建议在生产环境中使用@csrf_exempt。
更多详情https://docs.djangoproject.com/en/3.0/ref/csrf/
3. URL-Dispatcher/路径
这里我们在音乐应用程序下有模型和视图,因此在 urls.py 下方用于将 /music url 重定向到音乐应用程序 url
用于参考。我的项目结构为
proj_name -> music_track
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)),
]
音乐/urls.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.从前端到 django 的 POST API 调用。
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 元素(在类跨度内)来保存音乐的主键,这是在模型中添加愿望清单所需的,因为我们在 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.html
https://docs.djangoproject.com/en/3.0/ref/urls/