pythondjangodjango-modelsdjango-rest-frameworkimagefield

How do I rename image that I uploaded through Django Rest Framework


I have a problem in renaming an uploaded image. Instead of using the original name, I want my uploaded image to have the name model['name'].jpg. I have no problems doing it if I upload it directly from django, but I can't figure out how do I do it if I upload the image through Django Rest Framework.

Here is my 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)

Here is my serializer.py:

class ShopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Shop
        fields= '['name', 'slug', 'logo', 'user', 'industry', 
                'business_start', 'franchise_start', 'headquarter', 
                'units', 'description', 'joined']'

And here is my viewset in 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)

So I would like to know how do I rename the uploaded image in the logo field.


Solution

  • What you want to do is handle the filename modification at model level, so that any uploads from your custom views, django admin and even django-rest-framework will be handled the same.

    From your snippets, it looks like you're trying to do this, but I don't see where rename_and_path is defined.

    So define the following method above your Shop model

    
    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
    

    Then on your logo field on the model, add the following attribute:

    logo = models.ImageField(upload_to=logo_dir_path)