简体   繁体   中英

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

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
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM