리자

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

HTML 

 

[code]

        // 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("");

                    }

                }

            });

        }

[/code]

 

 

Django

 

[code]

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)

[/code]

 

 

 

 

 

|

댓글 2개

그누파이를 만드시나요?
고생이 많으십니다. 화이팅!!
댓글을 작성하시려면 로그인이 필요합니다.
+
제목 글쓴이 날짜 조회
19-11-19 조회 1,259
19-11-08 조회 1,304
19-11-07 조회 1,304
19-11-07 조회 1,440
19-10-30 조회 1,157
19-10-25 조회 1,067
19-10-24 조회 1,129
19-10-24 조회 1,387
19-09-20 조회 5,621
19-08-07 조회 1,499
19-06-11 조회 1,122
19-06-09 조회 2,313
19-06-05 조회 2,004
19-06-04 조회 1,389
19-06-04 조회 1,761
19-06-03 조회 1,509
19-06-03 조회 1,294
19-06-03 조회 1,266
19-06-03 조회 3,726
19-06-02 조회 1,680
19-06-01 조회 1,962
19-06-01 조회 1,736
19-06-01 조회 1,741
19-06-01 조회 1,890
19-06-01 조회 1,970
19-05-31 조회 1,938
19-05-31 조회 2,389
19-05-31 조회 2,037
19-05-31 조회 1,654
19-05-31 조회 2,099