리자

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

그누파이를 만드시나요?
고생이 많으십니다. 화이팅!!
댓글을 작성하시려면 로그인이 필요합니다.
+
제목 글쓴이 날짜 조회
24-02-08 조회 1,035
24-01-19 조회 854
23-12-24 조회 846
23-08-03 조회 878
23-07-27 조회 1,099
23-07-27 조회 966
23-07-18 조회 1,374
23-07-12 조회 1,084
23-07-12 조회 1,085
23-07-07 조회 1,388
23-06-30 조회 1,320
23-06-28 조회 1,143
22-09-04 조회 1,446
22-08-17 조회 1,491
22-07-22 조회 1,506
22-05-24 조회 1,523
22-02-02 조회 1,456
21-12-29 조회 1,733
21-12-24 조회 1,653
21-12-15 조회 1,889
21-05-29 조회 1,654
21-05-01 조회 2,941
21-03-16 조회 1,646
21-03-16 조회 1,461
21-03-01 조회 1,577
21-02-16 조회 2,050
21-01-02 조회 2,046
20-12-14 조회 1,759
20-12-02 조회 1,953
20-12-02 조회 1,963