question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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:closed
  • Created 5 years ago
  • Comments:6

github_iconTop GitHub Comments

4reactions
StevenMapescommented, May 28, 2019

This is a work around. You need to add the following CSS class overload to your projects CSS.

.invalid-feedback {
    display: initial;
}```

The default invalid-feedback which has a` display:None` so the errors messages are added to the DOM but do not appear so this overloads it.

The BS4 resource for .invalid feedback is [Form Styles](https://getbootstrap.com/docs/4.0/components/forms/)

2reactions
jennyd1commented, Feb 25, 2021

This is a work around. You need to add the following CSS class overload to your projects CSS.

.invalid-feedback {
    display: initial;
}```

The default invalid-feedback which has a` display:None` so the errors messages are added to the DOM but do not appear so this overloads it.

The BS4 resource for .invalid feedback is [Form Styles](https://getbootstrap.com/docs/4.0/components/forms/)

Thank you, after searching so many resources, and going over my code to try and find the error, this resolution resolved my issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I raise Validation Error for a FileField - Stack Overflow
1 Answer 1 ... So you just need to change the indentation at the end of the view, so that you return a...
Read more >
Validators - Django documentation
Writing validators¶. A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can...
Read more >
Webform | File Upload validation Error Message - Drupal
Hi Team,. I have used a "Document file" field type with the required option in the webform version - 8.x-5.22. The Form validation...
Read more >
Form Control: Upload a file field limitations are not working
When 'selected file types' such as pdf, .doc, .png etc. are added to the file upload field of the form, console error is...
Read more >
error_messages - Django Form Field Validation
The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found