How to extract a File object from a Django Form FileField

I created a ModelForm with fields, title , file and content . Here file is FileField (). But I can’t name the save() method of this form for some reason. Therefore, I have to create one model object and assign cleared values ​​to this object. Everything worked that FileField. The file is not saved. How can i fix this? Is this the right method to extract a filefield?

The 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() 

The file is not saved here. How can i fix this? Any help would be appreciated!

+4
source share
3 answers

You use enctype="multipart/form-data" in your form. The code seems to be in order.

+5
source

Please use this type of check. It can work

 if request.method == 'POST': form = ModelFormWithFileField(request.POST, request.FILES) if form.is_valid(): # file is saved form.save() return HttpResponseRedirect('/success/url/')`` 
+2
source

I think you can use

 request.FILES['file'] 

to get a file object

0
source

All Articles