Jquery validation - checking email and username availability from server-side Django

♀尐吖头ヾ 提交于 2019-12-19 12:04:21

问题


I'm trying to validate the registration form for email and username availability from server-side programmed with Django. I checked this one jQuery Validation Plugin remote check for password with Django but I'm getting 403 forbidden - CSRF verification failed. I tried including csrf token inside the jquery script. But still not working. I've shown the code below for checking email availability.

views.py:

def email_check(request):
    response_str="false"
    if request.is_ajax():
        e = request.POST.get("email_address")
        try:
            obj = User.objects.get(email=e)
        except DoesNotExist:
            response_str="true"
    return HttpResponse(response_str)

urls.py:

url(r'^signup/email/check/$', 'registration.views.email_check')

signup.html: https://gist.github.com/2253002

Could anyone help me on this?

Thanks!


回答1:


You should send the csrf token in a cookie named "X-CSRFToken", there is a way to globally enable this behavior with jQuery like this:

https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/#ajax




回答2:


$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

Reference the above jquery code in your template to ensure your AJAX POST calls always include the csrf token. For the details, check this article from the official doc.



来源:https://stackoverflow.com/questions/9947487/jquery-validation-checking-email-and-username-availability-from-server-side-dj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!