Answer the question
In order to leave comments, you need to log in
How to add like button Django + Ajax?
Hello, for educational purposes, I am creating a project similar to a toaster, I want to add a like button to my comment model. Did according to the guide from tangowithdjango
apps/questions/models:
class Answer(models.Model):
text = models.TextField()
date = models.DateTimeField(default=datetime.datetime.now)
likes = models.IntegerField(default=0)
resolve = models.IntegerField(default=0)
author = models.ForeignKey(CustomUser)
question = models.ForeignKey(Question)
apps/questions/views:
@login_required
def add_like(request):
ans_id = None
if request.method == 'GET':
ans_id = request.GET['answer_id']
likes = 0
if ans_id:
ans = Answer.objects.get(id=(int(ans_id)))
if ans:
likes = ans.likes + 1
ans.likes = likes
ans.save()
return HttpResponse(likes)
apps/questions/ulrs:
urlpatterns = [
url(r'add_like/$', views.add_like, name='add_like'),]
question.html:
{% for answer in answers %}
<div class="container-fluid no-padding">
{{ answer.text }}
</div>
<div class="container-fluid author-question">
<p>posted: {{ answer.date.day|stringformat:"02d" }}.{{ answer.date.month|stringformat:"02d"}}.{{ answer.date.year}}</p>
<p>by: {{ answer.author.username }}</p>
</div>
{% if user.is_authenticated %}
<button class="btn btn-default likes-button" type="button" data-ansid="{{ answer.id }}">
like | <strong id="like_count">{{ answer.likes }}</strong>
</button>
{% endif %}
{% endfor %}
js/ajax.js:
$('.likes-button').click(function(){
var ansid;
ansid = $(this).attr("data-ansid");
$.get('/apps/questions/add_like/', {answer_id: ansid}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
Answer the question
In order to leave comments, you need to log in
You can put an infinite number of likes in your Answer model from one account. Is that how it should be?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question