Search code examples
pythondjangoexcelopenpyxldjango-staticfiles

Where to put excel template file in django project


In my Django application users can get excel file for necessary data. I'm using openpyxl library for manipulating excel files. What i want to do is use an formatted excel file as an template for the file users download. I tryed to put my "template.xlsx" under static and other places but i couldn't reach file anyway.

This is how I open my excel file in the correspoding view:

filename = r'static\app1\template.xlsx'
    workbook = load_workbook(filename)

Also I'm not sure where to put my excel template file, neither how to get path to it. Thanks for any help.


Solution

  • Usually I would create some sort of resources directory. My directory structure would be something like this:

    project
    ----core
    --------settings.py
    --------urls.py
    --------wsgi.py
    ----app1
    --------resources
    ------------template.xlsx
    --------views.py
    

    You would then work with it like this:

    import os
    from django.conf import settings
    
    filename = os.path.join(settings.BASE_DIR, 'app1', 'resource', 'template.xlsx')
    workbook = load_workbook(filename)
    

    Also, I would highly suggest you don't do this kind of logic (or any kind of business logic) in views. Either use "fat models thin controllers" or introduce new service layer.