토큰을 전송해서 ajax 로 조회하는 방법 > 파이썬 게시판 만들기

파이썬 게시판 만들기

그누 어디까지 써봤니? 나는 파이썬까지 써봤어!

토큰을 전송해서 ajax 로 조회하는 방법 정보

토큰을 전송해서 ajax 로 조회하는 방법

본문

HTML 

 


        // Username validation (3~20 characters, alphanumeric only)
        var username = $("#id_username").val();
        if (!/^[a-z0-9]{3,20}$/.test(username)) {
            $("#username-error").text("{{ form.username.help_text }}");
            valid = false;
        } else {
            {% comment %} $("#username-error").text(""); {% endcomment %}
            $.ajax({
                url: '/accounts/username_exists/',
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}',
                },
                data: {
                    'username': username
                },
                dataType: 'json',
                async: false, // Wait for the response
                success: function (data) {
                    if (data.is_exists) {
                        $("#username-error").text("이미 존재하는 아이디 입니다.");
                        valid = false;
                    } else {
                        $("#username-error").text("");
                    }
                }
            });
        }

 

 

Django

 


from django.views.decorators.csrf import csrf_protect
rom django.views.decorators.http import require_POST
 
@csrf_protect # csrf 토큰이 넘어오지 않으면 403 에러를 발생시킨다. 반드시 POST로만 사용해야 한다.
@require_POST
def username_exists(request):
    username = request.POST.get('username')
 
    if User.objects.filter(username=username).exists():
        response_data = {'is_exists': True}
    else:
        response_data = {'is_exists': False}
 
    return JsonResponse(response_data)

 

 

 

 

 

추천
4
  • 복사

댓글 2개

© SIRSOFT
현재 페이지 제일 처음으로