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

176
Visualizações
Trying to Implement simple API in Django

I am very new to Django and trying to implement small API for social media website where I can monitor if post has been liked and number of likes and later fetch API using JavaScript so I can like without refreshing the page using put method. Problem is that I largely failed because of lack of proper knowledge. I could not get the API working in the first place.

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    pass

class New_Post(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    New_Post =  models.CharField(null=True, max_length=300)
    def __str__(self):
        return f"{self.New_Post}"

class Likes(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    like = models.BooleanField(default=False)
    New_Post =  models.ForeignKey(New_Post, null=True, on_delete=models.CASCADE)
    def serialize(self):
        return {
        "id": self.id,
        "post": self.New_Post,
        "user": self.user,
        "like": self.like
    }

views.py fragment

def likes(request):
    like = Likes.objects.all()
    return JsonResponse(like.serialize())

urls.py

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("Post", views.likes, name="likes"),
]

When I try to access Post url I expect json response to be shown on mostly blank page. Should it be like that? How can I get my API working?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The serialize method handles one Like object while like is an a list of likes, which doesn't have such a function

One technique is to loop on the objs inside

def likes(request):
    likes = [l.serialize() for l in Likes.objects.all()]
    return JsonResponse(likes,safe=False)

safe is False as JSONResponse wants an object by default.

about 4 years ago · Juan Pablo Isaza 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