如何在查询外部 django 视图时刷新 DOM HTML 的一部分



你好,很棒的人!

StackOverflow上的很多问题都是关于"如何通过jquery刷新dom(from the same view/url(">这不是我要找的。

对于一个大部分使用ajax运行的网站,我想知道如何在查询外部django视图时刷新HTML DOM的一部分。

让我用一些例子更清楚:

我有将all_users发送到模板的视图

def usersList(request):
all_users = User.objects.all()
return render(request,'administration/users-list.html',{'all_users':all_users})

在模板中,我循环遍历all_users...第二个<span>反映用户的activation state

{% for u in all_users %}
<span>{{forloop.counter}}.- {{u.name}} <span>
<span id='user_{{u.id}}_state'>
<button data-id='{{u.id}}' type='button' class='css-btn btn-circle'>
{% if u.is_activate %} Active{% else %}Inactive{% endif %}
</button>
<span>
{% endfor %}

使用 jquery,我向仅负责activatedeactivate用户帐户的特定视图发送请求。我们可以在网站的许多部分activate/deactivate用户,这就是为什么我以不同的观点这样做。

这是视图:

def deactivateUser(request):
user = request.user
if user.has_perm('is_admin') and request.is_ajax() and request.method == 'POST':
id_user = request.POST.get('id')
targeted_user = get_object_or_deny(User,id=id_user)
# get_object_or_deny is my own function
it will get the object or raise PermissionDenied otherwise
if targeted_user.is_activate:
targeted_user.is_activate = False
state = 'deactivated'
else:
targeted_user.is_activate = True
state = 'activated'
targeted_user.date_update_activation = NOW() # own function
targeted_user.save()
return JsonResponse({'done':True,'msg':'User successfully %s' %s state})
# Here we return a JsonResponse
raise PermissionDenied

那么现在,我如何使用以下jquery内容刷新Dom以获取每个用户的当前状态

$(document).on('click','.btn-circle',function(){
var id = $(this).data("id");
$.ajax({
url:'/u/de-activate/?ref={{ request.path }}',
type:'post',
data:{
csrfmiddlewaretoken:"{{ csrf_token }}",
id:id,
},
success:function(response){
$("#user_"+id+"_state").replaceWith($("#user_"+id+"_state",response));
if(response.created) alert(response.msg);
},
error:function(){
alert("An error has occured, try again later");
}
});
});

请注意,需要all_users才能循环。deactivateUser()返回 Json 响应,即使它没有返回它,也没关系。

您可以发送 http 响应,而不是 json。

首先,只需移动要更改的 html。 在这种情况下,

{% for u in all_users %}
<div id="user-part">
<span>{{forloop.counter}}.- {{u.name}} <span>
<span id='user_{{u.id}}_state'>
<button data-id='{{u.id}}' type='button' class='css-btn btn-circle'>
{% if u.is_activate %} Active{% else %}Inactive{% endif %}
</button>
<span>
</div>
{% endfor %}

然后保存它,即user_part.html

其次,使视图返回带有该 html 和上下文的HttpResponse。您可以使用HttpResponserender_to_response。我推荐render_to_response

context = {
'all_users': all_users,
}
return render_to_response(
'path_to/user_part.html',
context=context,
)

第三,您只需更改脚本即可替换html。

success: function(response){
$('#user-part').html(response);
prevent();
}

最新更新