如何使用 Django rest 框架将照片上传到我电脑中的文件

How to upload photos to a file in my computer using Django rest framework

我创建了照片模型、序列化程序和视图,用户可以将照片上传到我的网站。我了解到最好的解决方案是上传计算机上的照片和数据库中的路径。但是我怎样才能通过我的网站或我的 api 将照片上传到我的电脑?

Modèles.py

ken authentification. So for adding an Announcement the user must be authenticated.

Models.py

class User(AbstractUser):
    username = None
    email = models.EmailField(max_length=100, verbose_name='email', 
              unique=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

class Announcement(models.Model):
     author = models.ForeignKey(User, on_delete=models.CASCADE)
     name = models.CharField(max_length=100)
     photo = models.ManyToManyField(Photo, blank=True)

class Photo(models.Model):
     name = models.CharField(max_length=100)
     content_type = models.CharField(max_length=100)
     path = models.CharField(max_length=100)

Serializers.py


class AnnouncementSerializer(serializers.ModelSerializer):
    author = UserSerializer(required=True)
    parameters = ParameterSerializer(many=True, 
       required=False)
    photo = PhotoSerializer(many=True, 
        required=False)
    class Meta:
        model = Announcement
        fields = ['id', 'name', 'author', 
                         'parameters', 'photo']

class UserSerializer(serializers.ModelSerializer):
    photo = PhotoSerializer()
    class Meta:
        model = User
        fields = ['id', 'email','photo', ]

class ParameterSerializer(serializers.ModelSerializer):
    class Meta:
        model = Parameter
        fields = '__all__'
class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields = '__all__'

Views.py

class AnnouncementCreate(CreateAPIView):
    permission_classes = [IsAuthenticated]
    queryset = models.Announcement.objects.all()
    serializer_class = AnnouncementSerializer

您应该在模型中使用 ImageField。然后,当您将图像上传到 url 时,django 会将其保存在您应该在 settings.py:

MEDIA_ROOT 部分中设置的目录中

首先安装 pillow 以使用 ImageField:

pip3 install pillow

之后,将此字段作为照片添加到您的模型中:

...
photo = models.ImageField(...)
...

这可能会有帮助: