简体   繁体   English

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

[英]HttpResponse error during ajax post request in django

Friends, I am trying to handle form submission using ajax in django. 朋友们,我正在尝试使用django中的ajax处理表单提交。 I've been getting this error which says, 我一直得到这个错误,说,

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

Here's my change_profile.py 这是我的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")

and my ajax.js is as follows 我的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);
        }
    });
});
);

Where am I going wrong? 我哪里错了?

Remove this 删除它

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

You don't need it, as technically your Ajax request will also be of POST or GET type. 您不需要它,因为从技术上讲,您的Ajax请求也将是POST或GET类型。 So all you need is: 所以你需要的是:

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"})

Try doing this: 试着这样做:

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})

Post Django 1.7, using JsonResponse is the recommended format. 发布Django 1.7,使用JsonResponse是推荐的格式。 Pre 1.7 was the method you originally used. Pre 1.7是您最初使用的方法。

Let me know if that works. 如果有效,请告诉我。

Edit (attempt 2): 编辑(尝试2):

from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_http_methods


@require_http_methods(['POST'])
def change_username(request):
    if not request.is_ajax():
        return render(request, "auths/edits/edit_username.html", {})
    else:
        new_username = request.POST.get('username')
        user = get_object_or_404(User, id=request.user.id)
        initial_username = user.username
        user.username = new_username
        user.save()

        data = {}

        if user.username == new_username:
            data['data'] = "Username successfully updated!"
        else:
            data['data'] = "Something went wrong!"

        return JsonResponse(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM