我正在关注Django By Example教程,无法关注用户。我点击了关注按钮但没有任何反应。我一遍又一遍地浏览了那个部分,复制并粘贴了代码。它仍然无法运作。
以下是我的观点
view
这是我的html块中的ajax
@ajax_required
@require_POST
@login_required
def user_follow(request):
user_id = require.POST.get('id')
action = request.POST.get('action')
if user_id and action:
try:
user = User.objects.get(id=user_id)
if action == 'follow':
Contact.objects.get_or_create(user_form=request.user,user_to=user)
else:
Contact.objects.filter(user_form=request.user,user_to=user).delete()
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'ko'})
return JsonResponse({'status':'ko'})
这是网址
**
{% block domready %}
$('a.follow').click(function(e){
e.preventDefault();
$.post('{% url "user_follow" %}',
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok') {
var previous_action = $('a.follow').data('action');
// toggle data-action
$('a.follow').data('action',
previous_action == 'follow' ? 'unfollow' : 'follow');
// update total followers
var previous_followers = parseInt(
$('span.count .total').text());
$('span.count .total').text(previous_action == 'follow' ?
previous_followers + 1 : previous_followers - 1);
}
}
);
});
{% endblock %}
**
感谢您的帮助
答案 0 :(得分:0)
视图应该是
@ajax_required
@require_POST
@login_required
def user_follow(request):
user_id = request.POST.get('id')
action = request.POST.get('action')
if user_id and action:
try:
user = User.objects.get(id=user_id)
if action == 'follow':
Contact.objects.get_or_create(user_from=request.user,user_to=user)
else:
Contact.objects.filter(user_form=request.user,user_to=user).delete()
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'ko'})
return JsonResponse({'status':'ko'})
答案 1 :(得分:-1)
你错误地将你的状态值'ok'拼错为'ko' 请将其更改为“确定”
except User.DoesNotExist:
return JsonResponse({'status':'ok'})
return JsonResponse({'status':'ok'})
我希望在检查你的js代码时这是一个简单的错误。 ?