2

I have created a ModelForm with fields, title, file and content. Here file is a FileField(). But I can't call the save() method of this form due to some reasons. So I have to maually created one Model Object and assign cleaned values to that object. Everything worked excpt that FileField. The file is not saving. How can I fix this? Is it the correct method to extract FileField?

Form

class TestForm(forms.ModelForm):
    class Meta:
        model = Test
        fields = ('title','file', 'content',)

Views.py

 form = TestForm(request.POST,request.FILES)
 if form.is_valid():
     content = form.cleaned_data['content']
     file = form.cleaned_data['file']
     title = form.cleaned_data['title']
     fax = Fax()
     fax.title = title
     fax.file = file
     fax.content = content
     fax.save()

Here the file is not saving. How can I fix this? Any help will be appreciated!

Jubin Thomas
  • 1,003
  • 2
  • 12
  • 24
  • instead of form.cleaned_data['file'], use request.FILES['file'] - see https://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs#file-uploads – JamesO Aug 28 '12 at 12:11
  • Why can't you call the save method on the form? The ought to be the right way to do it. – super9 Aug 29 '12 at 04:46
  • @super9 its because I have create more than one object with that. There is a loop in the code, which I have omitted to describe it easily – Jubin Thomas Aug 29 '12 at 13:06

3 Answers3

6

Have u used enctype="multipart/form-data" in your form Seems like the code is fine.

Ani Varghese
  • 403
  • 2
  • 6
  • 17
2

Please using this type of validation. This may work

if request.method == 'POST':
    form = ModelFormWithFileField(request.POST, request.FILES)
    if form.is_valid():
        # file is saved
        form.save()
        return HttpResponseRedirect('/success/url/')``
arulmr
  • 8,620
  • 9
  • 54
  • 69
Abin Abraham
  • 497
  • 2
  • 11
  • 26
0

I think you can use

request.FILES['file']

for getting the file object

Rakesh
  • 81,458
  • 17
  • 76
  • 113