django中ajax post请求期间的HttpResponse错误

时间:2016-07-19 17:15:39

标签: jquery ajax django

朋友们,我正在尝试使用django中的ajax处理表单提交。我收到了这个错误,

The view auths.change_profile.change_username didn't return an HttpResponse object. It returned None instead.

这是我的change_profile.py

def change_username(request):
    if request.is_ajax() and request.method == 'GET':
        return render(request,"auths/edits/edit_username.html",{})
    elif request.method == 'POST' and request.is_ajax():
        username = request.POST['username']
        user = User.objects.get(username=request.user.username)
        user.username = username
        user.save()
        if user.save():
            data = "Username successfully updated"
        else:
            data = "Something went wrong!"
        return HttpResponse(json.dumps({'data':data}), content_type="application/json")

和我的ajax.js如下

$(document).ready(
    $('#username_form').submit(function(){
    $.ajax({
        type:"POST",
        url:'/change_username/',
        data:{
                'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()
        },
        success:function(data){
            $('#username').html(data);
        }
    });
});
);

我哪里错了?

2 个答案:

答案 0 :(得分:0)

删除此

if request.is_ajax():
    return render(request,"auths/edits/edit_username.html",{})

您不需要它,因为从技术上讲,您的Ajax请求也将是POST或GET类型。 所以你需要的只是:

if request.method == 'POST':
    username = request.POST['username']
    user = User.objects.get(username=request.user.username)
    user.username = username
    user.save()
    if user.save():
        data = "Username successfully updated"
    else:
        data = "Something went wrong!"
    return HttpResponse(json.dumps({'data':data}))
else:
    json.dumps({"nothing to see": "this isn't happening"})

答案 1 :(得分:0)

尝试这样做:

router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ] }
]);

发布Django 1.7,使用from django.http import JsonResponse def change_username(request): if request.is_ajax() and request.method == 'GET': return render(request, "auths/edits/edit_username.html", {}) elif request.is_ajax() and request.method == 'POST': username = request.POST['username'] user = User.objects.get(username=request.user.username) user.username = username user.save() if user.save(): data = "Username successfully updated" else: data = "Something went wrong!" return JsonResponse({'data': data}) 是推荐的格式。 Pre 1.7是你最初使用的方法。

如果有效,请告诉我。

编辑(尝试2):

JsonResponse