简体   繁体   中英

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

So as stated, I'm having trouble loading images from Django backend(fetch works fine). I've looked other similar questions, but NONE OF THEM HELPED, sadly.
So here's my Django code: settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

model.py

class Content(models.Model):
    objects = models.Manager()

    image = models.ImageField(upload_to='None', height_field=None, width_field=None, max_length=None, null=True, blank=True)
    key_line = models.CharField(max_length = 100, null=True)
    body = models.TextField(blank=True, null=True)

I've uploaded an image named 'eeee.PNG' via admin, and I can see the data serialized in JSON format like below:

[
    {
        "id": 5,
        "image": "/media/None/eeee.PNG",
        "key_line": "key.",
        "body": "blablabla",
    },
]

And my React code (fetch has been successfully worked):

<Container classname="">
     <Row className="">
         <Col className="text-text img-eachcake">{this.props.image}</Col>
         <Col className="text-text img-eachcake" src={this.props.image}></Col>
     </Row>
</Container>

As you can see, I've tried two ways but none of them worked. What do you think is the problem? All the other props are loaded fine. It's just the image file that doesn't work.

+in the inspection mode > Elements, I see the line as: <div src="/media/None/eeee.PNG" class="text-text img-eachcake col"></div>

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/

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.

Try adding:

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

worked for me

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