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')
restaurant.photois a relative url, likemedia/images/iconfinder_thefreeforty_trolle.png, then is not going to work. It should be an absolute url, likehttp://127.0.0.1:8000/media/images/iconfinder_thefreeforty_trolle.pngrestaurant.photovalue. 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}}" >