Reputation: 53
I have follow button which works by using ajax the {{ total_followers }}
works well by increasing or decreasing upon a click but the follow and unfollow buttons change only when I refresh the whole page which is what I do not want
My views
@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'})
My 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 %}
Upvotes: 0
Views: 431
Reputation: 3941
You need to return html template code dynamically from view when you called from ajax and replace that html with previous with current html that you will get in success() method of ajax.
Follow this answer Return JSON response using Django template system
Edit:
Make a template that should have html code that you want to change when ajax request called.
html = render_to_string("yourtemplate.html", context_object)
return JsonResponse({'status':'ok', 'html':html})
Template:
new_html = data['html']
$selector = $('#id of block');
$selector.html(new_html);
Upvotes: 1