在Django中,按文件类型限制图像文件上传

时间:2014-08-25 04:57:22

标签: django image

我有一个图片文件上传表格,如下所示,

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 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))

一切正常。但我想限制用户上传不是A JPEG图像文件的图像。我想用户只上传JPEG图像文件。现在我该怎么做?

3 个答案:

答案 0 :(得分:1)

  

但我希望限制用户上传不是A JPEG图像的图像   file.That是我想用户只上传JPEG图像文件。现在怎么办   我可以这样做吗?

您可以在clean方法上添加额外的验证规则。

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

答案 1 :(得分:1)

Django 附带 FileExtensionValidator 验证器。

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

所以,它可以如下使用:

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

答案 2 :(得分:0)

这可能有错误,你必须清除它

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