from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
import json
@csrf_exempt # 示範用,生產請用 csrf_token
def check_email(request):
if request.method != 'POST':
return JsonResponse({'error': 'POST only'}, status=405)
email = request.POST.get('email', '').strip()
if not email:
return JsonResponse({'exists': False})
exists = User.objects.filter(email__iexact=email).exists()
return JsonResponse({'exists': exists})
# urls.py
path('api/check-email/', views.check_email, name='check_email')
$('#email').on('blur', function() {
var email = $(this).val();
if (!email) return;
$.post('/api/check-email/', {email: email}, function(res) {
if (res.exists) {
$('#email-msg').text('此 Email 已註冊').addClass('error');
$('#submit-btn').prop('disabled', true);
} else {
$('#email-msg').text('可使用').removeClass('error');
$('#submit-btn').prop('disabled', false);
}
}, 'json');
});
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['POST'])
def check_email_drf(request):
email = request.data.get('email', '')
exists = User.objects.filter(email__iexact=email).exists()
return Response({'exists': exists})
@ensure_csrf_cookie + 前端攜帶 X-CSRFToken)django-ratelimit 或 DRF Throttling)Django 回傳 JSON 極簡單:JsonResponse 或 DRF Response。前端 $.post/fetch 配合即時驗證,提升使用者體驗。