리자

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

· 2023-07-27 (목) 17:20:07 · 1046 · 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 조회 981
24-01-19 조회 806
23-12-24 조회 801
23-08-03 조회 826
23-07-27 조회 1,047
23-07-27 조회 920
23-07-18 조회 1,325
23-07-12 조회 1,035
23-07-12 조회 1,041
23-07-07 조회 1,330
23-06-30 조회 1,259
23-06-28 조회 1,091
22-09-04 조회 1,401
22-08-17 조회 1,439
22-07-22 조회 1,456
22-05-24 조회 1,473
22-02-02 조회 1,403
21-12-29 조회 1,679
21-12-24 조회 1,605
21-12-15 조회 1,831
21-05-29 조회 1,607
21-05-01 조회 2,888
21-03-16 조회 1,599
21-03-16 조회 1,421
21-03-01 조회 1,537
21-02-16 조회 2,001
21-01-02 조회 1,993
20-12-14 조회 1,718
20-12-02 조회 1,900
20-12-02 조회 1,900