我正在使用 FileExtensionValidator Django 的 FileField 并利用此答案来限制文件大小,两者都可以正常工作,但不会显示验证错误消息。
我正在使用 Django 2.1。以下是我的代码:
模型
from django.core.validators import FileExtensionValidator
class Project(models.Model):
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='projects',
)
title = models.CharField(
_('project name'),
max_length=100,
help_text=_('Required. 100 characters or fewer.'),
)
slug = models.SlugField(
_('slug'),
max_length=80,
)
created = models.DateTimeField(
_('dateTime created'),
auto_now_add=True,
)
xmlfile = models.FileField(
_('input file'),
upload_to=user_directory_path,
validators=[FileExtensionValidator(allowed_extensions=('xml',))],
help_text=_('Required. Please upload an XML file.'),
)
形式
from django.core.exceptions import ValidationError
def file_size(value):
limit = 9 * 1024 * 1024
if value.size > limit:
raise ValidationError('File too large. Size should not exceed 9 MiB.')
class ProjectForm(forms.ModelForm):
xmlfile = forms.FileField(
label='XML File Upload',
widget=forms.FileInput(attrs={'accept':'application/xml'}),
validators=[file_size],
)
class Meta:
model = Project
widgets = {
'owner': HiddenInput(),
}
看法
class ProjectCreate(CreateView):
form_class = ProjectForm
model = Project
template_name = 'project_new.html'
success_url = reverse_lazy('my_projects_list')
def get_initial(self):
initial = super().get_initial()
initial['owner'] = self.request.user
return initial
我测试了这段代码。当尝试上传小于 9M 的 XML 文件时,它可以工作并且用户被带到成功 URL。但是当文件格式或文件大小错误时,我们继续停留在project_new.html页面上是正确的,但奇怪的是这个页面上并没有显示与FileExtensionValidator和file_size()相关的错误信息。你知道为什么吗?我在哪里犯错了?
感谢您的时间和帮助!