리자

토큰을 전송해서 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개

그누파이를 만드시나요?
고생이 많으십니다. 화이팅!!
댓글을 작성하시려면 로그인이 필요합니다.
+
제목 글쓴이 날짜 조회
20-11-27 조회 1,561
20-09-06 조회 1,691
20-08-17 조회 2,340
20-07-19 조회 2,335
20-07-13 조회 3만
20-06-28 조회 1,833
20-05-07 조회 1,761
20-05-06 조회 1,709
20-04-19 조회 1,359
20-02-12 조회 1,738
20-02-07 조회 2,171
19-12-31 조회 2,161
19-12-31 조회 2,099
19-12-30 조회 2,012
19-12-29 조회 1,725
19-12-29 조회 2,201
19-12-28 조회 2,216
19-12-28 조회 3,772
19-12-28 조회 3,866
19-12-27 조회 2,945
19-12-27 조회 2,344
19-12-27 조회 3,196
19-12-26 조회 1,901
19-12-26 조회 1,806
19-12-25 조회 1,694
19-12-24 조회 2,073
19-12-23 조회 2,567
19-12-22 조회 2,309
19-12-21 조회 1,772
19-12-20 조회 1,632