开发者

USe dynamic destination folder for uploaded file in Django

I would like to create dynamically the destination of my uploaded files. But, it seems that the 'upload_to' option is only available for a models, not for forms. So the following code is wrong.

class MyForm(forms.Form):

     f开发者_运维百科ichier = forms.FileField(**upload_to='files/%m-%Y/'**)

In the view handling the uploaded file, the destination is static. How can I make it dynamic ?

Thank you.


class YourFileModel(models.Model)
    def upload_path(self, name):
        name = do_sth_with_name(name)
        folder = generate_folder_name(self.id, self.whatever_field)
        return 'uploads/' + folder + '/' + name

    file = models.FileField(upload_to=upload_path)

edit after comment

def handle_uploaded_file(file):
    # generate dynamic path
    # save file to that path

example here http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#handling-uploaded-files

if form from model, override the save() method

class YourForm(forms.ModelForm):
    fichier = forms.FileField()
    def save(self):
        if self.cleaned_data['fichier']:
            file = handle_uploaded_file(self.cleaned_data['fichier'])
        super(YourForm, self).save()

if not form from model, call the upload handler in your view

def your_view(request):
    #####
    if form.is_valid():
        file = handle_uploaded_file(form.cleaned_data['fichier'])


Instead of a string, supply a callable -- i.e. the name of a function that takes the model instance and a string, and returns the desired name. See FileField docs for specifics. One thing they don't say (at least I can't find it in the docs) is that if the returned filename starts with '/' then it is an absolute path, otherwise it is relative to your /media directory.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜