文件扩展名



我创建了一个文件上传网站,我想让用户上传pdf, ppt, doc, txt和zip格式的文件。我正在使用HTML表单上传文件。

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

我想这样做当用户选择文件类型PDF,如果他试图上传一个文件与另一个扩展名,那么错误应该弹出请上传PDF文件,它应该是相同的所有扩展,如PPT doc zip TXT请帮我实现这个

您可以使用这篇文章来解决您的问题。

您可以使用以下函数验证要上传的文件扩展名。

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

相关内容

  • 没有找到相关文章

最新更新