Я пробовал создать отдельное поле:
fields.py
class LimitedImageField(ImageField):
def __init__(self, *args, **kwargs):
self.max_dim = kwargs.pop('max_dim', None)
def clean(self, *args, **kwargs):
data = super(LimitedImageField, self).clean(*args, **kwargs)
try:
w, h = get_image_dimensions(img_file)
if self.max_dim:
if (w > self.max_dim[0]) or (h > self.max_dim[1]):
err_msg = 'Разрешение изображения не должно превышать {}x{}'.format(*self.max_dim)
raise forms.ValidationError(err_msg)
except AttributeError:
pass
return data
Еще я пробовал в самой форме:
forms.py
class upload_skin(ModelForm):
logo = forms.LimitedImageField(max_dim=(300, 300), widget=forms.FileInput(attrs={'type': "file", 'class': "skin-btn_skin", }))
class Meta:
model = Profile
fields = {'logo',}
def clean_picture(self):
picture = self.cleaned_data.get("picture")
if not picture:
raise forms.ValidationError("Изображения не обнаружено!")
else:
w, h = get_image_dimensions(picture)
print(w, h)
if w > 64:
raise forms.ValidationError("У вас нет доступа")
if h > 64:<code lang="python">
raise forms.ValidationError("У вас нет доступа")
return picture
Не одно не другое не заработало, 1 варинат выдает ошибку, 2 вариант просто не работает.
Ошибка:
<code lang="python">
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\Projects\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner
response = get_response(request)
File "C:\Users\Admin\PycharmProjects\Projects\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Admin\PycharmProjects\Projects\Projects\user\views.py", line 131, in cabinet
form = upload_skin()
File "C:\Users\Admin\PycharmProjects\Projects\venv\lib\site-packages\django\forms\models.py", line 371, in __init__
super().__init__(
File "C:\Users\Admin\PycharmProjects\Projects\venv\lib\site-packages\django\forms\forms.py", line 107, in __init__
self.fields = copy.deepcopy(self.base_fields)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\copy.py", line 146, in deepcopy
y = copier(x, memo)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\copy.py", line 231, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\copy.py", line 153, in deepcopy
y = copier(memo)
File "C:\Users\Admin\PycharmProjects\Projects\venv\lib\site-packages\django\forms\fields.py", line 256, in __deepcopy__
result.error_messages = self.error_messages.copy()
AttributeError: 'LimitedImageField' object has no attribute 'error_messages'
</code>