리자

토큰을 전송해서 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-12-19 조회 1,772
19-12-18 조회 1,737
19-12-17 조회 1,662
19-12-16 조회 1,328
19-12-15 조회 1,464
19-12-14 조회 1,368
19-12-13 조회 1,706
19-12-13 조회 1,619
19-12-12 조회 1,294
19-12-12 조회 1,083
19-12-12 조회 1,347
19-12-11 조회 1,990
19-12-11 조회 1,447
19-12-10 조회 1,147
19-12-10 조회 1,533
19-12-10 조회 1,138
19-12-09 조회 1,387
19-12-07 조회 1,599
19-12-07 조회 1,376
19-12-06 조회 1,773
19-12-06 조회 1,427
19-12-05 조회 1,372
19-12-05 조회 1,287
19-12-04 조회 2,689
19-12-04 조회 1,200
19-12-03 조회 2,755
19-12-03 조회 1,191
19-12-03 조회 1,295
19-11-19 조회 1,374
19-11-19 조회 1,571