如何重命名通过 Django Rest Framework 上传的图像
How do I rename image that I uploaded through Django Rest Framework
我在重命名上传的图片时遇到问题。我希望我上传的图像具有名称 model['name'].jpg
,而不是使用原始名称。如果我直接从 django 上传它,我没有问题,但是如果我通过 Django Rest Framework 上传图像,我不知道该怎么做。
这是我的model.py:
class Shop(models.Model):
date = datetime.datetime.now()
year_now = int(date.strftime('%Y'))
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20, unique=True)
slug = models.SlugField(default='')
logo = models.ImageField(upload_to=rename_and_path)
industry = models.CharField(max_length= 20, choices=industry_choice)
business_start = IntegerBoundedField(min_value=1950, max_value=year_now)
franchise_start = IntegerBoundedField(min_value=1950, max_value=year_now)
headquarter = models.CharField(max_length=100)
units = models.IntegerField()
description = models.TextField()
joined = models.DateTimeField(auto_now_add=True)
这是我的serializer.py:
class ShopSerializer(serializers.ModelSerializer):
class Meta:
model = Shop
fields= '['name', 'slug', 'logo', 'user', 'industry',
'business_start', 'franchise_start', 'headquarter',
'units', 'description', 'joined']'
这是我在 views.py 中的视图集:
class ShopViewSet(ModelViewSet):
queryset = Shop.objects.all()
serializer_class = ShopSerializer
lookup_field = 'slug'
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.initial_data['user'] = request.user.id
serializer.initial_data['slug'] = slugify(request.data['name'])
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
所以我想知道如何在 logo 字段中重命名上传的图片。
您想要做的是在模型级别处理文件名修改,以便从您的自定义视图、django admin 甚至 django-rest-framework 上传的任何内容都将得到相同的处理。
从您的代码片段来看,您似乎正在尝试这样做,但我不知道 rename_and_path
的定义。
所以在你的 Shop 模型上面定义下面的方法
def logo_dir_path(instance, filename):
extension = filename.split('.')[-1]
og_filename = filename.split('.')[0]
new_filename = "shop_%s.%s" % (instance.name, extension)
return new_filename
然后在模型的徽标字段中添加以下属性:
logo = models.ImageField(upload_to=logo_dir_path)
我在重命名上传的图片时遇到问题。我希望我上传的图像具有名称 model['name'].jpg
,而不是使用原始名称。如果我直接从 django 上传它,我没有问题,但是如果我通过 Django Rest Framework 上传图像,我不知道该怎么做。
这是我的model.py:
class Shop(models.Model):
date = datetime.datetime.now()
year_now = int(date.strftime('%Y'))
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20, unique=True)
slug = models.SlugField(default='')
logo = models.ImageField(upload_to=rename_and_path)
industry = models.CharField(max_length= 20, choices=industry_choice)
business_start = IntegerBoundedField(min_value=1950, max_value=year_now)
franchise_start = IntegerBoundedField(min_value=1950, max_value=year_now)
headquarter = models.CharField(max_length=100)
units = models.IntegerField()
description = models.TextField()
joined = models.DateTimeField(auto_now_add=True)
这是我的serializer.py:
class ShopSerializer(serializers.ModelSerializer):
class Meta:
model = Shop
fields= '['name', 'slug', 'logo', 'user', 'industry',
'business_start', 'franchise_start', 'headquarter',
'units', 'description', 'joined']'
这是我在 views.py 中的视图集:
class ShopViewSet(ModelViewSet):
queryset = Shop.objects.all()
serializer_class = ShopSerializer
lookup_field = 'slug'
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.initial_data['user'] = request.user.id
serializer.initial_data['slug'] = slugify(request.data['name'])
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
所以我想知道如何在 logo 字段中重命名上传的图片。
您想要做的是在模型级别处理文件名修改,以便从您的自定义视图、django admin 甚至 django-rest-framework 上传的任何内容都将得到相同的处理。
从您的代码片段来看,您似乎正在尝试这样做,但我不知道 rename_and_path
的定义。
所以在你的 Shop 模型上面定义下面的方法
def logo_dir_path(instance, filename):
extension = filename.split('.')[-1]
og_filename = filename.split('.')[0]
new_filename = "shop_%s.%s" % (instance.name, extension)
return new_filename
然后在模型的徽标字段中添加以下属性:
logo = models.ImageField(upload_to=logo_dir_path)