Django验证器不会触发文件上传

时间:2017-06-13 07:34:35

标签: python django

我为用户编写了一个Django应用程序,用于上传文件并查看上传文件列表。我想将上传限制为仅使用gif格式并编写一个简单的验证器。然后我在模型中传递该验证器,但它永远不会触发,并且无论格式如何都保存文件。这是我到目前为止所得到的。

views.py

def list(request):
# Handle file upload
if request.method == 'POST':
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        newdoc = Document(docfile=request.FILES['docfile'])
        newdoc.save()
        messages.add_message(request, messages.INFO, "Saved")

        # Redirect to the document list after POST
        return HttpResponseRedirect(reverse('list'))
else:
    form = DocumentForm()  # A empty, unbound form

# Load documents for the list page
documents = Document.objects.all()

# Render list page with the documents and the form
return render(
    request,
    'list.html',
    {'documents': documents, 'form': form}
)

checkformat.py

def validate_file_type(upload):
if not (upload.name[-4:] == '.gif'):
    raise ValidationError('File type not supported.')

models.py

from .checkformat import validate_file_type

def content_file_name(instance, filename):
     return '/'.join(['documents', str(filename), filename])

class Document(models.Model):
    docfile = models.FileField(upload_to=content_file_name, validators=[validate_file_type], null=False, verbose_name="File")

forms.py

class DocumentForm(forms.Form):
docfile = forms.FileField(
    label='Select a file', widget=forms.FileInput(attrs={'accept':'image/gif'})
)

我有什么遗失的东西吗?我刚刚开始学习Django。另外,我知道这不是检查文件类型的安全方法,但我只想看到它继续工作。谢谢你的时间。

2 个答案:

答案 0 :(得分:0)

到目前为止看起来正确。也许这只是一个小/大写的问题?

更准确的解决方案可能是:

import os

def validate_file_type(upload):
    if os.path.splitext(upload.name)[1].lower() != '.gif':
        raise ValidationError('File type not supported.')

如果它仍然不起作用,请尝试在验证方法中添加断点并检查upload.name的值。

答案 1 :(得分:0)

   if form.is_valid():
        newdoc = Document(docfile=request.FILES['docfile'])
        if not '.gif' in newdoc.name:
            raise ValidationError('File type not supported.')
        else:
            newdoc.save()
            messages.add_message(request, messages.INFO, "Saved")

尝试这个简单的解决方案,希望它能够满足您的需求