Django에서 제공하는 Authentication 기능을 이용해 간단한 로그인 기능을 구현해 보도록 하겠습니다.
# blog/urls.py
from django.urls import include, path
urlpatterns = [
path('auth/', include('django.contrib.auth.urls')),
path('login/', views.login_view, name='login'),
]
# blog/urls.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, '로그인 되었습니다.')
return redirect('login')
else:
messages.error(request, '아이디 또는 비밀번호가 올바르지 않습니다.')
return render(request, 'blog/login.html')
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">{{ message }}</div>
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<div class="form-group">
<label for="username">아이디</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">비밀번호</label>
<input type="password" name="password" class="form-control">
</div>
<button type="submit" class="btn btn-primary">로그인</button>
</form>
from django.urls import include, path
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
path('auth/login/', LoginView.as_view(), name='login'),
path('auth/logout/', LogoutView.as_view(), name='logout'),
]
from django.views.generic.edit import FormView
from django.contrib.auth import authenticate, login
from django.contrib import messages
from django.urls import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
class LoginView(FormView):
template_name = 'login.html'
form_class = AuthenticationForm
success_url = reverse_lazy('home')
def form_valid(self, form):
user = form.get_user()
login(self.request, user)
messages.success(self.request, '로그인 되었습니다.')
return super().form_valid(form)
def form_invalid(self, form):
messages.error(self.request, '아이디 또는 비밀번호가 올바르지 않습니다.')
return super().form_invalid(form)
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">{{ message }}</div>
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<div class="form-group">
<label for="{{ form.username.id_for_label }}">아이디</label>
{{ form.username }}
</div>
<div class="form-group">
<label for="{{ form.password.id_for_label }}">비밀번호</label>
{{ form.password }}
</div>
<button type="submit" class="btn btn-primary">로그인</button>
</form>