'ImageFieldFile' 对象只有在图片已经上传之后才没有属性 'content_type' 然后既不更改也不删除

Get*_*one 3 django django-models django-forms django-profiles

我正在开发一个同时使用 django 注册和 django 配置文件的项目。我有一个允许用户编辑/创建个人资料的表单,其中包括上传照片。在以下情况下一切正常:创建或编辑配置文件并且从未上传过任何图像;编辑/创建配置文件并上传图像;上传图像后,只要更改或删除先前上传的图像,就可以编辑配置文件......我遇到问题的地方是是否存在现有的配置文件图像,并且用户尝试编辑他的/她的配置文件而不对当前图像进行任何更改(即删除或替换它)。在这种情况下,我收到错误“ImageFieldFile”对象没有属性“content_type”。关于为什么会发生这种情况的任何想法。我已经尝试了在堆栈溢出中找到的其他答案的变体,但无法让它们中的任何一个像它们所说的那样工作。我目前拥有的是我所做的更改之一的变体:

class UserProfileForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        try:
            self.fields['email'].initial = self.instance.user.email
        except User.DoesNotExist:
            pass

    email = forms.EmailField(label="Primary email", help_text='')

    class Meta:
        model = UserAccountProfile
            exclude = ('user', 'broadcaster', 'type')
            widgets = {
            ...
        }


    def save(self, *args, **kwargs):
        u = self.instance.user
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(UserProfileForm, self).save(*args,**kwargs)
        return profile

    def clean_avatar(self):
        avatar = self.cleaned_data['avatar']            

        if avatar:
            w, h = get_image_dimensions(avatar)
            max_width = max_height = 500
            if w >= max_width or h >= max_height:
                raise forms.ValidationError(u'Please use an image that is %s x %s pixels or less.' % (max_width, max_height))

            main, sub = avatar.content_type.split('/')
            if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
                raise forms.ValidationError(u'Please use a JPEG, GIF or PNG image.')

            if len(avatar) > (50 * 1024):
                raise forms.ValidationError(u'Avatar file size may not exceed 50k.')

        else:
            pass

        return avatar
Run Code Online (Sandbox Code Playgroud)

感谢您的任何帮助或建议。

这是完整的回溯:

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  20.                 return view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\profiles\views.py" in edit_profile
  197.         if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  124.         return self.is_bound and not bool(self.errors)
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _get_errors
  115.             self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  270.         self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
  290.                     value = getattr(self, 'clean_%s' % name)()
File "C:\Documents and Settings\user\projects\xlftv\lftv\userprofiles\forms.py" in clean_avatar
  146.          main, sub = avatar.content_type.split('/')

Exception Type: AttributeError at /instructor_profiles/edit
Exception Value: 'ImageFieldFile' object has no attribute 'content_type'
Run Code Online (Sandbox Code Playgroud)

小智 5

上传文件时,根据文件大小,它将是InMemoryUploadedFile类的实例或作为TemporaryUploadedFile类的子类的UploadedFile类。

并且图像模型字段被保存为django.db.models.fields.files.ImageFieldFile对象。

因此,当表单在不修改图像字段的情况下再次提交时,该字段将是django.db.models.fields.files.ImageFieldFile上传文件django.core.files.uploadedfile.UploadedFile实例的实例。因此,在访问content_type属性之前检查表单字段的类型。

from django.core.files.uploadedfile import UploadedFile
from django.db.models.fields.files import ImageFieldFile

def clean_avatar(self):
    avatar = self.cleaned_data['avatar']            

    if avatar and isinstance(avatar, UploadedFile):
        w, h = get_image_dimensions(avatar)
        max_width = max_height = 500
        if w >= max_width or h >= max_height:
            raise forms.ValidationError(u'Please use an image that is %s x %s pixels or less.' % (max_width, max_height))

        main, sub = avatar.content_type.split('/')
        if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
            raise forms.ValidationError(u'Please use a JPEG, GIF or PNG image.')

        if len(avatar) > (50 * 1024):
            raise forms.ValidationError(u'Avatar file size may not exceed 50k.')

    elif avatar and isinstance(avatar, ImageFieldFile):
        # something
        pass

    else:
        pass

    return avatar
Run Code Online (Sandbox Code Playgroud)