Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

Django admin form process file upload: 'InMemoryUploadedFile' object has no attribute 'width'

I have this model

class CauroselImage(models.Model):
    title = models.CharField(max_length=200, blank=True)
    description = models.CharField(max_length=400, blank=True)
    image = models.ImageField(upload_to=settings.UPLOAD_DIR,)
    visible = models.BooleanField(default=True)

    def __str__(self):
        return self.title

that i want to set the image file minimum dimensions and I've found out the forms.py file is the way to go

class CauroselImageForm(forms.ModelForm):
    class Meta:
        model = CauroselImage
        exclude = ('',)

    def clean(self):
        cleaned_data = self.cleaned_data
        image = cleaned_data.get('image')
        if image.width < 1300 or image.height < 400:
            raise forms.ValidationError("Image dimensions is too small, minimum is 1300x400")
        return cleaned_data

and admin

class CauroselImageAdmin(admin.ModelAdmin):
    form = CauroselImageForm

admin.site.register(CauroselImage, CauroselImageAdmin)

it however throws this error

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/admin/pages/cauroselimage/1/change/

Django Version: 3.1.2
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'guides',
'pages',
'sorl.thumbnail',
'ckeditor',
'django.contrib.sites',
'django.contrib.humanize']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 614, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner
    return view(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1656, in change_view
    return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1534, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1573, in _changeform_view
    form_validated = form.is_valid()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid
    return self.is_bound and not self.errors
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors
    self.full_clean()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 375, in full_clean
    self._clean_form()
File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/forms/forms.py", line 402, in _clean_form
    cleaned_data = self.clean()
File "/home/sam/code/kpsga/pages/forms.py", line 26, in clean
    if image.width < 1300 or image.height < 400:

Exception Type: AttributeError at /admin/pages/cauroselimage/1/change/
Exception Value: 'InMemoryUploadedFile' object has no attribute 'width'
question from:https://stackoverflow.com/questions/66060744/django-admin-form-process-file-upload-inmemoryuploadedfile-object-has-no-attr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use from django get_image_dimensions:

from django.core.files.images import get_image_dimensions

class CauroselImageForm(forms.ModelForm):
    
    ...

    def clean(self):
        width, height = get_image_dimensions(self.cleaned_data.get('image'))
        if width < 1300 or height < 400:
            raise forms.ValidationError("Image dimensions is too small, minimum is 1300x400")
        return cleaned_data

Method get_image_dimensions is using python PIL (Python Imaging Library).

get_image_dimensions returns the (width, height) of an image, given an open file or a path. Set 'close' to True to close the file at the end if it is initially in an open state.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...