리자

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

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

파이썬 게시판 만들기

+
제목 글쓴이 날짜 조회
1년 전 조회 732
2년 전 조회 547
2년 전 조회 555
2년 전 조회 546
2년 전 조회 773
2년 전 조회 602
2년 전 조회 979
2년 전 조회 742
2년 전 조회 705
2년 전 조회 1,025
2년 전 조회 918
2년 전 조회 771
3년 전 조회 1,020
3년 전 조회 1,126
3년 전 조회 1,174
3년 전 조회 1,156
3년 전 조회 1,096
4년 전 조회 1,359
4년 전 조회 1,305
4년 전 조회 1,524
4년 전 조회 1,276
4년 전 조회 2,564
4년 전 조회 1,264
4년 전 조회 1,097
4년 전 조회 1,254
4년 전 조회 1,660
5년 전 조회 1,640
5년 전 조회 1,416
5년 전 조회 1,539
5년 전 조회 1,531
🐛 버그신고