django项目注册页面ajax验证

ajax post方式提交时需要在 data中添加 "csrfmiddlewaretoken":$("[name=csrfmiddlewaretoken]").val()

user/url.py

urlpatterns = [
    url(r"^check_username/$",views.check_username,name="check_username"),
    url(r"^check_password/$",views.check_password,name="check_password"),
    url(r"^check_password2/$",views.check_password2,name="check_password2"),
    url(r"^check_img_code/$",views.check_img_code,name="check_img_code"),
...]

user/register.html

{% load static from staticfiles %}


{% csrf_token %}
用户名:
密码:
确认密码:
验证码:

user/views.py

def check_username(request):
    username = request.GET.get("username")
    print(username)
    for i in User.objects.all():
        if i.username == username:
            r={"r_link":"该用户名已被使用"}
            return HttpResponse(json.dumps(r, ensure_ascii=False),
                            content_type="application/json;charset=utf-8")
    else:
        if len(username)>=6 and len(username)<=10:
            r = {"r_link": "ok"}
            return HttpResponse(json.dumps(r, ensure_ascii=False),
                        content_type="application/json;charset=utf-8")
        else:
            r = {"r_link": "用户名为6-10位"}
            return HttpResponse(json.dumps(r, ensure_ascii=False),
                            content_type="application/json;charset=utf-8")


def check_password(request):
    password = request.POST.get("password")
    if len(password)>=6 and len(password)<=10:
        r = {"r_link": "ok"}
    else:
        r = {"r_link": "密码为6-10位"}
    return HttpResponse(json.dumps(r, ensure_ascii=False),
                    content_type="application/json;charset=utf-8")

def check_password2(request):
    password = request.POST.get("password")
    password2 = request.POST.get("password2")
    print(password,password2)
    if password==password2:
        r = {"r_link": "ok"}
    else:
        r = {"r_link": "两次密码不一致"}

    return HttpResponse(json.dumps(r, ensure_ascii=False),
                        content_type="application/json;charset=utf-8")

def check_img_code(request):
    img_code1 = request.GET.get("img_code")
    img_code2= request.session.get("img_code")
    print(img_code1,img_code2)
    if img_code1==img_code2:
        r = {"r_link": "ok"}
    else:
        r = {"r_link": "验证码错误"}
    return HttpResponse(json.dumps(r, ensure_ascii=False),
                        content_type="application/json;charset=utf-8")    

你可能感兴趣的:(django项目注册页面ajax验证)