在Django中上传media目录下子目录下的文件



我使用的是Django 3。我试图上传文件到特定的目录。Location ='media/dental/diplomas/'和Location ='media/dental/government_docs/'目录。但文件仍然直接上传到/media目录。但我希望文件上传到牙医目录下媒体目录。

def create_account_dentist(request):
if request.method == 'POST':
#Upload Dentist Diploma and Government Document
uploaded_file_url = ""
uploaded_file_url2 = ""
if request.FILES['customFileInput1']:
myfile = request.FILES['customFileInput1']
fs = FileSystemStorage(location='media/dentist/diplomas/')
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
if request.FILES['customFileInput2']:
myfile2 = request.FILES['customFileInput2']        
fs2 = FileSystemStorage(location='media/dentist/government_docs/')        
filename2 = fs2.save(myfile2.name, myfile2)        
uploaded_file_url2 = fs.url(filename2)
print(uploaded_file_url2)
return redirect(reverse('dentist-section')) #Forward to Dentist Main Page
return render(request, 'create-account-dentist.html')

您的代码应该可以工作,但您也可以尝试以下方法:

def create_account_dentist(request):
if request.method == 'POST':
#Upload Dentist Diploma and Government Document
uploaded_file_url = ""
uploaded_file_url2 = ""
if request.FILES['customFileInput1']:
myfile = request.FILES['customFileInput1']
fs = FileSystemStorage()
filename = fs.save(f'dentist/diplomas/{myfile.name}', myfile) # <--
uploaded_file_url = fs.url(filename)
if request.FILES['customFileInput2']:
myfile2 = request.FILES['customFileInput2']        
fs2 = FileSystemStorage()        
filename2 = fs2.save(f'dentist/government_docs/{myfile2.name}', myfile2) # <--
uploaded_file_url2 = fs.url(filename2)
print(uploaded_file_url2)
return redirect(reverse('dentist-section')) #Forward to Dentist Main Page
return render(request, 'create-account-dentist.html')

我更改了下面的代码;

fs = FileSystemStorage(location='media/dentist/diplomas/')
filename = fs.save(myfile.name, myfile)

;

fs = FileSystemStorage()
filename = fs.save('dentist/diplomas/' + myfile.name, myfile)

,我的问题解决了。

最新更新