我正在开发一个同时使用 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
感谢您的任何帮助或建议。
这是完整的回溯:
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'