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?
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With