django.contrib_auth
Django 인증 시스템을 사용하여 로그인 / 로그아웃 기능을 구현하는 방법을 알아보자!
accounts
app 생성 및 등록$ python manage.py startapp accounts
# settings.py
# Application definition
INSTALLED_APPS = [
'articles',
'accounts',
...
]
# accounts/urls.py
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
]
# crud/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
path('accounts/', include('accounts.urls'))
]
Session
을 Create
하는 과정
login()
login(request, user, backend=None)
get_user()
# account/urls.py
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', views.login, name='login')
]
# accounts/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login as auth_login
# Create your views here.
def login(request):
if request.method == 'POST':
# 로그인 처리를 해줌
form = AuthenticationForm(request, request.POST)
if form.is_valid():
auth_login(request, form.get_user())
return redirect('articles:index')
else:
# 비어있는 로그인 페이지 제공
form = AuthenticationForm()
context = {
'form' : form
}
return render(request, 'accounts/login.html', context)
<!-- accounts/login.html -->
{% extends 'base.html' %}
{% block content %}
<h1>Login</h1>
<form action="{% url 'accounts:login' %}" method="POST">
{% csrf_token %}
{{form.as_p}}
<input type="submit">
</form>
{% endblock content %}
<!-- base.html -->
<body>
<a href="{% url 'accounts:login' %}">로그인</a>
<hr>
{% block content %}
{% endblock content %}
...
</body>
</html
$ python manage.py createsuperuser
<!-- base.html -->
<body>
<div class="container">
<h3>안녕하세요, {{user}} 님!</h3>
<a href="{% url 'accounts:login' %}">로그인</a>
{% block content %}
{% endblock content %}
<hr>
</div>
</body>
</html>
django.contrib.auth.context_processors.auth
# settings.py
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
django.contrib.auth.context_processors.auth
{{ user }}
에 저장됨Session
을 Delete
하는 과정
logout()
logout(request)
# accounts/urls.py
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
]
# accounts/views.py
from django.contrib.auth import logout as auth_logout
def logout(request):
auth_logout(request)
return redirect('articles:index')
<!-- base.html -->
<body>
<div class="container">
<h3>안녕하세요, {{user}} 님!</h3>
<a href="{% url 'accounts:login' %}">로그인</a>
<form action="{% url 'accounts:logout' %}" method="POST">
{% csrf_token %}
<input type="submit" value="Logout">
</form>
{% block content %}
{% endblock content %}
<hr>
</div>
</body>
</html>