Python/초간단 장고 Django

Django 초간단 게시판 7. log in, log out

컴닥 2021. 5. 28. 13:17
반응형

1. login

장고에는 'django.contrib.auth' 앱이 설치되어 있다. 

# config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth', # !!!
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'board.apps.BoardConfig',
]

 

'config/urls.py'로 위 앱에 대한 url을 설정해주자. 

# config/urls.py

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

urlpatterns = [
    path('', include('board.urls')),
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('board/', include('board.urls'), name='board'),
]

 

브라우저에서 '[서버주소]/accounts/'에 접속하면,
다음 화면을 볼 수 있다. 

Using the URLconf defined in config.urls, Django tried these URL patterns, in this order:

[name='index']
create/ [name='create']
<int:pk>/ [name='detail']
<int:pk>/update/ [name='update']
<int:pk>/delete/ [name='delete']
admin/
accounts/ login/ [name='login']
accounts/ logout/ [name='logout']
accounts/ password_change/ [name='password_change']
accounts/ password_change/done/ [name='password_change_done']
accounts/ password_reset/ [name='password_reset']
accounts/ password_reset/done/ [name='password_reset_done']
accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/ reset/done/ [name='password_reset_complete']
board/
The current path, accounts/, didn’t match any of these.

로그인 아웃에 대한 다양한 url이 있다. 
장고는 모든 걸 준비해 두었구나 싶다. 

 

이제 장고를 믿고 ~!
브라우저에서 '[서버주소]/accounts/login'에 접속하면
다음 에러를 볼 수 있다. ㅎ

Exception Type: TemplateDoesNotExist
Exception Value: registration/login.html

 

'registration/login.html'만 만들면 되는 구나... 
그런데 어디에?

 

startapp으로 생성한 앱이 아니니까 어디에 만들어야 할 지 애매한 느낌이다. 
이럴 때 쓰라고 준비된 설정이 있다. 

# config/settings.py
TEMPLATES = [
    {
        ...
        'DIRS': [BASE_DIR / 'templates'],
        ...
    },
]

템플릿 파일을 찾을 때 'BASE_DIR/templates' 폴더도 뒤져라~!
연산자 오버로딩을 사용해 연산자 / 으로 기존의 joinpath를 대체했다. 
재미있는 트릭이다. 문법적 설탕이라고 싫어하는 사람도 있겠지만....ㅎㅎ

 

이제 templates/registration/login.html 을 만들어 보자. 

<!-- templates/registration/login.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>Log In</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Log In</button>
</form>
</body>
</html>

 

다시 '[서버주소]/accounts/login'에 접속하면
다음 화면을 볼 수 있다. 

드디어~!!!!

 

그런데 로그인을 해보면 다음과 같은 경고가 뜬다. 

The current path, accounts/profile/, didn’t match any of these.

로그인을 하면 프로필 url로 넘어간다. ㅠ,.ㅠ

 

config/settings.py에 다음 설정을 추가해서 해결할 수 있다. 

# config/settings.py
LOGIN_REDIRECT_URL = '/'

 

2. logout

 

아까 우리는 로그아웃 링크를 봤었다. 

accounts/ logout/ [name='logout']

 

이 링크를 이용해서 로그아웃하면 다음 화면을 보게 된다는 문제가 있는데.....

 

config/settings.py에 다음 설정을 추가해서 해결할 수 있다. 

# config/settings.py
LOGOUT_REDIRECT_URL = '/'

 

로그인/로그아웃 완성~!

완성된 로그아웃을 게시판에도 적용한다..

<!--board/templates/board/article_list.html-->
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% if object_list %}
    <ul>
        {% for each in object_list  %}
        <li>
            <a href="{% url 'detail' each.id%}">
            {{each.id}} / {{each.author}} / {{ each.title }} / {{each.created_at}}
            </a>
        </li>
        {% endfor %}
    </ul>
    {% else %}
    <p>목록이 비었습니다.</p>
    {% endif %}

    {% if is_paginated %}
    <ul>
        {% if page_obj.has_previous %}
        <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
        {% else %}
        <li><span>&laquo;</span></li>
        {% endif %}

        {% for i in paginator.page_range %}
            {% if page_obj.number == i %}
        <li><span>{{ i }} <span>(current)</span></span></li>
            {% else %}
        <li><a href="?page={{ i }}">{{ i }}</a></li>
            {% endif %}
        {% endfor %}
        {% if page_obj.has_next %}
        <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li>
        {% else %}
        <li><span>&raquo;</span></li>
        {% endif %}
    </ul>
    {% endif %}
    <div><a href="{% url 'create' %}">글 등록</a></div>
    {% if user.is_authenticated %}
    <div><p>Hi {{ user.username }}!</p></div>
    <div><a href="{% url 'logout' %}">Log Out</a></div>
    {% else %}
    <div><p>You are not logged in</p></div>
    <div><a href="{% url 'login' %}">Log In</a></div>
    {% endif %}
</body>
</html>

 

참고 : https://learndjango.com/tutorials/django-login-and-logout-tutorial

반응형