从AJAX函数调用Django视图

时间:2019-01-20 11:11:12

标签: javascript ajax django django-2.1

我有一个传递对象ID的按钮。按下按钮时,我希望其对应的Django视图应显示。

views.py

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def updateUser(request, id):

    user= get_object_or_404(CustomUser, pk=id)
    if request.method == 'POST':
        form = UpdateUser(request.POST, instance=user)
        try:
            print("DJANGO VIEW")
            if form.is_valid():
                form.save()
                messages.success(request, ("New user account has been created"))
            else:
                messages.warning(request, ("Data in fields is incorrect, please try again"))
        except Exception as e:
            messages.warning(request, ("Error: {}". format(e)))
    else:
        form = UpdateUser(instance=user)
    context ={'form': form, 'user': user,}
    return render(request, 'user/updateUser.html', context)

urls.py

 path('updateUser/<int:id>/', views.updateUser, name="updateUser"),

my.js

function myfunction($this) {

    var stid = $this;
   console.log("button clicked");
    var request_data = '/user/updateUser/'+stid;
    alert(request_data);
    console.log("data: " + stid);
    $.ajax({
        url:  "../updateUser/" + stid+"/" ,
        contentType: "application/json; charset=utf-8",
        processData: true,
        type:  'post',
        dataType:  'html',

        success:  function (data) {
           alert("Success");
           $("#updateUser").html(response);
        },
         error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + ':' + errorThrown);
         }
    });
}

已调用Django视图,但未显示该视图。按钮应呈现相应的页面。

1 个答案:

答案 0 :(得分:0)

所有代码都可以正常工作,但是正如link中强调的那样,我们只需要给windows.location一个变量,该变量是用AJAX定义的。真好!