login_or_not - pai-plznw4me/django-initializer GitHub Wiki

login ์—ฌ๋ถ€์— ๋”ฐ๋ผ ๋‹ค๋ฅด๊ฒŒ page ์„ ๋ณด์—ฌ์ฃผ๊ณ  ์‹ถ์„๋•Œ

  1. views
  2. html

2๊ฐ€์ง€ ๊ด€์ ์—์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ์ฝ”๋”ฉํ• ์ˆ˜ ์žˆ๋‹ค. skeleton ์ฝ”๋“œ๋ฅผ ์•„๋ž˜์— ์ ์–ด ๋‘”๋‹ค.

Skeleton

login ์ด ๋˜๋ฉด authenticate ์—์„œ user ์ •๋ณด๋ฅผ ์ค€๋‹ค.

views.py

from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
    # A backend authenticated the credentials
else:
    # No backend authenticated the credentials

templates

<!-- templates/home.html-->
{% if user.is_authenticated %}
  Hi {{ user.username }}!
{% else %}
  <p>You are not logged in</p>
{% endif %}

๋กœ๊ทธ์ธ ์—ฌ๋ถ€ checking ํ•˜๊ธฐ

skeleton code 1 : if ๊ตฌ๋ฌธ, is_authenticated ์‚ฌ์šฉ

  • ๋กœ๊ทธ์ธ ํ•œ ํ›„์— ํ•ด๋‹น function ์— ์ ‘๊ทผํ•˜๋ฉด ๋กœ๊ทธ์ธ ์—ฌ๋ถ€์— ๋”ฐ๋ผ์„œ ๋‹ค๋ฅด๊ฒŒ ์‹คํ–‰๋จ์„ ์•Œ์ˆ˜ ์žˆ๋‹ค. reference
def only_login(request):
    if request.user.is_authenticated:
        return HttpResponse('Login user')
    elif request.user.is_authenticated is None:
        return HttpResponse('Not login user')

skeleton code : @login_required ์‚ฌ์šฉ

  • ๋กœ๊ทธ์ธ ํ•œ ํ›„์— ํ•ด๋‹น function ์— ์ ‘๊ทผํ•˜๋ฉด ๋กœ๊ทธ์ธ ์—ฌ๋ถ€์— ๋”ฐ๋ผ์„œ ๋‹ค๋ฅด๊ฒŒ ์‹คํ–‰๋จ์„ ์•Œ์ˆ˜ ์žˆ๋‹ค.
@login_required
def only_login(request):
    return HttpResponse('Login success!')