class Roob_Titles(models.Model):
# id= models.BigIntegerField(primary_key=True)
r_id = models.BigIntegerField()
r_title = models.CharField(max_length=100)
r_author =models.CharField(max_length=40)
r_date = models.DateTimeField()
images_url= models.FileField(upload_to='avatar/')
class Meta:
db_table = "runoob_tbl"
verbose_name = '菜鸟标题表'
ordering = ['id']
CREATE TABLE `runoob_tbl` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `r_id` varchar(100) NOT NULL, `r_title` varchar(100) NOT NULL, `r_author` varchar(40) NOT NULL, `r_date` datetime DEFAULT NULL, `images_url` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb3;
视图:
from django.shortcuts import render from .models import Roob_Titles from .serials.serials_model import RoobSerializer from rest_framework.parsers import FormParser,JSONParser,MultiPartParser,FileUploadParser # Create your views here. from rest_framework.viewsets import ModelViewSet class BaseRoobView(ModelViewSet): parser_classes = [MultiPartParser] lookup_field = 'id' queryset = Roob_Titles.objects.all() serializer_class = RoobSerializer
请求:
curl -X POST "http://127.0.0.1:8000/api/roob/" -H "accept: application/json" -H "Content-Type: multipart/form-data" -H
"X-CSRFToken: MztdPIk8H6uRstn3kArNyNr36WGpt20X71Do1ehxTZtQK8C7YsKt1Mrxk55HbUPR" -F "r_id=11" -F "r_title=22" -F "r_author=33" -F "r_date=2022-11-01 22:33:11" -F "images_url=@2022年半年度绩效计划模板 - xx.xlsx;type=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
响应:
{ "id": 7, "r_id": 1, "r_title": "2", "r_author": "3", "r_date": "2011-11-11 11:22:33", "images_url": "http://172.18.23.223:8000/2022%E5%B9%B4%E5%B7%A5%E4%BD%9C%E8%A7%84%E5%88%92%E6%B5%8B%E8%AF%95.xlsx" }
数据库:服务器地址自动拼接了
默认会上传到项目根目录,当然也可以指定目录:
settings.py:
除了指定目录外模型每个字段可以通过upload_to 指定media_root 目录下文件存在哪个子目录位置