开发者

How can I rename the images uploaded in Django model

开发者 https://www.devze.com 2023-03-18 00:24 出处:网络
I have this code to submit the form: form = form_class(request.POST, request.FILES, instance=object) if form.is_valid():

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

0

精彩评论

暂无评论...
验证码 换一张
取 消