【发布时间】:2016-07-19 13:47:25
【问题描述】:
我在 Django 模板中使用带有数据的 ajax POST 查询:{'action':'add'},但如果我在 views.py 中打印 request.POST,它会显示在控制台 <QueryDict: {}> .
但萤火虫显示POST 302 和action=add 或action=remove 参数!所以我不明白为什么<QueryDict: {}> 是空的。请帮忙。
附言。如果我使用 GET 它工作正常。
模板show_event.html:
<form id="unfollow" {% if user not in event.users.all %}style="display:none;"{% endif %}>
<input type="hidden" value="{{ event.id }}" name="remove">
<button type="submit" class="btn btn-warning btn-block">{% trans "Remove from My events"%}</button>
</form>
<form id="follow" {% if user in event.users.all %}style="display:none;"{% endif %}>
<input type="hidden" value="{{ event.id }}" name="add">
<button type="submit" class="btn btn-primary btn-block">{% trans "Add to My events"%}</button>
</form>
$(document).on('submit','#unfollow', function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:'/event/follow/{{ event.id }}/',
data: {'action':'remove'},
success:function(){
$('#unfollow').hide();
$('#follow').show();
}
})
});
$(document).on('submit','#follow', function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:'/event/follow/{{ event.id }}/',
data: {'action':'add'},
success:function(){
$('#follow').hide();
$('#unfollow').show();
}
})
});
views.py:
def follow (request, event_id):
event = get_object_or_404(Event, id=event_id)
user = request.user
print request.POST
if request.method == 'POST':
print "post"
if request.POST['action'] == 'add':
print "add"
event.users.add(user)
event.save()
elif request.POST['action'] == 'remove':
print "remove"
event.users.remove(user)
event.save()
return HttpResponse('')
urls.py:
url(r'^event/follow/(?P<event_id>[0-9]+)/$', 'events.views.follow', name='follow')
【问题讨论】:
-
有
500状态错误吗?该视图接受counter_id作为 kwarg 并且您正在传递event_id.. 这是同一个视图吗? -
@v1k45 抱歉,我粘贴了错误的视图,现在我编辑了我的问题。没有500错误