Ajax像Django中的按钮一样

时间:2017-12-23 20:40:06

标签: javascript jquery python ajax django

我为类似按钮构建了下一个架构,但它不起作用。这是我的文件:

models.py

class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    archivo = models.FileField(upload_to='media/%Y/%m/%d', null=True, blank=True)
    slug= models.SlugField(default=0)
    likes = models.ManyToManyField(Perfil, related_name="likes")

    def __str__(self):
        return (self.titulo)

    @property

    def total_likes(self):
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug=slugify(self.titulo)
        super(Comentario, self).save(*args, **kwargs)

views.py

try:
    from django.utils import simplejson as json
except ImportError:
    import json

def like (request):
    if request.method=='POST':
    perfil=request.user
    slug=request.POST.get('slug', None)
    comentario=get_object_or_404(Comentario, slug=slug)

        if comentario.objects.filter(perfil__id=perfil.id).exists():
            comentario.likes.remove(perfil_id)
        else:

            comentario.likes.add(perfil_id)

    context={'likes_count':comentario.total_likes}
    return HttpResponse(json.dumps(context), content_type='home/json')

urls.py

url(r'^like/$', login_required(views.like), name='like')

html的

<input type="button" id="like" name='{{ comentario_slug  }}' value="Like" /> 

                <script>
                $('#like').click(function(){
                     $.ajax("/home/like/",{
                            type: "POST",
                            url: "{% url 'home:like' %}",
                            data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                            dataType: "json",
                            success: function(response) {

                            alert(' likes count is now ' + response.likes_count);
                        },
                            error: function(rs, e) {
                            alert(rs.responseText);
                            }
                        }); 
                    })
                </script>

当我按下按钮时,它没有做任何事情。控制台告诉我:

POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404(未找到)

和:http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

问题出在哪?

谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

有问题是您的视图未被slug字段找到Comentario。你的ajax { 'slug' : $(this).attr('titulo') ...是否正确?您确定'titulo'是slug的正确字段还是$(this).attr('slug')?试试这个:

$.ajax("/home/like/",{
                        type: "POST",
                        url: "{% url 'home:like' %}",
                        data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                        dataType: "json",
                        success: function(response) {

                        alert(' likes count is now ' + response.likes_count);
                    },
                        error: function(rs, e) {
                        alert(rs.responseText);
                        }
                    });