login logout - pai-plznw4me/django-initializer GitHub Wiki
Django ๊ธฐ๋ณธ ๋ด์ฅ
login๋ฐlogout๊ธฐ๋ฅ์ ๊ตฌํํ๋ค.
-
login
-
logout
1. project ์์ฑ
2. app ์์ฑ
3. project ์ ์ฑ ๋ฑ๋ก
4. migrate ์ํํ๊ธฐ
5. create super user (id : admin , pw : 1234)
-
settings.py์ ์๋ ์ฝ๋ ์ถ๊ฐ
# django settings.py
# ์์ฑํ app ๋ฑ๋ก
INSTALLED_APPS = [
...
'django.contrib.auth',
]
# pre installed app์์ ๋ฐ๋ผ๋ณด๋ templates ์์น
TEMPLATES = [
{
...
'DIRS': [str(BASE_DIR.joinpath('templates'))],
... - ํ๋ก์ ํธ ํด๋ ์๋ urls.py ์ ์๋ ์ฝ๋ ์ถ๊ฐ
โโโ <project name>
โโโurls.py < -- โ๏ธ
โโโ manage.py
- ์ถ๊ฐ ๋ ์ฝ๋
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
...
path('accounts/', include('django.contrib.auth.urls')),
path('accounts/', include('account.urls')), # <-- ์ฌ๋ฌ ์ฑ์ urls์ ์ค๋ณต ์ถ๊ฐ ํ ์ ์๋ค.
]Auth view ๋ชฉ๋ก
```python 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/// [name='password_reset_confirm'] accounts/reset/done/ [name='password_reset_complete']```/account/login ์ผ๋ก ์ ์์ ๋ณด์ฌ์ง๋ Web template ์ ๋ง๋ค์ด ๋ณด์
LoginView ๋ก ์ด๋ํ์. (auth app login view ๋ LoginView ์ ์ฌ์ฉํ๋ค. ๊ด๋ จ ์ค์ ์ด ํด๋น ๋ทฐ ํด๋์ค์ ์ ์ฅ ๋์ด ์๋ค.)
LoginView๋ฅผ ํ์ธํด๋ณด๋ฉด ์๋์ ๊ฐ์ ์ฝ๋๋ฅผ ํ์ธํด ๋ณผ ์ ์๋ค.
(โป LoginView ๋ from django.contrib.auth.views import LoginView ์ ์ ์ ๋์ด ์๋ค.)
class LoginView(RedirectURLMixin, FormView):
"""
Display the login form and handle the login action.
"""
form_class = AuthenticationForm
authentication_form = None
template_name = "registration/login.html" # <-- โ๏ธ ์ฌ๊ธฐ ๋ถ๋ถ์ ๋ณ๊ฒฝํ๋ค.
redirect_authenticated_user = False
extra_context = None
...์ ์ฝ๋๋ฅผ ๋ณด๋ฉด template_name = "registration/login.html" ๋ถ๋ถ์ template_name = "account/login.html"์ผ๋ก ๋ณ๊ฒฝํ๋ค.
templates/account/ page ํด๋น ๊ฒฝ๋ก์ login.html ์ ์์ฑํ๋ค.
์์ฑ๋ html ์ ์๋ ์ฝ๋๋ฅผ ์
๋ ฅํ๋ค.
<!-- templates/account/login.html -->
<h2>Log In</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log In</button>
</form>๋ก๊ทธ์ธ ํ ํน์ ์น ํ์ด์ง๋ก ์ด๋ํ๋๋ก ์ค์ ํ๋ค.
settings.py ์ ์ด๋ํ๊ณ ์ ํ๋ ์น ์ฃผ์๋ฅผ ๋ฑ๋กํ๋ค.
# settings.py
LOGIN_REDIRECT_URL = '/account/index'์ ์์ ์๋ account app view ์ index๊ฐ ๋ฑ๋ก ๋์ด ์๋ค๊ณ ๊ฐ์ ํ๋ค. )
๋ก๊ทธ์ธ ์ ํ๋ฉด User instance ์ ๋ณด์ธ user ์ ๋ณด๊ฐ html ๋ก ๋ค์ด์จ๋ค.
(์๋ ๊ทธ๋ฆผ์์ is_authenticated = True ์์ ๋ ์ฌ๊ฒจ ๋ณด์)

1.1 auth app ๋ฑ๋ก ๋จ๊ณ๋ฅผ ์งํํ๋ค๋ฉด ๋จ์ํ /accounts/logout url ๋ก ์ ์ํ๋ฉด ๋๋ค.
๋ก๊ทธ์ธ ํ์ด์ง์ ๊ฐ๊ฒ settings.py ์ logout ์ฑ๊ณต ์ ์ด๋ํ๋ ํ์ด์ง๋ฅผ ์ ์ํด ๋๋ค.
LOGOUT_REDIRECT_URL = 'home' # newhttps://wikidocs.net/71259 https://learndjango.com/tutorials/django-login-and-logout-tutorial