Django CBV (2) - ๋กœ๊ทธ์ธ, ๋กœ๊ทธ์•„์›ƒ ๊ตฌํ˜„

2021. 5. 23. 14:25ใ†Backend/๐Ÿ Python

Urls.py

์ฒซ์ค„์˜ from django.contrib.auth.views import LogoutView, LoginView ์—์„œ
LoginView ์™€ LogoutView ๋ผ๋Š” ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›์•˜์Œ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

from django.contrib.auth.views import LogoutView, LoginView
from django.urls import path

from account.views import AccountCreateView, hello_world

app_name = "account"

urlpatterns = [
    path('hello_world', hello_world, name='hello_world'),
    path('create/', AccountCreateView.as_view(), name='create'),
    
    # login, logout ๋งคํ•‘ ์ฝ”๋“œ
    path('login/', LoginView.as_view(template_name='login.html'), name="login"),
    path('logout/', LogoutView.as_view(), name='logout'),
]

 

CBV์—์„œ๋Š”  login, logout ์„ ์œ„ํ•ด ๋”ฐ๋กœ views.py ๋‚ด๋ถ€์— ํ•จ์ˆ˜๋‚˜ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค

urls.py์—์„œ ๊ณง๋ฐ”๋กœ login.html๋กœ ๋กœ๊ทธ์ธ ํ˜•์‹(form)์„ ๋ Œ๋”๋ง ํ•ด์ค๋‹ˆ๋‹ค.

์•„๋ž˜์˜ login.html์„ ํ™•์ธํ•ด๋ด…์‹œ๋‹ค.

 

login.html

    <div style="text-align: center; max-width: 500px; margin: 4rem auto">
        <div>
            <h4>LOGIN</h4>
        </div>
        <div>
            <form action="" method="post">
                {% csrf_token %}
                {{ form }}
                <input type="submit">
            </form>
        </div>
    </div>

 

{{form}} ์€ urls.py์˜

path('login/', LoginView.as_view(template_name='login.html'), name="login")

์œ„ ์ฝ”๋“œ์—์„œ ์ •์˜ํ•œ ๋Œ€๋กœ, login.html๋กœ LoginvView์— ํ•ด๋‹นํ•˜๋Š” ๋‚ด์šฉ์„ {{form}}์˜ ํ˜•ํƒœ๋กœ ๋ณด๋‚ธ ๊ฒƒ ๋ฟ์ž…๋‹ˆ๋‹ค.

 

ํƒœ๊ทธ ๋‚ด๋ถ€์— {{form}} ๋งŒ ์ž‘์„ฑํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ login ํ™”๋ฉด์ด ์ž๋™์œผ๋กœ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค. (css๋Š” ๋”ฐ๋กœ ์ž…ํ˜”์Šต๋‹ˆ๋‹ค)

 

 

LogoutView.as_view()

logout์€ ๋”ฐ๋กœ htmlํŽ˜์ด์ง€๊ฐ€ ํ•„์š”์—†์Šต๋‹ˆ๋‹ค. ๊ทธ์ € ๋กœ๊ทธ์•„์›ƒ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ์ž‘๋™ํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

๋กœ๊ทธ์•„์›ƒ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅธ ํ›„ ์–ด๋””๋กœ redirect ๋  ์ง€๋งŒ ์ •ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

์ด๋ฅผ ์ •ํ•˜๊ธฐ ์œ„ํ•ด settings.py๋กœ ๊ฐ‘๋‹ˆ๋‹ค.

Settings.py

LOGIN_REDIRECT_URL = reverse_lazy('account:hello_world')
LOGOUT_REDIRECT_URL = reverse_lazy('account:login')

๋กœ๊ทธ์•„์›ƒ ํ›„์— redirect ๋  url์ด ์–ด๋–ค ๊ฒƒ์ธ์ง€, reverse_lazy() ๋ฉ”์†Œ๋“œ๋กœ ๋งคํ•‘ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ €๋Š” "account ์•ฑ ๋‚ด๋ถ€์˜ login" ์ด๋ผ๋Š” ์ด๋ฆ„์˜ url๋กœ ๋งคํ•‘ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.

 

์ฆ‰ ๋กœ๊ทธ์•„์›ƒ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅธ ํ›„์— ๋ณด์—ฌ์ค„ ํ™”๋ฉด์„ ๋”ฐ๋กœ ๋งŒ๋“ค ํ•„์š”์—†์ด, ๊ทธ์ € login.html๋กœ ๋งคํ•‘ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.