Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda