简体   繁体   中英

How to save django FileField to user folder?

I've got a model like this

\ndef upload_location(instance, filename): return 'validate/%s/builds/%s' % (get_current_user(), filename) class MidletPair(models.Model): jad_file = models.FileField(upload_to = upload_location) jar_file = models.FileField(upload_to = upload_location) upload_to=tempfile.gettempdir() 

How can I get the current user in upload_location()... ?

Side note: Looking up django stuff is confusing as theres a lot of pre-1.0 stuff around on the net.

The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload_to function.

So you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object into the form's __init__ method and store it in an instance attribute, where you can get to it in a custom upload handler. For documentation on upload handlers, look here .

如果您在模型中添加了用户字段,并在执行上载之前设置了该属性,那么您可以通过instance属性将用户输入upload_location函数。

First, don't search the net for Django help. Search here only: http://docs.djangoproject.com/en/dev/

Second, the current user is part of Authentication.

http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth

The user is recorded in the request. request.user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM