3

I have a form, with a bunch of fields, and then I have a:

    profile_image=forms.ImageField(required=False)

The problem si that after the form.is_valid() check,

form.cleaned_data.get('first_name')

for example DOES return the actual name, however,

form.cleaned_data.get('profile_image')

DOES NOT return anynthing.

In the print(request.POST) output, i get

u'profile_image': [u'02 Portfolio Page.jpg']

but in the print(form.cleaned_data) i get:

 'profile_image': None

Why is the file lost at the is_valid check? What should I do?

UPDATE:

class NewChickForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
profile_image=forms.ImageField(required=False)
def do_save(self):
    u = Subject(
        first_name = self.cleaned_data.get('first_name'),
        last_name = self.cleaned_data.get('last_name'),
        profile_image = self.cleaned_data.get('profile_image'),
    )
    print(self.cleaned_data)
    u.save()
    return u

and

s = Subject()
form = NewChickForm(request.POST) # 1)do i add here `request.FILES` ?
if form.is_valid():
    s = form.do_save()
            # 2) s.profile_image = form.cleaned_data.get('profile_image')?

Even if i do #1) and #2), i still get NONE

1 Answer 1

16

Make sure you've used the correct enctype on your HTML form:

<form enctype="multipart/form-data" method="post" action="/foo/">

Also, make sure you bind request.FILES when you construct the form object.

# Bound form with an image field, data from the request
>>> f = ContactFormWithMugshot(request.POST, request.FILES)

Binding uploaded files to a form

Edit: File Uploads

Sign up to request clarification or add additional context in comments.

3 Comments

You were right. I didn't have the multipart. added. But I am not getting the binding thing too much. The django explanation seems to be very differently done from what I have in my code. Could you drop a line on how I should be doing it according to the new code I pasted in the UPDATE? that would be really awesome
The multipart data will be put in request.FILES, so you need to bind it to the form in #1 for is_valid to validate that field. I'm not sure about #2 as I always just extract the file from request.FILES directly instead of using cleaned_data.get(...) Have you inspected request.FILES to see if your data is there?
Here, this doc is probably a better explanation: docs.djangoproject.com/en/dev/topics/http/file-uploads/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.