장고 비로그인시 접근제한

<프론트>|2021. 1. 13. 22:36
반응형

html 추가할부분

<!--비로그인 실행할부분에 로그인html을 넣어줬다/ 비로그인상태면 로그인창으로 이동시켜줌.
로그인html에서 Post request가 발생하면 view에서 받아오는걸로 해놨기 때문에 로그인html만 추가하면끝이다 간단하다-->

{% if user.is_authenticated %}
로그인상태일때 실행할부분
{%else%}
비로그인시 실행할부분
{%endif%}

views.py에서 추가할부분

(로그인 함수 부분에서 login(reqest,result) 추가해줘야한다)

(추가안하면 인증만 하는거고 render해서 다른 html넘어갈때 비로그인상태다. 저거 추가하면 로그인상태로 쭉 유지해준다, ~/admin에서 로그인한거랑 똑같아짐)

(로그아웃하고싶을땐 전 포스팅 로그아웃 참조하기)

def Login(request):

    if request.method == 'POST':
        id = request.POST.get('userid','')
        pw = request.POST.get('userpw', '')

        result = authenticate(username=id, password=pw)

        if result :
            print("로그인 성공!")
            login(request, result)
            return render(request, 'mainapp/index.html')

        else:
            print("실패")
            return render(request, 'mainapp/Login.html')

    return render(request, 'mainapp/Login.html')

views.py에서 에러나면 저것들을 import해주자.

from django.contrib.auth import authenticate
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.contrib.auth import login

 

반응형

'<프론트>' 카테고리의 다른 글

kibana dashboard 구성 가이드라인  (0) 2021.01.13
장고 로그아웃 (django logout)  (0) 2021.01.13

댓글()