大家好,我是Leo
今天我們會延續昨天的上傳檔案,但今天要講解的是上傳多個檔案
OK~~~ Let's go now!!!
如果我們今天想要敲一次API就能達到上傳多個user證照的圖檔,概念圖如下
如果不太清楚model內的function get_file的朋友,可以去看上一篇有介紹,主要是更改檔案存檔的路徑
models/user_certificates_model.py
from django.db import models
from website.models.users_model import Users
import uuid
import os
def get_file(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join(f'users/{instance.user.id}', filename)
class User_Certificates(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(Users, on_delete=models.PROTECT, to_field='id', related_name='user_certicicate_users',default=None,blank=True,null=True)
file_name = models.CharField(max_length=255,null=True)
file_path = models.FileField(upload_to=get_file,null=True, blank=True, default=None)
created_at = models.DateTimeField(auto_now_add = True,editable=False)
deleted_at = models.DateTimeField(null=True)
model/init.py
from .user_certificates_model import *
這邊file_path將serializer的type改成list,而裡面的子檔案為FieField的型式
validated_data 驗證成功,可以通過序列化器對象的獲取數據,獲取的是一個有序的字典類型的數據 data from views request.data的參數。
pop的用法,像是移除一個值,我們也可以將移除的值儲存在一個變數內
也就是說,如果我有一個dict 為{"apple":50,"orange":10,"banana":20}
如果我今天apple_value = dict.pop("apple") -> dict = {"orange":10,"banana":20}
而這時候apple_value = 50
serializers/user_certificates_ser.py
from rest_framework import serializers
from website.models import User_Certificates
class UserCertificatesSerializers(serializers.ModelSerializer):
file_path = serializers.ListField(
child=serializers.FileField(max_length=100000,
allow_empty_file=True,
use_url=True), write_only=True
)
class Meta:
model = User_Certificates
fields = ('file_name','file_path','user')
def create(self, validated_data):
file_path = validated_data.pop('file_path')
user = validated_data.pop('user')
file_name = validated_data.pop('file_name')
for img in file_path:
photo = User_Certificates.objects.create(
user=user,
file_name = file_name,
file_path=img
)
photo.save()
return user
serializers/init.py
from .user_certificates_ser import *
views/user_certificates.py
from rest_framework import generics,permissions
from rest_framework.response import Response
from website.serializers import UserCertificatesSerializers
class UserCertificatesCreateAPIViews(generics.CreateAPIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = []
def post(self, request, *args):
serializer = UserCertificatesSerializers(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response({'success': True,
'userId':request.data.get('user'),
'message': "certificates created successfully"})
return Response({'success': False,
'userId': request.data.get('user'),
'message': "certificates created error"})
views/init.py
from .user_certificates import *
urls.py
from website.views import (
UserCertificatesCreateAPIViews
)
path('api/user/certificates/create', UserCertificatesCreateAPIViews.as_view(), name='api-user-certificates-create')
今天主要是介紹多個檔案的上傳方式,明天我們來介紹縣市鄉鎮的篩選
我們明天見,各位掰掰~~~