[d-5]django上传图片并使用postman测试

说明:使用django模型类ImageFields字段上传图片到服务器本地,并使用postman测试

  • models.py的内容
class People(BaseModel):
  
    name = models.CharField(verbose_name='姓名', max_length=1024, default="",blank=True, null=True)
    age = models.CharField(verbose_name='年龄',max_length=30,blank=True, null=True,help_text='年龄')
    face = models.ImageField(upload_to='pic')
    create_time = models.CharField(max_length=30,verbose_name='时间', blank=True, null=True)

    class Meta:
        db_table = 'people'
        verbose_name = '人物信息'
        verbose_name_plural = verbose_name
  • serializer.py的内容
class PeopleSerializer(serializers.ModelSerializer):
    face = serializers.ImageField(max_length=None, use_url=True)

    class Meta:
        model = People
        fields = ("__all__")
  • views.py的内容
class PeopleViewSet(ModelViewSet):

    lookup_field = 'pk'
    serializer_class = PeopleSerializer

urls.py

router = DefaultRouter()
router.register('adddata', views.PeopleViewSet,basename='people')
  • settings.py的内容
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = 'media/'
  • postman测试


    image.png

    image.png
  • 发送请求,报错信息如下:

The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS错误
  • 解决方式,在settings.py中添加
DATA_UPLOAD_MAX_NUMBER_FIELDS = 10240

  • 再次运行,成功
{
    "code": 201,
    "message": "保存成功",
    "data": {
        "id": 15,
        "face": "http://0.0.0.0:8000/people/adddata/media/pic/dubai-5041154_1920.jpg",
        "update_time": "2020-04-17T10:06:17.418673",
        "gender": "1",
    }
}

你可能感兴趣的:([d-5]django上传图片并使用postman测试)