[Django]-How do I load image to React from Django REST API?

0👍

Problem is in your image URL,

"image": "/media/None/eeee.PNG",

This should have domain or localhost before /media on which your Django project is working
Like:

"image": "localhost:8000/media/None/eeee.PNG"

and if you’re running on server this Django project localhost:8000 should replace with domain

So Problem is in your serializer data way, You’re using the wrong way to serialize data because the image URL is not serializing according to your question.

Use a proper Django REST framework serializer to serialize your data.
https://www.django-rest-framework.org/api-guide/serializers/

0👍

Trying to clarfy Neeraj’s answer:

  • instead of sending

    "image": "localhost:8000/media/None/eeee.PNG"

  • try:

    "image": "http://127.0.0.1:8000/None/eeee.PNG"

Since Django redirects automatically to your media folder. Remember the IP and Port may change depending on your project.

0👍

Try adding:

`http://localhost:8000${this.props.image}`

worked for me

0👍

This how I did mine, this solution works if anyone still having issues with this same question.

class Image(models.Model):
   image_file = models.ImageField()

   @property
   def get_image_url(self) -> str:
      if self.image_file and hasattr(self.image_file, 'url'):
         return f"http://localhost:8000{self.image_file.url"
```.

Image_file is the image file in the model class and the property function also belong to the same class. So knsdI hope this helps because it work for me.

Leave a comment