简体   繁体   English

Ajax在Django中像按钮一样强大

[英]Ajax powered like button in Django

I have built the next architecture for the like button, but it does not work. 我为“喜欢”按钮构建了下一个体系结构,但是它不起作用。 Here are my files: 这是我的文件:

models.py 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 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 urls.py

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

.html 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>

When I push the button like it does not do anything. 当我按下按钮时,它不会执行任何操作。 The console tells me: 控制台告诉我:

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

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

Which is the problem? 哪有问题

thank you for your help 谢谢您的帮助

There is problem in that your view not found Comentario by slug field. 有一个问题,您的视图未按Comentario字段找到Comentario Does your ajax { 'slug' : $(this).attr('titulo') ... correct? 您的ajax { 'slug' : $(this).attr('titulo') ...是否正确? You sure that 'titulo' is correct field for slug or it must be $(this).attr('slug') ? 您确定'titulo'是的正确字段,还是必须是$(this).attr('slug') try this one : 试试这个:

$.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);
                        }
                    }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM