0

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?

Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
Siavash
  • 358
  • 1
  • 5
  • 19
  • Please comment and vote if this answer is enough or not? If it solves your problem, accept it. – Mp0int Sep 18 '10 at 10:23

1 Answers1

0
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.

Mp0int
  • 18,172
  • 15
  • 83
  • 114
  • 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 Sep 19 '10 at 08:32