- 包版本:1.7.2
- Django 版本:2.1
- Python版本:3.7
- 模板包:Bootstrap4
我的模型中有一个 FileField,我实现了 Django 的 FileExtensionValidator,以及我自己的自定义字段验证器来检查文件大小。它可以工作,但是当这些验证失败时,crispy-forms 不会显示错误消息。
模型
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(),
}
模板
{% block content %}
<h1>New Project</h1>
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Create" />
</form>
{% endblock content %}
看法
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()相关的错误信息。
当我更改{{ form|crispy }}
为{{ form.as_p }}
时,验证错误将显示在屏幕上。您知道使用时如何显示验证错误消息{{ form|crispy }}
吗?谢谢!