1. 程式人生 > >django從零開始-視圖

django從零開始-視圖

cookie rec admin none 分享圖片 migrate direct nbsp turn

1.處理的登錄請求

views文章中添加登錄函數login_action

def login_action(request):
    if request.method == POST:
        username = request.POST.get(username,‘‘)
        password = request.POST.get(password, ‘‘)
        if username == admin and password == admin:
            return HttpResponse(登錄成功)
        
else: return render(request,index.html,{error:用戶名或者密碼錯誤})

添加url路由

  

 url(r^login_action$,views.login_action),

2.登錄成功頁面

創建event_manage.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>發布會管理</title>
</
head> <body> <h1> <center>登錄成功</center> </h1> </body> </html>

改寫views.py的登錄函數,返回一個頁面

def login_action(request):
    if request.method == POST:
        username = request.POST.get(username,‘‘)
        password = request.POST.get(password, ‘‘)
        
if username == admin and password == admin: return HttpResponseRedirect(/event_manage/) #return render(request,‘event_manage.html‘)#BUILD2 #return HttpResponse(‘登錄成功‘) else: return render(request,index.html,{error:用戶名或者密碼錯誤}) def event_manage(request): return render(request,event_manage.html)

改下url路由

  url(r^event_manage/$,views.event_manage),

3.cookie and seeion

在這裏我們使用seeion

  1. 更改試圖函數技術分享圖片

  2. 編輯html文件接受session技術分享圖片

  3. 數據庫遷移
     python .\manage.py migrate

4.認證系統

  •   登錄admin後臺
    • 創建用戶
       python .\manage.py createsuperuser

  • 引用認證登錄
    • 修改login函數
      • def login_action(request):
            if request.method == POST:
                username = request.POST.get(username,‘‘)
                password = request.POST.get(password, ‘‘)
                user = auth.authenticate(username = username, password = password)
                if user is not None:
                    auth.login(request,user)
                #if username == ‘admin‘ and password == ‘admin‘:
                
                    response =  HttpResponseRedirect(/event_manage/)
                    request.session[user] = username
                    return  response
                    #return render(request,‘event_manage.html‘)#BUILD2
                    #return HttpResponse(‘登錄成功‘)
                else:
                    return  render(request,index.html,{error:用戶名或者密碼錯誤})

  • 使用裝飾器 關窗
    • 使用自帶login_required裝飾登錄後才能展示的函數
    • 修改url路由

django從零開始-視圖