Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uploading files in subdirectories in media directory in Django

I am using Django 3. I am trying to upload files to specific directories. location=’media/dentist/diplomas/’ and location=’media/dentist/government_docs/’ directories. But still files are directly uploaded to /media directory. But i want files to be uploaded into dentist directory under media directory.

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your code should work, but you can also try this instead:

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading