Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!