How to display validation error message for FileField?
See original GitHub issue- Package version:1.7.2
- Django version:2.1
- Python version:3.7
- Template pack: Bootstrap4
I have a FileField in my model and I implemented Django’s FileExtensionValidator, as well as my own custom field validator to check the file size. It works, but crispy-forms doesn’t display error message when these validations fail.
Model
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.'),
)
Form
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(),
}
Template
{% 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 %}
View
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
When trying to upload an XML file less than 9M, it works and the user is brought to the success URL. But when either file format or file size is wrong, it’s correct that we continue to stay on the page of project_new.html, but no error message is displayed on this page related to FileExtensionValidator or file_size().
When I change {{ form|crispy }}
to {{ form.as_p }}
, the validation error will be displayed on the screen. Do you know how to display validation error messages when using {{ form|crispy }}
? Thank you!
Issue Analytics
- State:
- Created 5 years ago
- Comments:6
Top GitHub Comments
This is a work around. You need to add the following CSS class overload to your projects CSS.
Thank you, after searching so many resources, and going over my code to try and find the error, this resolution resolved my issue.