Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

434
Visualizações
Set model's field via onclick (django)

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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/

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda