点击收藏的实现
场景:
假设用户已经登陆,当用户点击收藏时,就要将该课程已收藏的信息存到数据库中。并且显示已收藏。当用户再次点击已收藏按钮时,就删除数据库中的数据,显示未收藏。
![](https://img.haomeiwen.com/i22697958/acf4018c6a35cbca.png)
1.课程的收藏
在coursedetail.html中使用两个ajax请求,分别对应两个收藏按钮
- 课程收藏
- 机构收藏
在coursedetail.html中添加js插槽,在插槽中写ajax请求:
{# js插槽 #}
{% block custum_js %}
{# 收藏的ajax #}
<script type="text/javascript">
//收藏的调用函数,三个参数:监听的dom对象(按钮),数据的id,数据的类型
function add_fav(current_elem, fav_id, fav_type) {
$.ajax({
cache: false,
type: "POST",
url: "{% url 'op:fav' %}",
data: {'fav_id': fav_id, 'fav_type': fav_type}, //像后端传递两个参数
async: true,
beforeSend: function (xhr, settings) {
//xhr:异步的ajax请求.
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function (data) {
if (data.status == 'fail') {
if (data.msg == '用户未登录') {
window.location.href = "{% url 'login' %}";
} else {
alert(data.msg)
}
}
else if (data.status == 'success') {
//修改该获取的dom对象的内容
current_elem.text(data.msg)
}
},
});
}
//课程的收藏
$(document).ready(function () {
$('#jsLeftBtn').on('click', function () {
//$(this):传的就是这个获取的按钮 :id=#jsLeftBtn的按钮
add_fav($(this), {{ course.id }}, 1);
});
});
//机构的收藏
$(document).ready(function () {
$('#jsRightBtn').on('click', function () {
//$(this):传的就是这个获取的按钮 :id=#jsRightBtn的按钮
add_fav($(this), {{ course.course_org.id }}, 2);
});
});
</script>
{% endblock %}
后端view处理逻辑,要使用form表单验证,所以在operations下新建form.py:
from django import forms #导入forms表单验证
from apps.operations.models import UserFavorite #导入要存储的数据库
class UserFavForm(forms.ModelForm):
class Meta:
model = UserFavorite #指定数据库
fields = ['fav_id','fav_type'] #筛选要存的字段
在views.py中导入即可使用。
apps/operations/views.py:
from django.shortcuts import render
# Create your views here.
from django.views.generic.base import View # 视图类
from apps.operations.form import UserFavForm # 表单验证类
from django.http import JsonResponse
from apps.operations.models import UserFavorite #用户收藏模型类
from apps.courses.models import Course #课程类
from apps.organizations.models import CourseOrg #机构类
from apps.organizations.models import Teacher #教师类
class AddFavView(View):
'''
用户收藏实现:
前台使用ajax请求post方法,把该请求的数据存到数据库中,这相当于提交了一个表单
1.当用户点击收藏按钮时,ajax请求提交,也就是进入该视图类了。
2.首先判断用户是否登录,如果没有登陆,那么就跳转到login页面进行登录。
3.如果用户登录了,那么就实例化表单验证,
如果该表单对象是不合法的,那么就返回错误信息
如果该表单对象是合法的,那么就会获取该表单中的fav_id和fav_type进一步操作。
4,获取到以后到数据库中查询用户是否已经收藏了该数据,也就是在数据库中查询是否有这条收藏记录,
如果有,那么就删除该条记录,(从已收藏到未收藏)
如果没有,就插入该条记录。(未收藏到已收藏)
'''
# POST方法
def post(self, request, *args, **kwargs):
# 先判断用户是否登录
if not request.user.is_authenticated:
return JsonResponse({
'status': 'fail',
'msg': '用户未登录'
})
# 实例化表单验证类
user_fav_form = UserFavForm(request.POST)
if user_fav_form.is_valid(): # 如果是合法的
fav_id = user_fav_form.cleaned_data['fav_id']
fav_type = user_fav_form.cleaned_data['fav_type']
#判断用户是否已经收藏
exist = UserFavorite.objects.filter(user=request.user,fav_id = fav_id,fav_type=fav_type)
if exist: #如果已经收藏,就删除该信息
exist.delete()
if fav_type ==1:
course = Course.objects.get(id=fav_id)
course.fav_nums-=1
course.save()
elif fav_type == 2:
courseorg = CourseOrg.objects.get(id=fav_id)
courseorg.fav_nums -= 1
courseorg.save()
elif fav_type == 3:
teacher = Teacher.objects.get(id=fav_id)
teacher.fav_nums-=1
teacher.save()
return JsonResponse({
'status':'success',
'msg':'收藏'
})
else:
#添加数据,创建对象
userfav = UserFavorite()
userfav.user = request.user
userfav.fav_id = fav_id
userfav.fav_type = fav_type
userfav.save()
return JsonResponse({
'status': 'success',
'msg': '已收藏'
})
else:
return JsonResponse({
'status': 'fail',
'msg': '参数错误'
})
在MXOnline中编写operatons app的总路由:
MXOnline/urls.py:
#用户操作operayions线相关路由
url(r'^op/',include(('apps.operations.urls','operations'),namespace='op'))
在operations下新建urls.py:
进入AddFavView视图类中进行处理。
from django.conf.urls import url
from apps.operations.views import AddFavView
urlpatterns = [
url(r'^fav/$',AddFavView.as_view(),name='fav')
]
运行:
![](https://img.haomeiwen.com/i22697958/f3e83c0e5799aa8e.png)
点击收藏后,变为已收藏。
![](https://img.haomeiwen.com/i22697958/ca4719a04d4f9570.png)
userfavitrate表中:
![](https://img.haomeiwen.com/i22697958/aa833c16c369b499.png)
再点击一次后,又变为收藏。
![](https://img.haomeiwen.com/i22697958/78b432bd0820207e.png)
数据库中的记录删除。
![](https://img.haomeiwen.com/i22697958/d191a2d2aefd6635.png)
机构收藏与之相同,不做演示。
提交github
网友评论