Answer the question
In order to leave comments, you need to log in
How to limit image upload size in Django?
Good afternoon. Trying to make a simple limited image uploader. I've been trying to solve this problem for 2 days, but so far nothing
Question 1: How can I limit the uploaded object to 200 kb?
My attempts:
models.py
class UploadImage(models.Model):
title = models.CharField(max_length=100, unique=True, verbose_name='Введите название изображения')
cover = models.ImageField(upload_to='images/', verbose_name='')
def __str__(self):
return self.title
class PostForm(forms.ModelForm):
class Meta:
model = UploadImage
fields = ['title', 'cover']
def clean_image(self):
cover = self.cleaned_data.get('cover', False)
if cover:
if cover.size > 4*1024*1024:
raise ValidationError("Image file too large ( > 4mb )")
return cover
else:
raise ValidationError("Couldn't read uploaded image")
class IndexView(LoginRequiredMixin, CreateView):
template_name = 'upload/index.html'
form_class = PostForm
model = UploadImage
success_url = '/upload/'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['message'] = ''
return context
if 1 + 2 == 3:
IndexView.get_context_data(self, message) = 'Всё верно'
else:
IndexView.get_context_data(self, message) = 'Неверно'
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question