리자

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

· 2023-07-27 (목) 17:20:07 · 1091 · 2

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개

그누파이를 만드시나요?
고생이 많으십니다. 화이팅!!
좋아요.
댓글을 작성하시려면 로그인이 필요합니다.

파이썬 게시판 만들기

121건

+
제목 글쓴이 날짜 조회
24-02-08 조회 1,028
24-01-19 조회 849
23-12-24 조회 838
23-08-03 조회 869
23-07-27 조회 1,092
23-07-27 조회 957
23-07-18 조회 1,359
23-07-12 조회 1,074
23-07-12 조회 1,076
23-07-07 조회 1,365
23-06-30 조회 1,305
23-06-28 조회 1,132
22-09-04 조회 1,436
22-08-17 조회 1,480
22-07-22 조회 1,492
22-05-24 조회 1,512
22-02-02 조회 1,443
21-12-29 조회 1,721
21-12-24 조회 1,639
21-12-15 조회 1,874
21-05-29 조회 1,642
21-05-01 조회 2,931
21-03-16 조회 1,638
21-03-16 조회 1,454
21-03-01 조회 1,570
21-02-16 조회 2,044
21-01-02 조회 2,037
20-12-14 조회 1,749
20-12-02 조회 1,942
20-12-02 조회 1,951