[Answered ]-Django validator not triggering on file upload

2👍

   if form.is_valid():
        newdoc = Document(docfile=request.FILES['docfile'])
        if not '.gif' in newdoc.name:
            raise ValidationError('File type not supported.')
        else:
            newdoc.save()
            messages.add_message(request, messages.INFO, "Saved")

try this simple solution, hope it works as you need

0👍

Looks right so far. Maybe it’s simply a lower/upper case issue?

A more accurate solution might be:

import os

def validate_file_type(upload):
    if os.path.splitext(upload.name)[1].lower() != '.gif':
        raise ValidationError('File type not supported.')

If it’s still not working try to add a break point within the validation method and check the value of upload.name.

0👍

I think the problem is the form is derived from a simple Model class, but in your case you must use ModelForm instead.

This way the form knows about the Document model, and you can do some fancy operations, like calling the save mehond in the Form object so save the model instance. Also the is_valid method calls all the validations defined in the model, in addition to the validations defined in the Form itself.

👤Dayana

Leave a comment