Django:在form.is_valid检查之后,cleaning_data缺少图像字段

时间:2010-12-01 23:23:58

标签: django validation forms django-models

我有一个表格,有一堆字段,然后我有一个:

    profile_image=forms.ImageField(required=False)

在form.is_valid()检查之后的问题,

form.cleaned_data.get('first_name')

例如,DOES返回实际名称,

form.cleaned_data.get('profile_image')

不会返回任何东西。

在print(request.POST)输出中,我得到了

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

但是在print(form.cleaned_data)中我得到:

 'profile_image': None

为什么文件在is_valid检查时丢失了?我该怎么办?

更新:

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

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')?

即使我做#1)和#2),我仍然没有

1 个答案:

答案 0 :(得分:13)

确保您在HTML表单上使用了正确的enctype

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

此外,请确保在构造表单对象时绑定request.FILES

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

Binding uploaded files to a form

修改: File Uploads