
# pragmatic/accountapp/urls.py
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import path
from accountapp.views import hello_world, AccountCreateView
app_name = "accountapp"
urlpatterns = [
path('hello_world/', hello_world, name='hello_world'),
path('login/', LoginView.as_view(template_name = 'accountapp/login.html'), name='login'), # 추가
path('logout/', LogoutView.as_view(), name='logout'), # 추가
path('create/', AccountCreateView.as_view(), name='create'),
]
{% extends 'base.html' %} <!-- extends 를 이용하여 base 가져오기 -->
{% block content %}
<div style="text-align: center">
<div>
<h4>Login</h4>
</div>
<div>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary">
</form>
</div>
</div>
{% endblock%}




header.html 파일에서 nav4 를 login 으로 변경해준다.
그 Login 을 a(anchor) 태그로 감싸 우리가 만든 login 페이지 경로로 갈 수 있도록 url 기입
{% url 'accountapp:login' %}<a href="{% url 'accountapp:logout' %}">분기문을 넣어주어 유저라는 것을 판단해주고 is_authenticated 구문 사용
{% if not user.is_authenticated %} {% else %}login, logout 을 완성하고 나서 다시 갈 경로 next 를 얻어줘야 하기 떄문에 get 방식으로 next 라는 값을 넘겨준다.
?next= {{ request.path }} : request.path 라는 인자를 넘겨줄것<!-- pragmatic/templates/header.html -->
<div class="pragmatic_header">
<div>
<h1 class="pragmatic_logo">Prgmatic</h1>
</div>
<div>
<span>nav1</span>
<span>nav2</span>
<span>nav3</span>
{% if not user.is_authenticated %}
<a href="{% url 'accountapp:login' %}?next= {{ request.path }}">
<span>login</span>
</a>
{% else %}
<a href="{% url 'accountapp:logout' %}?next= {{ request.path }}">
<span>logout</span>
</a>
{% endif %}
</div>
</div>
logout 을 누르기

원래 있었던 곳 hello_world 로 돌아오는 것을 볼 수 있다.
url 부분의 ?next= 뒤에 우리가 원래 있었던 경로 (account/hello_world/) 가 넘겨졌음을 볼 수 있다.

로그인 누르면 로그인 페이지로 이동

다시 로그인을 하기


# pragmatic/pragmatic/settings.py
from django.urls import reverse_lazy
...
# 맨 아래에 다음 코드 추가
LOGIN_REDIRECT_URL = reverse_lazy('accountapp:hello_world')
LOGOUT_REDIRECT_URL = reverse_lazy('accountapp:login')



path('login/', LoginView.as_view(template_name = 'accountapp/login.html'), name='login'),
# 중간에 template_name 부분에서 띄어쓰기 제거 -> 정상 작동