Revolvelot McShooty Revolvelot McShooty -4 years ago 65
Python Question

Django validator not triggering on file upload

I have wrote a Django app for the user to upload files and see a list of uploaded files. I want to restrict the uploads to only using gif format and wrote a simple validator. Then I pass that validator in the Model, however it never triggers and the file is saved regardless of the format. Here's what I got so far.

def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
messages.add_message(request, messages.INFO, "Saved")

# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list'))
form = DocumentForm() # A empty, unbound form

# Load documents for the list page
documents = Document.objects.all()

# Render list page with the documents and the form
return render(
{'documents': documents, 'form': form}

def validate_file_type(upload):
if not ([-4:] == '.gif'):
raise ValidationError('File type not supported.')

from .checkformat import validate_file_type

def content_file_name(instance, filename):
return '/'.join(['documents', str(filename), filename])

class Document(models.Model):
docfile = models.FileField(upload_to=content_file_name, validators=[validate_file_type], null=False, verbose_name="File")

class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file', widget=forms.FileInput(attrs={'accept':'image/gif'})

Is there something I'm missing? I've just started learning Django. Also, I know this is not a sercure way to check for a file type, but I just want to see it work to continue. Thank you for your time.

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

try this simple solution, hope it works as you need

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download