django ImageField - ' NoneType'宾语

时间:2014-05-23 14:37:20

标签: django django-models

这是我的档案 的 forms.py

class RegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField widget=forms.PasswordInput())
username = forms.CharField(max_length=15)
email = forms.CharField(max_length=25)
avatar = forms.ImageField(required=False)

class Meta:
    model = User
    fields = ('username', 'email', 'password', 'password2', 'avatar')

def clean_password2(self):
    password = self.cleaned_data.get("password")
    password2 = self.cleaned_data.get("password2")
    if not password2:
        raise forms.ValidationError("error")
    if password != password2:
        raise forms.ValidationError("error2.")  

    return self.cleaned_data


def clean_avatar(self):
    image = self.cleaned_data['avatar']
    if image.size > 1*1024:
        raise forms.ValidationError("Image file too large ( > 1kb )")
    return image

和 的 models.py

class User(AbstractBaseUser):
username = models.CharField(max_length=15, unique = True)
email = models.CharField(max_length=25, unique = True)
reg_date = models.DateTimeField(_('reg_date'), default=timezone.now)
user_rating = models.IntegerField(default='0')
avatar = models.ImageField(upload_to='avatars', blank=True)

register.html

<form class="form" action='/auth/register/' method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ form.as_p }}

            <div class="form-actions">
              <button type="submit" class="btn btn-info">Reg</button>

            </div>
        </form> 

最后 的 views.py

def register(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
    form = RegisterForm(data=request.POST)
    if form.is_valid():
        user = form.save()
        user.set_password(user.password)
        if 'avatar' in request.FILES:
            user.avatar = request.FILES['avatar']
        user.save()
        registered = True
    else:
        print form.errors
else:
    form = RegisterForm()
return render_to_response('loginsys/register.html', {'form': form, 'registered': registered}, context)

我收到了这个错误:

 'NoneType' object has no attribute 'size'

    Request Method:     POST Request URL:   xxxxx/auth/register/ Django Version:    1.6.2 Exception Type:   AttributeError Exception Value:     

'NoneType' object has no attribute 'size'

Exception Location:     /home/max/xxxxx/loginsys/forms.py in clean_avatar, line 37



    loginsys/forms.py in clean_avatar

        37  if image.size > 1*1024:

...

▶本地大战

Traceback Switch to copy-and-paste view

/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response

                        response = wrapped_callback(request, *callback_args, **callback_kwargs)

    ...
▶ Local vars
/home/max/xxxxx/loginsys/views.py in register

            if form.is_valid():

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in is_valid

            return self.is_bound and not bool(self.errors)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in errors

                self.full_clean()

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in full_clean

            self._clean_fields()

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in _clean_fields

                        value = getattr(self, 'clean_%s' % name)()

    ...
▶ Local vars
/home/max/xxxxx/loginsys/forms.py in clean_avatar

            if image._size > 1*1024:

    ...
▶ Local vars 

为什么对象总是&#39; NoneType&#39;?如果我删除了函数&#34; def clean_avatar(self)&#34;,则文件已成功保存。

1 个答案:

答案 0 :(得分:1)

1)您需要通过表单验证图像字段。

form = RegisterForm(data=request.POST, files=request.FILES)

2)您需要考虑用户没有选择图像,因为不需要图像字段。所以,在表单清理中你可以测试它:

if image and image.size > 1*1024:

我希望我有所帮助。