토큰을 전송해서 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개
고생이 많으십니다. 화이팅!!
게시판 목록
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|
| 91 | 4년 전 | 1162 | ||
| 90 | 5년 전 | 1294 | ||
| 89 | 5년 전 | 1858 | ||
| 88 | 5년 전 | 1894 | ||
| 87 | 5년 전 | 28249 | ||
| 86 | 5년 전 | 1424 | ||
| 85 | 5년 전 | 1291 | ||
| 84 | 5년 전 | 1311 | ||
| 83 | 5년 전 | 963 | ||
| 82 | 5년 전 | 1342 | ||
| 81 | 5년 전 | 1750 | ||
| 80 | 5년 전 | 1739 | ||
| 79 | 5년 전 | 1669 | ||
| 78 | 5년 전 | 1576 | ||
| 77 | 5년 전 | 1275 | ||
| 76 | 5년 전 | 1779 | ||
| 75 | 5년 전 | 1796 | ||
| 74 | 5년 전 | 3252 | ||
| 73 | 5년 전 | 3417 | ||
| 72 | 5년 전 | 2506 | ||
| 71 | 5년 전 | 1846 | ||
| 70 | 5년 전 | 2708 | ||
| 69 | 5년 전 | 1454 | ||
| 68 | 5년 전 | 1383 | ||
| 67 | 5년 전 | 1240 | ||
| 66 | 5년 전 | 1603 | ||
| 65 | 5년 전 | 2067 | ||
| 64 | 5년 전 | 1809 | ||
| 63 | 5년 전 | 1316 | ||
| 62 | 5년 전 | 1158 |

댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기