728x90

장고 온라인 강좌 로그인 처리가 매끄럽지 못한 거 같아서 jQuery ajax 로그인 처리 기능을 테스트하고 적어둔다.

 

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>로그인</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container pt-5">
    <div class="login-form">
        <div class="row">
            <div class="col-12">
                {{ error }}
            </div>
        </div>
        <form method="post" id="post-form">
            {% csrf_token %}
            <h2 class="text-center">로그인</h2>
            <div class="form-group">
                <input type="text" id="useremail" class="form-control" placeholder="user email 입력">
            </div>
            <div class="form-group">
                <input type="password" id="password" class="form-control" placeholder="비밀번호 입력">
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary btn-block">로그인</button>
            </div>
        </form>
        <p class="text-center"><a href="#" id="register">회원 가입</a></p>
    </div>
</div>
</body>
<script>
    $(document).on('submit''#post-form'function (e) {
        e.preventDefault();
        if($('#useremail').val() == ''){
            alert('email을 입력하세요');
            $('#useremail').focus();
            return false;
        }
 
        if($('#password').val() == ''){
            alert('비밀번호를 입력하세요');
            $('#password').focus();
            return false;
        }
 
        $.ajax({
            type: 'POST',
            url: '{% url "user:ajax_login" %}',
            data: {
                useremail: $('#useremail').val(),
                password: $('#password').val(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                action: 'post'
            },
            success: function (json) {
                if(json.status == 1){
                    document.getElementById("post-form").reset();
                    window.location.href = 'http://127.0.0.1:8000/';
                    alert('로그인되었습니다.');
                } else if(json.status == 0){
                    alert('로그인 정보를 확인하세요.');
                }
            },
            error: function (xhr, errmsg, err) {
                alert('에러가 발생했네요.' + errmsg);
                console.log(xhr.status + ": " + xhr.responseText); 
            }
        });
    });
</script>
</html>
 

 

 

views.py

완벽 동작하도록 로직을 수정했지만, Secure Coding까지 고려하지는 않은 상태다.

로그인에서 비밀번호가 일치하지 않거나, 아이디가 없거나 할 경우에 동일한 메시지를 출력해야 한다.

 

 
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password, check_password
from .models import User
 
# Create your views here.
def home(reqest):
    user_id = reqest.session.get('user')
 
    if user_id:
        user = User.objects.get(pk=user_id)
        return HttpResponse(user.useremail)
 
    return HttpResponse('Home')
 
 
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        useremail = request.POST.get('useremail'None)
        password = request.POST.get('password'None)
 
        res_data = {}
        try:
            user = User.objects.get(useremail=useremail)
            if check_password(password, user.password):
                # 비밀번호가 일치하면 세션 생성
                request.session['user'= user.id
                res_data['status'= '1'
            else:
                res_data['status'= '0'
            return JsonResponse(res_data)
        except User.DoesNotExist:
            # 대문자 User 임에 주의
            res_data['status'= '0'
            return JsonResponse(res_data)
 
        return render(request, 'login.html', res_data)
 
 
def logout(request):
    if request.session.get('user'):
        del(request.session['user'])
 
    return redirect('/user/login')
 
 

 

 

urls.py

from django.urls import path
from . import views
 
app_name = 'user'
urlpatterns = [
    path('register/', views.register, name='ajax_register'),
    path('login/', views.login, name='ajax_login'),
    path('logout/', views.logout),
]
 
 

 

참고자료

https://dev.to/thepylot/how-to-send-django-form-with-ajax-4bpo

 

How to send Django form with AJAX

What's up DEV Network? In this quick tutorial I am going to show you how to POST Django form without...

dev.to

 

728x90
블로그 이미지

Link2Me

,