R
R
Razer15112021-02-20 13:32:12
Django
Razer1511, 2021-02-20 13:32:12

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


forms.py
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")


For some reason, this method does not work, although here we are talking about 4mb

2. How to refer to the message object from the view?

views.py
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


I want to create an informational message in the same form check if the form worked correctly or not.
Tried something like this:

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

1 answer(s)
D
Dr. Bacon, 2021-02-20
@bacon

1. clean_image is clean image fields

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question