Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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/')``

I think you can use

request.FILES['file']

for getting the file object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top