Reputation: 97
I have built the next architecture for the like button, but it does not work. Here are my files:
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>
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)
and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
Which is the problem?
thank you for your help
Upvotes: 0
Views: 387
Reputation: 702
There is problem in that your view not found Comentario
by slug field. Does your ajax { 'slug' : $(this).attr('titulo') ...
correct? You sure that 'titulo'
is correct field for slug or it must be $(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);
}
});
Upvotes: 1