Django1.9.8 + Xadmin + Windows 快速搭建网站三

1.ajax 实现收藏取消收藏功能

 1 #收藏功能ajax
 2 function add_fav(current_elem, fav_id, fav_type) {
 3         $.ajax({
 4             cache: false,
 5             type: "POST",
 6             url: "{% url 'org:addFav' %}",
 7             data: {'fav_id': fav_id, 'fav_type': fav_type},
 8             async: true,
 9             beforeSend: function (xhr, settings) {
10                 xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");//此处只是将csrf_token的值传进去 不能使用{% csrf_token %}是生成一段html代码
11             },
12             success: function (data) {
13                 if (data.status == 'fail') {
14                     if (data.msg == '用户未登录') {
15                         window.location.href = "{% url 'login' %}";
16                     } else {
17                         alert(data.msg)
18                     }
19 
20                 } else if (data.status == 'success') {
21                     current_elem.text(data.msg)
22                 }
23             },
24         });
25     }
26 
27     $('.collectionbtn').on('click', function () {
28         add_fav($(this), {{ course_org.id }}, 2);
29     });

  view

 1 class addFavView(View):
 2     def post(self, request):
 3         favId = int(request.POST.get('fav_id',0))
 4         favType = int(request.POST.get('fav_type',0))
 5 
 6         if not request.user.is_authenticated():
 7             #判断用户登录状态
 8             return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type='application/json')
 9         exist_records = userFav.objects.filter(user=request.user, favId=favId, favType=favType)
10         if exist_records:
11             #如果存在该记录那么就是取消收藏
12             exist_records.delete()
13             return HttpResponse('{"status":"fail", "msg":"收藏"}', content_type='application/json')
14         else:
15             userfavourite = userFav()
16             #添加收藏记录
17             if int(favId) > 0 and int(favType) > 0:
18                 userfavourite.user = request.user
19                 userfavourite.favId = favId
20                 userfavourite.favType = favType
21                 userfavourite.save()
22                 return HttpResponse('{"status":"success", "msg":"已收藏"}', content_type='application/json')
23             else:
24                 return HttpResponse('{"status":"fail", "msg":"收藏出错!"}', content_type='application/json')

  url

1 url(r'^addFav/$',addFavView.as_view(),name="addFav"),

  html

1  <div class="btn fr collectionbtn  notlogin
2                  " data-favid="22" data-fav-type="1">
3                         收藏
4                     </div>

 2.添加评论信息

  view

 1 from django.http import HttpResponse
 2 class addCommentView(View):
 3     def post(self, request):
 4         #判断用户是否已经登录
 5         if not request.user.is_authenticated():
 6             return HttpResponse('{"status":"fail","msg":"用户未登录"}', content_type='application/json')
 7 
 8         #取到id 已经评论内容
 9         course_id = int(request.POST.get('course_id', 0))
10         comments = request.POST.get('comments', '')
11         #简单验证
12         if course_id and comments:
13             #将信息保存到数据库
14             course_comments = userCourseComment()
15             course_comments.course = courses.objects.get(id=course_id)
16             course_comments.comments = comments
17             course_comments.user = request.user
18             course_comments.save()
19             #返回成功信息
20             return HttpResponse('{"status":"success","msg":"添加成功"}', content_type='application/json')
21         else:
22             #返回失败信息
23             return HttpResponse('{"status":"fail","msg":"添加失败"}', content_type='application/json')

  url

url(r'^addComment/$',addCommentView.as_view(), name="addCourseComment"),

  AJAX

<script>
//添加评论
$('#js-pl-submit').on('click', function () {
    var comments = $("#js-pl-textarea").val()
    if (comments == "") {
        alert("评论不能为空")
        return
    }
    $.ajax({
        cache: false,
        type: "POST",
        url: "{% url 'course:addCourseComment' %}",
        data: {course_id: {{ course.id }}, comments: comments},
        async: true,
        beforeSend: function (xhr, settings) {
            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') {
                alert('评论成功!')
                window.location.reload();//刷新当前页面.
            }
        },
        error: function(error) {
          alert('ajax 失败!')
        }
    });
});
</script>

 3.使用django自带登录验证功能

  1.在utils添加mixin_utils.py文件了(定义一个基础类)

1 from django.contrib.auth.decorators import login_required
2 from django.utils.decorators import method_decorator
3 
4 
5 class LoginRequiredMixin(object):
6     @method_decorator(login_required(login_url='/login/'))
7     def dispatch(self, request, *args, **kwargs):
8         return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)

  2.在view中继承该基础类(在url路由到类的方法的时候就会自动判断用户是否登录若未登录则自动跳转到配置的login_url 的路径下)

from utils.mixin_utils import loginRequiredMixin
class XXX(loginRequiredMixin View):
    def method(self, request):
        ..........

 

posted @ 2017-10-26 12:35  WangLC  阅读(401)  评论(0编辑  收藏  举报