Md. Tanvir Raihan
Md. Tanvir Raihan

Reputation: 4285

In Django Restrict image file upload by file type

i have an image file upload form as follow,

from django import forms

class DocumentForm(forms.Form):

    name = forms.CharField(label='Name Of Your Image',widget=forms.TextInput(attrs={'class' : 'form-control',}))
    photo = forms.ImageField(
        label='Select a file',)
    Certification = forms.BooleanField(label='I certify that this is my original work')
    description = forms.CharField(label='Describe Your Image',widget=forms.TextInput(attrs={'class' : 'form-control',}))
    Image_Keyword = forms.CharField(label='Keyword Of Image',widget=forms.TextInput(attrs={'class' : 'form-control',}))

and this is the view

def UserImageUpload(request):


    if request.method == 'POST':
        form = DocumentForm(request.POST,request.FILES)
        if form.is_valid():
            messages.add_message(request, messages.SUCCESS, 'Your Image upload is waiting for Admin approval')


            newdoc = Photo(photo =  request.FILES['photo'],watermarked_image=request.FILES['photo'],user = request.user,name =  request.POST['name'],description = request.POST['description'],keyword =  request.POST['Image_Keyword'],Certified=request.POST['Certification'])

            newdoc.save()
        else:
            messages.add_message(request, messages.ERROR, 'Something is Missing!')



    else:
        form = DocumentForm()

    uploaded_image = Photo.objects.all()

    return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))

everything is working fine.But i want restrict user to upload an image which is not A JPEG image file.That is i want to user to upload only JPEG image file. Now how can i do this?

Upvotes: 1

Views: 4266

Answers (5)

Hai Nguyen
Hai Nguyen

Reputation: 21

You can use this:

uploader = forms.FileField(widget=forms.FileInput(attrs={'accept': 'image/jpg'}))

Upvotes: 1

Mehrdad995
Mehrdad995

Reputation: 47

Django has added a FileExtensionValidator for model fields in version 1.11, the doc is here.

from django import forms    
from django.core.validators import FileExtensionValidator
            
class SampleForm(forms.Form):
    file = forms.ImageField(validators=[FileExtensionValidator(allowed_extensions=['jpg'])])

don't forget to include allowed_extensions or the error message on the website will appear inappropriately.

Upvotes: 1

Maria Mozgunova
Maria Mozgunova

Reputation: 51

Django ships with FileExtensionValidator validator.

Django docs https://docs.djangoproject.com/en/3.1/ref/validators/#fileextensionvalidator

So, it can be used as following:

from django import forms    
from django.core.validators import FileExtensionValidator
            
class SampleForm(forms.Form):
    file = forms.ImageField(validators=[FileExtensionValidator('jpg')])

Upvotes: 3

nKandel
nKandel

Reputation: 2575

But i want restrict user to upload an image which is not A JPEG image file.That is i want to user to upload only JPEG image file. Now how can i do this?

You can add extra validation rule on clean method.

from django import forms


class DocumentForm(forms.Form):
    name = forms.CharField(label='Name Of Your Image', widget=forms.TextInput(attrs={'class': 'form-control', }))
    photo = forms.ImageField(label='Select a file', )
    Certification = forms.BooleanField(label='I certify that this is my original work')
    description = forms.CharField(label='Describe Your Image',
                                  widget=forms.TextInput(attrs={'class': 'form-control', }))
    Image_Keyword = forms.CharField(label='Keyword Of Image', widget=forms.TextInput(attrs={'class': 'form-control', }))

    def clean_photo(self):
        image_file = self.cleaned_data.get('photo')
        if not image_file.name.endswith(".jpg"):
            raise forms.ValidationError("Only .jpg image accepted")
        return image_file

Upvotes: 3

Raja Simon
Raja Simon

Reputation: 10305

This may have bugs, you have to clear it

class DocumentForm(forms.Form):
    class Meta:
       #form field here

def clean_image(self):
    cleaned_data = super(DocumentForm,self).clean()
    photo = cleaned_data.get("photo")
    if photo:
        if not photo.name[-3:].lower() in ['jpg']:
            raise forms.ValidationError("Your file extension was not recongized")
    return photo

Upvotes: 1

Related Questions