this is my code:
models.py
class Photos(models.Model):
username = models.CharField(max_length=50)
caption = models.CharField(max_length=150, blank=True, null=True)
img = models.ImageField(upload_to = 'userProfile/static/img', null=True, blank=True)
update_date = models.DateTimeField(default=timezone.now)
category = models.CharField(max_length=50, blank=True, null=True)
likes_count = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'photos'
and this is a part of html code that my js code produces
<div class="container_card">
<img class="container_card_image" onclick="..." src="/static/img/1/uploads/img1.jpg">
</div>
I want that when you click on the image, 'likes_count' is incremented without refresh the page (like instagram or like all social network).
Then, if i use <a href="{% url 'like' value=user.id %}> <img ...> </a> and a view defined in this way, it increases the likes_count but is not good because it refesh the page for each click
urls.py
urlpatterns = [
...
url(r'^(?P<value>\w+)$', views.like, name='like'),
]
views.py
def like(request, value):
photo = Photos.objects.get(pk=value)
photo.likes_count += 1
photo.save()
return redirect('home')
Is there a way to get what I want?
In order to get what you want, you need to use ajax. For example jquery is really simple and easy to make ajax request and handle the response. https://api.jquery.com/jquery.get/
$.post( "photo/15/like", function( data ) {
// here you handle the response.
});
IN addition your django view should not redirect you to another page, because this will cause the whole page to refresh. Instead you should use a JsonReponse
def get(self, request, *args, **kwargs):
photo = Photos.objects.get(pk=value)
photo.likes_count += 1
photo.save()
return JsonResponse({'action': 'success'}, safe=False)
More advance you can use a whole framework which handle json responses like http://www.django-rest-framework.org/, and for writing less code use some of the class based views http://www.cdrf.co/