我有一个传递对象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视图,但未显示该视图。按钮应呈现相应的页面。