我有一个Django模板:home.html页面:
<a href="#" class = "dept" contextmenu = "mymenu2" id = "{{d.dept.id}}" ><i class="fa fa-circle-o"></i> {{d.dept}} <i class="fa fa-angle-left pull-right"></i></a>
<ul class='custom-menu2'>
<p><a id = "add_emp">Add new Employee</a></p> <br>
<p><a class = "del_dept">Delete this Deptartment</a></p>
</ul>
<script>
var id;
$('.dept').mousedown(function(event) {
switch (event.which) {
case 3:
id = $(this).attr('id');
$('.del_dept').on('click',function(e){
if(e.handled !== true)
{
alert(id);
$.ajax({
type: "POST",
url: "del_dept",
data: { 'id':id },
success: function(response){
alert(response.success);
}
});
return false;
e.handled = true;
}
});
break;
}
});
</script>
views.py:
def del_dept(request):
department = Department.objects.get(pk = int(request.REQUEST['id']))
print department
print ("ABCD")
department.delete()
payload = {'success': True}
return HttpResponse(json.dumps(payload), content_type='application/json')
main urls.py:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^employee/', include('EmployeeManagement.urls')),
)
和EmployeeManagement.urls文件:
urlpatterns = [
# ex: /polls/
url(r'^$', views.home, name='home'),
url(r'^(?P<emp_id>[-\w]+)/$', views.get_employee, name='get_employee'),
url(r'^(?P<emp_id>[-\w]+)/(?P<status>[-\w]+)/$', views.change_status, name='change_status'),
url(r'save_dept$',views.save_dept, name = 'save_dept'),
url(r'save_emp$',views.save_emp, name = 'save_emp'),
url(r'del_dept$',views.del_dept, name = 'del_dept'),
不知道什么是错的,显然,当我点击'删除此部门'按钮时,该特定部门的ID会发出警报,但之后没有任何反应。同样在 del_dept视图中,我尝试打印部门和一些文本进行测试,但它们都没有打印。
答案 0 :(得分:1)
您的ajax网址不是有效的网址
$.ajax({
type: "POST",
url: "{% url 'del_dept' %}",
data: { 'id':id },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(response){
alert(response.success);
}
});
注意我已更改del_dept
以使用django网址模板标记。你可能需要在这里包含一个命名空间,但它看起来并不像你所展示的那样
对于帖子请求,您还需要添加csrf token。
此外,您的观点查找的ID位置错误,帖子数据会转到request.POST
,因此您的查询会变为以下内容
department = Department.objects.get(pk=int(request.POST['id']))
您可能不需要将id转换为int,因为它可能已经是一个。