$(document).ready(function(){
jQuery.ajaxSetup({
beforeSend: function(xhr, settings){
function getCookie(n) {
var cookieValue = null;
if(document.cookie&&document.cookie != ''){
var cookies = document.cookie.split(';');
for(var i = 0; i < cookies.length; i++){
var cookie = jQuery.trim(cookies[i]);
if(cookie.substring(0, n.length + 1) == (n + '=')){
cookieValue = decodeURIComponent(cookie.substring(n.length + 1));
break;
}
}
}
return cookieValue;
}
if(!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))){
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
jQuery("#em").on("keyup", function () {
var error = document.getElementById("erremail");
var pattern = /^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i;
if(pattern.test(this.value)){
jQuery.ajax({
method:"POST",
url:"http://mysite.ru/email_check",
data:{
"email":jQuery("#em").val()
},
success: suc,
async:true,
datatype:"HTML"
});
}else{
error.innerHTML = "Введите корректный email";
}
});
})
def email_check(request):
if request.method == "POST":
email = request.POST["email"]
try:
User.objects.get(email=email)
return HttpResponse("Пользователь с таким email уже зарегистрирован")
except User.DoesNotExist:
return HttpResponse("1")
return HttpResponse("0")
url('^email_check$', views.email_check),
(function(G) {
"use strict";
var $ = G.jQuery;
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
var host = document.location.host, // host + port
protocol = document.location.protocol,
sr_origin = '//' + host,
origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin
+ '/')
|| (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin
+ '/') ||
!(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
beforeSend : function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
}
}
});
}(this));
@csrf_protect #Защищать так защищать
def email_check(request):
if request.method == "POST":
post_email = request.POST.get("email")
user_by_email = User.objects.get(email=post_email)
if user_by_email is not None: #Такой email уже использован
return HttpResponse(json.dumps({"success": False, "error": "Пользователь с таким email уже зарегистрирован"}), content_type="application/json")
else: #E-mail свободен
return HttpResponse(json.dumps({"success": True}), "application/json")