Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 538
user1 Avatar asked Jul 08 '11 07:07

user1


People also ask

Where does Django save uploaded files?

MEDIA_ROOT We have used the same join functions in Django static files tutorial that we have passed in the file path of media directory. This directory will store all the files a user uploads in Django. Although you can directly give the path as a string in MEDIA_ROOT.

How can add image in Django model form?

Create a file model fieldGo to models.py and add a FieldField() with a specified media file upload path. This is also an example of an ImageField() upload as a model field. upload_to automatically uploads to the media ROOT specified in the settings. You do not need to specify media in upload_to .


1 Answers

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

like image 97
Vosem Avatar answered Sep 27 '22 23:09

Vosem