在 Angular 8 中渲染来自 Django 服务器的图像 [英] rendering Image from the Django server in Angular 8

查看:34
本文介绍了在 Angular 8 中渲染来自 Django 服务器的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的模型、视图和序列化程序文件.API 端点工作正常,在 Angular 中,我可以从 Restaurant 模型打印名称和地点.但是,我找不到渲染和显示图像(我已存储在照片对象中)的方法.我的 API 在我输入时显示图像:

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

但是,如果我使用

我看不到图片,{{restaurant.photo}}"指向网址media/images/iconfinder_thefreeforty_trolle.png",但无法显示图片.这是将图像从 django 服务器渲染为角度的正确方法吗?

我的 Django 文件如下:Models.py

from django.db 导入模型类餐厅(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.method == 'GET':餐厅 = Restaurant.objects.all()serializer = RestaurantSerializer(餐厅,许多=真)返回 JsonResponse(serializer.data, safe=False)elif request.method == 'POST':序列化器 = RestaurantSerializer(data=request.data)如果 serializer.is_valid():序列化器.save()返回响应(serializer.data,status=status.HTTP_201_CREATED)返回响应(serializer.errors,status=status.HTTP_400_BAD_REQUEST)@api_view(['GET', 'PUT', 'DELETE'])def restaurant_detail(请求,pk):"""检索、更新或删除代码片段."""尝试:餐厅 = Restaurant.objects.get(pk=pk)除了 Restaurant.DoesNotExist:返回响应(状态=状态.HTTP_404_NOT_FOUND)如果 request.method == 'GET':serializer = RestaurantSerializer(餐厅)返回响应(serializer.data)elif request.method == 'PUT':餐厅 = RestaurantSerializer(餐厅,数据=request.data)如果 serializer.is_valid():序列化器.save()返回响应(serializer.data)返回响应(serializer.errors,status=status.HTTP_400_BAD_REQUEST)elif request.method == 'DELETE':片段.删除()返回响应(状态=状态.HTTP_204_NO_CONTENT)

serializers.py

<预><代码>从 rest_framework 导入序列化程序从 .models 导入餐厅类 RestaurantSerializer(serializers.ModelSerializer):元类:模型=餐厅fields=('id','name','place','photo')

解决方案

如果您使用相对值,例如您正在使用的值,那么您就是在引用您网站中的资源.

因为您的 API 是外部资源,所以 img 标签的 src 属性的值必须是绝对 URL.

在您的情况下,该值应为 http://127.0.0.1:8000/media/images/iconfinder_thefreeforty_trolle.png.

又快又脏,<img src="http://127.0.0.1:8000/{{restaurant.photo}}" >(只是举个例子,就是不是一个好习惯,请为此类参数使用环境).

[来自评论的回答]

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')

解决方案

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]

这篇关于在 Angular 8 中渲染来自 Django 服务器的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆