Загрузка файлов в подкаталоги в каталоге медиа в Django
Я использую Django 3. Я пытаюсь загрузить файлы в определенные директории. location='media/dentist/diplomas/' и location='media/dentist/government_docs/'. Но все равно файлы напрямую загружаются в каталог /media. Но я хочу, чтобы файлы загружались в каталог dentist в каталоге 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)
as;
fs = FileSystemStorage()
filename = fs.save('dentist/diplomas/' + myfile.name, myfile)
и моя проблема решена.