简体   繁体   中英

Image is not loading from django rest framework in react

i am beginner in drf. i want to load image from django rest framework to react but I does not show image in react.

views.py


def PostView(request):
    parser_classes = (MultiPartParser, FormParser,JSONParser)
    if request.method=="GET":
        post = Post.objects.all()
        post_serializer = PostSerializer(post, many=True)
        return Response(post_serializer.data)

Seriliazer.py


class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = "__all__"

settings.py

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

Axios call

 async function getPost() {
    await axios
      .get(
        "http://127.0.0.1:8000/api/post/"
     
      )
      .then((res) => {
        console.log(res.data);
        setPost(res.data);
      });
  }

and react code is


<div className="card mb-3" key={res.id}>
          <img className="card-img-top" src={`http://127.0.0.1:8000${res.image}`} alt="post image" />
          <div className="card-body">
            <h4>{res.title}</h4>
            <p className="card-text">{res.image}</p>
          </div>

following is my API response following is my API response

and browser error

error

You have to pass context into serializer. Thanks to that DRF will be add domain to image.

Change it to this

post_serializer = PostSerializer(post, many=True, context={"request": request})

change your p tag to <img src={res.image}/> , should do it if it was passing as a url

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