0
文本我有跟隨按鈕,它的工作原理是使用Ajax {{ total_followers }}
作品以及通過增加或在點擊減小之前刷新頁面,但遵循和取消關注按鈕時才改變我刷新整個頁面是什麼,我不想有我的Ajax請求發生在Django
我的觀點
@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_from=request.user,user_to=user).delete()
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'ok'})
return JsonResponse({'status':'ok'})
我的HTML
{% extends 'base.html' %}
{% load thumbnail %}
{% block title %}{{ user.get_full_name }}{% endblock %}
{% block content %}
<h1>{{ user.get_full_name }}</h1>
<div class="profile-info">
{% thumbnail user.profile.photo '180x180' crop='100%' as im %}
<img src="{{ im.url }}" alt="profile photo">
{% endthumbnail %}
</div>
{% with total_followers=user.followers.count %}
<span class="count">
<span class="total">{{ total_followers }}</span>
follower{{ total_followers|pluralize }}
</span>
<a href="#" data-id='{{ user.id }}' data-action='{% if request.user in user.followers.all %}un{% endif %}follow' class="follow button">
{% if request.user not in user.followers.all %}
Follow
{% else %}
Unfollow
{% endif %}
</a>
<div id="image-list" class="image-container">
{% include "images/image/list_ajax.html" with images=user.images_created.all %}
</div>
{% endwith %}
{% endblock %}
{% 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 %}
這個例子我必須寫這個函數一個全新的看法? –
無需編寫新視圖,在已存在的代碼中添加額外內容。檢查我的更新回答 –
謝謝@NeErAj KuMaR工作 –