A
A
archi19982014-11-07 23:18:36
JavaScript
archi1998, 2014-11-07 23:18:36

Why does Internal server error 500 appear when using ajax with django?

javascript

$(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_\.-])[email protected][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";
                }
            });
})

views.py
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")

urls.py
url('^email_check$', views.email_check),
middlewarecsrf in settings.py file is commented out, in template I used {% csrf_token %}
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Dunayevsky, 2014-11-08
@archi1998

1. You need to include the {% csrf token %} tag in your template that is displayed on the page
2. You also need this script to work when the page loads:

(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));

3. You don't need to comment the csrf_token middleware. Be consistent - if you do CSRF, do it to the end.
4. Your view is better written like 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")

I
Ilya, 2014-11-08
@FireGM

And just create a form (not Ajax) and try to send?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question