Open In App
Related Articles

FileExtensionValidator – Validate File Extensions in Django

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 manage.py startapp main

Then add the app name inside your INSTALLED_APPS inside the settings.py

Syntax :-

FileExtensionValidator(allowed_extensions, message, code)

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

models.py

Python3

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

                    

forms.py

Python3

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

                    

views.py

Python3

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})

                    

index.html

HTML

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

                    

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.



Last Updated : 16 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads