我目前通过使用带有angularJS的Django REST框架创建的API上传图像 但问题是它存储为媒体文件但未存储在数据库中。
这是我的ViewSet
代码。
# views.py
import time
from rest_framework import viewsets
from rest_framework.permissions import IsAdminUser
from django.contrib.auth import get_user_model
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
permission_classes = (IsAdminUser,)
serializer_class = UserSerializer
queryset = get_user_model()
def perform_update(self, serializer):
serializer.save(profile_image=self.request.data.get('file'))
但是,当我在time.sleep(1)
函数之前添加代码serializer.save()
时,它已成功地神秘地保存到数据库中。
def perform_update(self, serializer):
time.sleep(1) # Delay 1s
serializer.save(profile_image=self.request.data.get('file'))
为什么会这样?请给我一个明智的解决方案。
我不知道它是否会有所帮助,所以我附上了angularjs代码。
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
return $http.patch(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}])
这是我要求分享的User
模型。我省略了与错误无关的代码
我确认图像保存在我指定的路径中。但未保存在数据库中。
# models.py
import datetime
import os
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
def set_filename_format(now, instance, filename):
return "{username}-{date}-{microsecond}{extension}".format(
username=instance.username,
date=now.date().strftime("%Y-%m-%d"),
microsecond=now.microsecond,
extension=os.path.splitext(filename)[1],
)
def profile_image_path(instance, filename):
now = datetime.datetime.now()
path = "profile_images/{username}/{year}/{month}/{day}/{filename}".format(
username=instance.username,
year=now.year,
month=now.month,
day=now.day,
filename=set_filename_format(now, instance, filename),
)
return path
class User(AbstractBaseUser, PermissionsMixin):
# ...
profile_image = models.ImageField(
upload_to=profile_image_path,
blank=True,
)
# ...