4
  • 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!

student
  • 289
  • 2
  • 14

1 Answers1

0

According to crispy docs: 'By default when django-crispy-forms encounters errors, it fails silently, logs them and continues working if possible. A settings variable called CRISPY_FAIL_SILENTLY has been added so that you can control this behavior. If you want to raise exceptions instead of logging, telling you what’s going on when you are developing in debug mode, you can set it to:

CRISPY_FAIL_SILENTLY = not DEBUG 

Besides you can check other error attributes here(documentation): https://django-crispy-forms.readthedocs.io/en/d-0/tags.html#helper-attributes-you-can-set

Olga
  • 146
  • 2
  • 6
  • Thank you for your reply. I added `CRISPY_FAIL_SILENTLY = not DEBUG` in the settings.py, but still the FileField error message generated by `FileExtensionValidator` or `file_size()` validator will not be displayed on the screen. What else should I do? – student Feb 26 '19 at 15:08