views:

70

answers:

1

I'm using an Ajax code for uploading files. Django takes good care of file uploads on ModelForms. Just writing form.save() would upload any file data in the header, manage creating the folders if needed and even rename the file if a duplicate already exists. Take this ModelForm which only has one filed named file for example:

class UploadFileForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('file',)

Since I'm using Ajax the only information I have in my view is request.FILES['file']. This is what I tried in my view:

 form = UploadFileForm(initial={'file':request.FILES['file']})
 if form.is_valid():
     form.save()

But it returns an invalid form (file is required). I can do this using pure Python but with the power of Django where's the point in that?

A: 
form = UploadFileForm(request.FILES)
if form.is_valid():
    form.save()

initial parameter let you initialize form fields, like giving a new form filed some initial data.

Here, you are getting the file data from a request.

FallenAngel
Thanks, Just need to change the first line of your code to "form=UploadFileForm(request.POST, request.FILES)". From my understaing the first paramater must be request.POST.
Siavash M