Django_session登录状态保持

1、url

from django.contrib import admin
from django.urls import path,include
from . import views

urlpatterns = [
    path('indexlog/', views.indexlog,name='indexlog'),
    path('log_in/', views.LResponse.as_view(),name='log_in'),
    path('log_out/', views.log_out,name='log_out'),
]

2、views

from django.shortcuts import render,reverse,redirect
from django.http import HttpResponse
from django.views import View
# Create your views here.

def indexlog(request):
    username = request.session.get("username","未登录")
    return render(request,'log_in_out/index.html',context={'username':username})

class LResponse(View):
    def get(self,request):
        return render(request,'log_in_out/log_in.html')


    def post(self,request):
        username = request.POST.get('username')
        print(username)
        request.session['username'] = username
        request.session.set_expiry(0)
        return redirect(reverse('indexlog'))

def log_out(request):
    request.session.flush()
    return redirect(reverse('indexlog'))

3、login.html




    
    登陆


{% csrf_token %} {# #}

4、index.html




    
    首页


欢迎:{{ username }}
登录
退出

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