开发者

File upload after model save on Django admin

I am using a file upload in my Django model like this :

 def upload_path(self, filename):
    return 'upload/actualities/%s/%s' % (self.id, filename)

photo = models.ImageField(upload_to=upload_path)

and my adminModel is :

from actualities.models import *
from django.contrib import admin  

class ActualityAdmin(admin.ModelAdmin):
     class Media:
         js = ('/static/js/tiny_mce/tiny_mce.js', '/static/js/textareas.js')

 admin.site.register(Actuality, ActualityAdmin)

Everything work开发者_如何学Gos fine except when i edit mu model because it has an id. But when I create it, the file upload happens before the model saving... So i put my file in /media/actualities/None/filename.jpg, and I want /media/2/filename.jpg

How can I force to make the file upload after the model saving?

Thank you!!!


You will probably want to override the Model's save() method, and maybe come up with a custom "don't do anything" UploadHandler, then switch back to the original one and call save again.

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

https://docs.djangoproject.com/en/dev/topics/db/models/

What I would do in this situation however, is make a custom upload handler that saves the file off into some temp space. Then I'd override the save method (in a mixin or something) that moves the file from temp to wherever you wanted it.

@Tomek's answer is also another way. If you have your model generate it's own id, then you can use that.

A second to last suggestion which is what I do with my photo blog is instead of saving all the images in a directory like media/2/filename.jpg I save the image by date uploaded. 2011/10/2/image.jpg This kind of helps any directory from getting too unwieldy.

Finally, you could hash the file names and store them in directories of hash name to kind of equally spread out the images in a directory.

I've picked the date style because that's meaningful for me with that project. Perhaps there is another way you can name an image for saving that would mean something more than "model with id 2's pics" that you could use for this problem.

Good Luck!


As workaround, try generating UUID for file name (instead of using self.id).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜