请求方式为post方式:
上传图片部分
import requests
def main():
with open('../2222.jpg','rb') as f:
img = f.read()
file = {'image':('img.jpg',img,'image/jpg')} # image为字段名 不能修改
connt = requests.post('http://192.168.1.180:8000/kolinfo/',files=file)
print(connt.content.decode('utf-8'))
if __name__ == '__main__':
main()
如下 django 模型类中带有图片字段,上传图片的代码如上
def user_directory_path(instance, filename):
ext = filename.split('.')[-1]
filename = '{}.{}'.format(uuid.uuid4().hex[:8], ext)
# return the whole path to the file
return "{0}/{1}/{2}".format("image", datetime.datetime.now().strftime('%Y/%m/%d'),filename)
class 模型类名(models.Model):
image = models.ImageField(default='',null=True,blank=True,verbose_name='头像',upload_to=user_directory_path)
class Meta:
db_table = '表名'
视图自行定义