B
B
baterson2015-10-12 16:16:24
JavaScript
baterson, 2015-10-12 16:16:24

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();
});
});


Nothing happens when you click, if you copy the js file to the browser console, it gives 404:
GET 127.0.0.1:8000/apps/questions/add_like?answer_id=1 404 (NOT FOUND)

upd: It worked, I had to remove / in ajax.js apps/ before questions/add_like/ .
The truth only works when I load the code into the browser console, although the js file is connected.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Sklyar, 2015-10-12
@baterson

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 question

Ask a Question

731 491 924 answers to any question