django登录验证(状态保持)

设置book应用下的页面需要登录才能访问
user/views.py

def login(request):
      ...
      #部分省略
    user=User.objects.filter(username=username,password=my_md5(password))
    if user:
      #将用户的username保存到session中
      request.session["login_user"] =username

book/views.py

#验证是否登录的装饰器
def check_user(func):
    def inner(*args, **kwargs):
        #判断是否登录
        username = args[0].session.get("login_user", "")
        if username == "":
            #保存当前的url到session中
            args[0].session["path"] = args[0].path
            #重定向到登录页面
            return redirect(reverse("user:login"))
        return func(*args, **kwargs)

    return inner


@check_user
def book_list(request):
    book_list = BookInfo.objects.all()
    return render(request, "book/book_list.html",     {"book_list": book_list})


@check_user
def book_detail(request, bid):
    book = BookInfo.objects.get(id=bid)
    return render(request, "book/book_detail.html", {"book": book})


@check_user
def index(requests):
    return render(requests, "book/index.html", {})

你可能感兴趣的:(django登录验证(状态保持))