0

In my view I am getting a file like :

def add_view(request):
    if request.method == "POST":
        my_files = request.FILES.getlist("file")
        for file in my_files:
            Here if file is greater than 2 Mb raise error and send error message
            Also check if the file is of type jpg. If it is then return something 

How can I do this ? I want to do it by taking constant variable from settings. Like setting MEDIA_TYPE or MIME_FORMAT in settings and also file size in setting

1 Answer 1

1

You can use something like this:

CONTENT_TYPES = ['image']
MAX_UPLOAD_PHOTO_SIZE = "2621440"
content = request.FILES.getlist("file")
content_type = content.content_type.split('/')[0]
if content_type in CONTENT_TYPES:
    if content._size > MAX_UPLOAD_PHOTO_SIZE:
        #raise size error
    if not content.name.endswith('.jpg'):
       #raise jot jpg error
else:
    #raise content type error

UPDATED

If you want a form validation, try this:

class FileUploadForm(forms.Form):
    file = forms.FileField()

    def clean_file(self):
        CONTENT_TYPES = ['image']
        MAX_UPLOAD_PHOTO_SIZE = "2621440"
        content = self.cleaned_data['file']
        content_type = content.content_type.split('/')[0]
        if content_type in CONTENT_TYPES:
            if content._size > MAX_UPLOAD_PHOTO_SIZE:
                msg = 'Keep your file size under %s. actual size %s'\
                        % (filesizeformat(settings.MAX_UPLOAD_PHOTO_SIZE), filesizeformat(content._size))
                raise forms.ValidationError(msg)

            if not content.name.endswith('.jpg'):
                msg = 'Your file is not jpg'
                raise forms.ValidationError(msg)
        else:
            raise forms.ValidationError('File not supported')
        return content
Sign up to request clarification or add additional context in comments.

4 Comments

I only want it to submit the photo of type jpg.. how to do that ?
also here content = request.FILES.getlist("file") is list of image. I want to check this for every image
@aryan just iterate over them and validate each one, using the form provided above or just validation code directly.
Small correction in your code MAX_UPLOAD_PHOTO_SIZE = "2621440" this should be an integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.