0

Is there any option to get new filename uploaded by ModelForm in views.py?

I have ModelForm like this. I want to rename all files uploaded by users to unique name and followed this guide Enforce unique upload file names using django?

models.py

class SomePhotos(models.Model):

    def get_file_path(instance, filename):
        ext = filename.split('.')[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        return os.path.join('some_photos/', filename)

    image = models.ImageField(upload_to = get_file_path)
    link = models.URLField(verbose_name = u'URI', null = True, blank = True)
    title_color = RGBColorField()

This works great - files are saved as unique name to right directory, but my function in vievs.py stopped working because before unique renaming I have been using filename from POST but now file has other, unique name!

views.py

filename = request.FILES['image'].name

forms.py

class MotivatorForm(ModelForm):
     class Meta:
        model = SomePhotos
Community
  • 1
  • 1

1 Answers1

0

Once you saved your ModelForm, you can get at the file's path using your instance's .image.path

def myview(request):
    if request.method == "POST":
        form = MotivatorForm(request.POST, request.FILE)
        if form.is_valid():
            instance = form.save()
            filepath = instance.image.path
    # etc...
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118