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 w开发者_运维百科ant that the image should be renamed to modelName_pk
.jpg and that value gets saved in image_path
How can I achieve that?
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
精彩评论