8

I have this code to submit the form:

form = form_class(request.POST, request.FILES, instance=object)
if form.is_valid(): 
form.save()

image_path = models.ImageField(upload_to='books/')

Currently books/book1/jpg gets inserted into that field.

But I want that the image should be renamed to modelName_pk.jpg and that value gets saved in image_path

How can I achieve that?

shahab
  • 313
  • 3
  • 16
user1
  • 2,159
  • 3
  • 19
  • 19
  • This is a good question, idk why there are no answers. – Ahmed I. Elsayed Sep 16 '19 at 19:21
  • The problem here is that before `save()` is called, pk is not assigned to the model instance. You can upload and then rename it by referring to this answer: https://stackoverflow.com/a/20139166/3803979 – Shipra Oct 29 '19 at 12:30

1 Answers1

2

Each of the uploaded files are saved to request.FILES which are instances of UploadedFile, so, using the name of the image field in the form you can access it: request.FILES['imagename'].name.

Then you can save the model instance as usual. Hope this helps someone else because this is a very old question

Vosem
  • 106
  • 1
  • 7