【发布时间】:2021-11-27 20:12:37
【问题描述】:
我正在从事一个带有 django 后端和 react 前端的项目。我一直坚持在反应前端显示图像。
在我的反应控制台中提供的网址是:http://localhost:8000/media/media/images/cards/card1.jpg 当我在新的 chrome 中加载此 url 时,图像会显示在页面中,但是在我的反应页面中,图像是空白的。
这是我的 django settings.py :
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
#Directories
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR)
MEDIA_URL = '/media/'
这是我的序列化器:
class StartupSerializer(serializers.ModelSerializer):
class Meta:
model = Startup
fields = ('id', 'header', 'title', 'category', 'description', 'tags' , 'card_image' ,
'logo_image')
这是我的模型:
class Startup(models.Model):
header = models.CharField("Header", max_length=255, null=False)
title = models.CharField("Title", max_length=255, null=False)
category = models.CharField("category", max_length=255, null=False)
description = models.CharField("description", max_length=255, null=False)
# TODO Change this to options instead of array
tags = ArrayField(models.CharField(max_length=10, blank=True), size=5,)
# TODO Images to be stored in aws only url will be in DB
card_image = models.ImageField(upload_to='media/images/cards', null=False)
logo_image = models.ImageField(upload_to='media/images/logos', null=False)
createdAt = models.DateTimeField("Created At", auto_now_add=True)
def __str__(self):
return self.title
请不要在 recat 方面,axios 工作正常,我可以得到所有其他字段,我的问题只是图像显示。
我还想知道为什么 URL 有 /media/media 我无法弄清楚我在哪里复制媒体路径。请注意我正在使用 postgres 数据库来存储数据。
这是我的前端父组件:
import React from 'react';
import CardComponent from './CardComponent';
import { Grid } from '@material-ui/core';
import { Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
import StartUpService from './../Services/StartUpService';
const CardList = () => {
const [startup, setstartups] = useState([]);
const retrieveTutorials = () => {
StartUpService.getAll()
.then((response) => {
const myData = response.data;
setstartups(myData);
console.log(myData);
})
.catch((e) => {
console.log(e);
});
};
useEffect(() => {
retrieveTutorials();
}, []);
console.log("sttart up is " + startup)
return (
<div className="card list">
<Grid container spacing={4}>
{startup.map((startups) => (
<Grid key={startups.id} item xs={4}>
<Link to={{ pathname: `product/${startups.id}` }}>
<CardComponent
className="cards"
key={startups.id}
id={startups.id}
image={startups.image}
header={startups.header}
title={startups.title}
category={startups.category}
summary={startups.summary}
/>
</Link>
</Grid>
))}
</Grid>
</div>
);
};
export default CardList;
【问题讨论】:
-
您的后端看起来不错,将 ('upload_to='media/images/logos'') 更改为 'upload_to='/images/logos') 以撤消重复的媒体路径,因为您的媒体路径根已经定义了“MEDIA_URL = '/media/'”,问题出在你的前端,你能提供更多细节吗?
-
当然我会编辑问题以在前面添加详细信息