zoukankan      html  css  js  c++  java
  • [ecommerce2] 106 Login Required Mixin

    功能:实现显示订单时,必须已经通过django授权了,才能访问相关的view

    #       modified:   orders/mixins.py

    #       modified:   orders/views.py

    首先我们import login_requiredmethod_decorator,然后通过修改dispatch函数来实现LoginRequired功能

    参考

    django.utils.decorators

    method_decorator(decorator)

    Converts a function decorator into a method decorator. See decorating class-based views for example usage.

     

    login_required(redirect_field_name='next'login_url=None)

    As a shortcut, you can use the convenient login_required() decorator:

    login_required() does the following:

    • If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/.
    • If the user is logged in, execute the view normally. The view code is free to assume the user is logged in.

    By default, the path that the user should be redirected to upon successful authentication is stored in a query string parameter called "next". If you would prefer to use a different name for this parameter, login_required() takes an optional redirect_field_name parameter:

    1. 定义类 LoginRequiredMixin,给dispatch函数增加装饰器login_required

    orders/mixins.py

    +from django.contrib.auth.decorators import login_required
    +from django.utils.decorators import method_decorator
    
    
    +class LoginRequiredMixin(object):
    +	@method_decorator(login_required)
    +	def dispatch(self, request, *args, **kwargs):
    +		return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs)
    

    2. OrderList添加基类LoginRequiredMixin

    则该view需要登录之后才能访问, 输入http://127.0.0.1:8001/orders,如果当前用户并没有登录,则自动跳转到http://127.0.0.1:8001/accounts/login/?next=/orders/

    实现LoginRequired功能之后,传递过来的user_id则都为已登录的user_id,取值可以直接从request_user_id取,不需要再从session里面获取

     orders/views.py

    -from .mixins import CartOrderMixin
    +from .mixins import CartOrderMixin, LoginRequiredMixin
     
    -class OrderList(ListView):
    +class OrderList(LoginRequiredMixin, ListView):
     	queryset = Order.objects.all()
     
     	def get_queryset(self):
    -		user_check_id = self.request.session.get("user_checkout_id")
    +		user_check_id = self.request.user.id
     		user_checkout = UserCheckout.objects.get(id=user_check_id)
     		return super(OrderList, self).get_queryset().filter(user=user_checkout)
    
  • 相关阅读:
    [转]趣题:一个n位数平均有多少个单调区间?---- From Matrix67
    2015编程之美复赛
    Codeforces Round #304 (Div. 2)
    HDU 5226
    HDU 5225
    HDU 3666
    HDU 4598
    Codeforces Round #303 (Div. 2) E
    编程之美初赛第二场AB
    2015 编程之美初赛第一场 AC题
  • 原文地址:https://www.cnblogs.com/2dogslife/p/6557609.html
Copyright © 2011-2022 走看看