'file extentions in Django

I have created a file upload website where I want to allow users to upload files in pdf, ppt, doc, txt, and zip format. I am using the HTML form to upload files.

models.py:

class Upload_Notes(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
uploadingdate = models.CharField(max_length=30)
branch = models.CharField(max_length=30)
subject = models.CharField(max_length=50)
notesfile = models.FileField(null=True)
filetype = models.CharField(max_length=30)
description = models.CharField(max_length=200, null=True)
status = models.CharField(max_length=15)

def __str__(self):
      return f'{self.user} notes'

view.py

def upload_notes(request):
if request.method=='POST':
    branch = request.POST['branch']
    subject = request.POST['subject']
    notes = request.FILES['notesfile']
    filetype = request.POST['filetype']
    description = request.POST['description']

    user = User.objects.filter(username=request.user.username).first()
    Upload_Notes.objects.create(user=user,uploadingdate=date.today(),branch=branch,subject=subject,notesfile=notes,
                             filetype=filetype,description=description,status='pending')
    messages.success(request,f"Notes uploaded from {request.user.username} successfully!")
    return redirect('/view_mynotes')
return render(request,'user/upload_notes.html')

I want to do like When the user selects file type PDF and if he trying to upload a file with another extension then an error should be popup Please upload pdf file and it should be same for all extensions like ppt doc zip txt please help me to achieve this



Solution 1:[1]

You can solve your problem using this article.

You can validate the file extensions to be uploaded with the following function.

import os
from django.core.exceptions import ValidationError
from django.db import models

def validate_file_extension(value):
ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
valid_extensions = ('.pdf', '.ppt', '.doc')  # Only allowed extensions.
if not ext.lower() in valid_extensions:
    raise ValidationError('Unsupported file.')


class ExampleModel(models.Model):
    example_field = models.FileField(
        'Example Field',
        upload_to='upload_folder/',
        validators=(validate_file_extension, )
    )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Umut