Skip to content
Related Articles

Related Articles

Improve Article

FileExtensionValidator – Validate File Extensions in Django

  • Last Updated : 16 Mar, 2021
Geek Week

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

How to use FileExtensionValidator in Django ?

To demonstrate use of FileExtensionValidator, we will create a file uploader application that will validate ‘pdf’ files at backend.

First create new project.

django-admin startproject fileuploader
cd fileuploader

Then create new app inside the project

python startapp main

Then add the app name inside your INSTALLED_APPS inside the

Syntax :-

FileExtensionValidator(allowed_extensions, message, code)

Raises a ValidationError with a code of ‘invalid_extension’ if the extension of (value is a File) isn’t found in allowed_extensions. The extension is compared case-insensitively with allowed_extensions.


from django.core.validators import FileExtensionValidator
class Post(models.Model):
    PDF = models.FileField(null=True
                           validators=[FileExtensionValidator( ['pdf'] ) ])


from django.forms import ModelForm
from .models import *
from django import forms
class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = __all__


from django.shortcuts import render,HttpResponse
from .forms import *
# Create your views here.
def home(request):
    form = PostForm()
    return render(request,"main/index.html",{"form":form})



<!DOCTYPE html>
<title>Page Title</title>
<h2>Welcome To GFG</h2>
<form method="post">
    {% csrf_token %}
  <button type="submit">Upload</button>

User can only upload pdf files in this filefield. Otherwise it will throw exception. Moreover, it is always recommended to add client-side validation for such requirements. This article illustrates how can you validate file uploads at server end.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :