views:

215

answers:

2

Hi,

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):

     fichier = 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.

+1  A: 

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.

Peter Rowell
+1  A: 
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'])
zalew
I'm not using models... I'm using Forms instead.
djibril
updated. if this is not what you're looking for, give some detailed info what's the problem.
zalew
upload_to='files/%m-%Y/' does not work with forms !
djibril
that was a ctrV sorry. still the rest is ok
zalew