user1
user1

Reputation: 2259

How can I rename the images uploaded in Django model

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?

Upvotes: 8

Views: 7917

Answers (1)

Vosem
Vosem

Reputation: 106

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

Upvotes: 2

Related Questions