Python-Django响应错误的文本

时间:2016-09-19 13:52:55

标签: python ajax django

如何使用Ajax将验证错误的文本响应到我的模板?

def create_user(request):
    if request.method == 'POST':
        is_super = True
        if request.POST.get('is_super') in 'false':
            is_super = False
        if request.POST.get('password') == request.POST.get('confirm'):
            user = User.objects.create(first_name=request.POST.get('first_name'),
                                       last_name=request.POST.get('second_name'),
                                       username=request.POST.get('username'),
                                       is_superuser=is_super,
                                       date_joined=datetime.now())
            user.set_password(request.POST.get('password'))
            user.save()
        else:
            raise forms.ValidationError("Passwords doesn't match")
        return HttpResponse('')

1 个答案:

答案 0 :(得分:0)

def create_user(request):
    if request.method == 'POST':
        is_super = True
        if request.POST.get('is_super') in 'false':
            is_super = False
        if request.POST.get('password') == request.POST.get('confirm'):
            user = User.objects.create(first_name=request.POST.get('first_name'),
                                       last_name=request.POST.get('second_name'),
                                       username=request.POST.get('username'),
                                       is_superuser=is_super,
                                       date_joined=datetime.now())
            user.set_password(request.POST.get('password'))
            user.save()

        else:
            return HttpResponse(json.dumps({'error': True, 'message': 'Password and confirm password doesnt match'}))`            
        return HttpResponse('')

您需要显示以上错误消息"密码并确认密码不匹配"在HTML中使用Jquery。