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

311
Views
How to get the image url from an ImageField in a Django model with a JsonResponse?

I have this Model in a Django app

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    say = models.CharField(max_length=250)
    date = models.DateTimeField(auto_now_add=True)
    photo =  models.ImageField(null = True, blank = True)
    
    def serialize(self):
        return {
            "user": self.user.username,
            "say": self.say,
            "date": self.date.strftime("%a-%d-%b-%Y , %H:%M:%S %p"),
            "photo": self.photo
        }

and this function in the views.py

@login_required(login_url = 'login')#redirect when user is not logged in
def all_comments(request):
    all_comments = Comment.objects.order_by("-date").all()
    return JsonResponse([comment.serialize() for comment in all_comments], safe=False)

and finaly this part of code in my javascript file

document.addEventListener('DOMContentLoaded', function() {
    fetch('/all_comments') 
  .then(response => response.json())
  .then(all_comments => {
do somethings with the data...

and when i run this i'm getting the error:

TypeError: Object of type ImageFieldFile is not JSON serializable

If i remove the line

"photo": self.photo

from the serialize function inside the mode everything goes fine and im getting the data that i need. How can i retrieve images url, with the JsonResponse as well, in order to display it with the other data? Ihave tryied many things i found here and there but i cant find any solution. Thanks so much in advance

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Adding .url after photo will give you the photo's URL as a string, add like so:

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    say = models.CharField(max_length=250)
    date = models.DateTimeField(auto_now_add=True)
    photo =  models.ImageField(null = True, blank = True)
    
    def serialize(self):
        return {
            "user": self.user.username,
            "say": self.say,
            "date": self.date.strftime("%a-%d-%b-%Y , %H:%M:%S %p"),
            "photo": self.photo.url
        }
about 4 years ago · Juan Pablo Isaza Report

0

try this

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    say = models.CharField(max_length=250)
    date = models.DateTimeField(auto_now_add=True)
    photo =  models.ImageField(upload_to='myphotos',null = True, blank = True)
    
    def serialize(self):
        if self.photo:
            return {
            "user": self.user.username,
            "say": self.say,
            "date": self.date.strftime("%a-%d-%b-%Y , %H:%M:%S %p"),
            "photo": self.photo.url
        }
        return {
            "user": self.user.username,
            "say": self.say,
            "date": self.date.strftime("%a-%d-%b-%Y , %H:%M:%S %p")
        }

or

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    say = models.CharField(max_length=250)
    date = models.DateTimeField(auto_now_add=True)
    photo =  models.ImageField(upload_to='myphotos',null = True, blank = True)
    
    def serialize(self):
        return {
            "user": self.user.username,
            "say": self.say,
            "date": self.date.strftime("%a-%d-%b-%Y , %H:%M:%S %p"),
            "photo": self.photo.url if self.photo else None
        } 

Note is it important to add upload_to to the FileField or ImageField.do not forget to run migrations an migrate.

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!