0

Following are my models, views and serializers file. API endpoints are working fine and in Angular I am able to print name and place from the Restaurant model. However, I couldn't find the way to render and show the image ( which I have stored in photo object). My API shows the image when I type:

http://127.0.0.1:8000/media/images/iconfinder_thefreeforty_trolle.png

However, if I use

<div class='container' >
  <div  *ngFor= "let restaurant of restaurants | async; let i=index">
        <h2> {{restaurant.name}} in {{restaurant.place}}  </h2>
        <small>{{restaurant.photo}}</small>
        <img src={{restaurant.photo}} >
        </div>
  </div>

I see no image, the "{{restaurant.photo}}" points to the url 'media/images/iconfinder_thefreeforty_trolle.png', but not able to show the image. Is this the right way to render an image from django server to angular?

My django files are following: Models.py

from django.db import models


class Restaurant(models.Model):
    name=models.CharField(max_length=40,blank=False)
    place=models.CharField(max_length=20,blank=False)
    photo=models.ImageField(upload_to='images', blank=True)

views.py

@api_view(['GET', 'POST'])
def restaurant_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        restaurants = Restaurant.objects.all()
        serializer = RestaurantSerializer(restaurants, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        serializer = RestaurantSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def restaurant_detail(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        restaurant = Restaurant.objects.get(pk=pk)
    except Restaurant.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = RestaurantSerializer(restaurant)
        return Response(serializer.data)

    elif request.method == 'PUT':
        restaurant = RestaurantSerializer(restaurant, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

serializers.py


from rest_framework import serializers
from .models import Restaurant

class RestaurantSerializer(serializers.ModelSerializer):
    class Meta:
        model=Restaurant
        fields=('id','name','place','photo')
6
  • If restaurant.photo is a relative url, like media/images/iconfinder_thefreeforty_trolle.png, then is not going to work. It should be an absolute url, like http://127.0.0.1:8000/media/images/iconfinder_thefreeforty_trolle.png Commented Jan 22, 2020 at 18:53
  • I think src={{restaurant.photo}} points to localhost:4200/media/images/iconfinder_thefreeforty_trolle.png instead of >127.0.0.1:8000/media/images/iconfinder_thefreeforty_trolle.png and there is no file such as this. So it throws file not found. But how to make it absolute url? Commented Jan 22, 2020 at 19:02
  • 1
    If is a relative url, like the one you post, you just need to concat the base url of your API to the restaurant.photo value. For example <img src="{{api.url + restaurant.photo}}" >, to test it quickly hard code it, <img src="http://127.0.0.1:8000/{{restaurant.photo}}" > Commented Jan 22, 2020 at 19:13
  • it is working with ``` <img src="127.0.0.1:8000{{restaurant.photo} ``` but not with this api.url way, just to be sure, where would you define api.url? Commented Jan 22, 2020 at 20:06
  • i have endpoint defined in the service file, like `endpoint: string = '127.0.0.1:8000/restaurants/';' and I tried to use that endpoint in html but didn't work. Commented Jan 22, 2020 at 20:13

1 Answer 1

1

If you use a relative value, like the one you are using, then you are referencing a resource within your website.

Because your API is an external resource, the value of the src property of the img tag must be an absolute URL.

In your case the value should be, http://127.0.0.1:8000/media/images/iconfinder_thefreeforty_trolle.png.

Quick and dirty, <img src="http://127.0.0.1:8000/{{restaurant.photo}}" > (just to use as an example, it is not a good practice, use environments for this kind of parameters).

[Answer from the comments]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.