【发布时间】:2020-12-12 00:52:51
【问题描述】:
在 model.py 文件的 imageField 中默认使用图像。
from django.db import models
class Product(models.Model):
item_title= models.CharField(max_length=50)
item_desc=models.TextField()
item_price=models.IntegerField()
item_image=models.ImageField(upload_to='post_images',default='default.png')
这是我的序列化程序类
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields= ('item_title', 'item_desc', 'item_price', 'item_image')
views.py 是-
class ProductView(viewsets.ModelViewSet):
serializer_class = ProductSerializer
queryset = Product.objects.all()
在localhost:8000收到的json数据是 localhost:8000/api/products
在 App.js 的前端(react js)获取数据。这是代码
class App extends Component {
constructor(props) {
super(props);
this.state = {
productList: [],
};
}
refreshList = () => {
axios
.get("/api/protducts/")
.then((res) => this.setState({ productList: res.data }))
.catch((err) => console.log(err));
};
componentWillMount() {
this.refreshList();
}
render() {
return (
<div>
{this.state.productList.map((item) => (
<Product key={item.id} item={item} />
))}
</div>
);
}
}
export default App;
前端的Product组件是
class Product extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div class="jumbotron col-sm-2">
<img src={this.props.item.item_image}></img>
<mark>{this.props.item.item_title}</mark>
<div class="lead">{this.props.item.item_desc}</div>
<div class="text-primary">{this.props.item.item_price}</div>
</div>
);}}
export default Product;
前端显示的数据不显示任何图像。 localhost:3000
【问题讨论】:
-
你使用过自定义的 axios 实例吗?如果不是,那么您的
get请求将被定向到localhost:3000/api/products/。 -
获取请求能够定向到 localhost:3000/api/products/。
-
并且数据能够从后端显示在前端。请参考问题中按赞给出的图像。我只能显示图像。字符串数据正常工作。
标签: json django reactjs django-rest-framework react-fullstack