Расширения файлов в Django

Я создал сайт загрузки файлов, где я хочу позволить пользователям загружать файлы в формате pdf, ppt, doc, txt и zip. Я использую HTML форму для загрузки файлов.

model.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')

Я пытался сделать это, следуя этому руководству, но у меня ничего не получается. пожалуйста, помогите мне добиться этого

Вы можете решить свою проблему, используя эту статью.

Вы можете проверить расширения загружаемых файлов с помощью следующей функции.

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, )
    )
Вернуться на верх