Connor Meeks
Connor Meeks

Reputation: 501

Downloadable File from Django Management Command

I have been researching for days, and I still cant figure this out! Hopefully a fellow StackOverflower can help me out here.

So, right now I have a custom django management command that runs a report and sends and email containing the report as an xlsx file (excel). Now im wondering if there is a way to get that excel report on a website so that people could download it and view it for themselves if they dont want to get an email.

I already have my urls and html templates set up, all I need now is to put a link to my report (that is generated from my management command) into my template on my website so that anyone could download it!!! Please help! Im stuck!

management command (condensed)

FILENAME = tempfile.mkstemp('.xlsx', 'EDIComplianceReport')
class Command(BaseCommand):
    def handle(self, *args, **options):

    final_results[carrier_scac] = carrier_results


    ts_util.sendMessage(['[email protected]'],
                        'EDI Compliance Report', '\n EDI Compliance Report Attached',
                        self.populateSpreadsheet(final_results))



    def populateSpreadsheet(self, results):
            workbook = xlsxwriter.Workbook(STATICFILES_DIRS + 'ediportal/ComplianceSummaryReports/' + str(datetime.now().strftime('%Y%m%d%H%M%S'))) #appends a unique time at the end of the file to prevent overwrite



            format01 = workbook.add_format({'border': 1, 'bold': True,'align': 'center', 'bg_color': '#DDDDDD'})
            format02 = workbook.add_format({'border': 1, 'bold': True, 'bg_color': '#9999FF', 'align': 'center'})
            format03 = workbook.add_format({'border': 1, 'bold': True, 'font_color': 'red', 'bg_color': 'white', 'align': 'center'})
            format04 = workbook.add_format({'border': 1, 'bold': True, 'bg_color': 'white', 'align': 'center'})

            worksheet = workbook.add_worksheet("Summary")
            row = 0
            col = 0
            sorted_carriers = list(CARRIERS.keys())
            sorted_carriers.sort()
            for i, carrier in enumerate(sorted_carriers):
                worksheet.write(i+row, 0, carrier, format01)
                worksheet.write(i+row, 1, 'Estimated Overall Compliance', format01)
                worksheet.write(i+row+1, 1, results[carrier]['overall_compliance'], format03)
                for ind, code in enumerate(CARRIERS[carrier].split(',')):
                    if code != 'overall_compliance':
                        worksheet.write(i+row, ind+2, code, format02)
                        worksheet.write(i+row+1, ind+2, results[carrier][code], format04)
                row += 2

            workbook.close()
            return FILENAME[1]

Thus, I want to serve the file called EDIComplianceReport.xslx and allow others to download it as a link on a html template.

Right now it is just running on my local host machine!!! Ive had an idea of saving the excel workbooks to a static folder and grabbing it from there, but i just cant figure out the exact code to embed the document in my template...

Upvotes: 0

Views: 603

Answers (1)

cutteeth
cutteeth

Reputation: 2213

Set your MEDIA_ROOT in settings.py . You can try MEDIA_ROOT=BASE_DIR+'/media'. After that create your media url in settings.py as MEDIA_URL='/media/'. Then in template you can mention download url as src="{{MEDIA_URL}}/<DATE STRING HERE>" check Django docs on media files here and static files here. It is better to setup a model in your app's models.py to handle file uploads. A typical model looks like below.

class ExcelUploads(models.Model):
    excel_file = models.FileField(upload_to='/media/excel_files')
    description = models.CharField(max_length=255)

def __unicode__(self):
    return self.description

To provide download links for your excel files, make use of {% static %} template tag or {{MEDIA_URL}} after adding django.template.context_processors.media to your 'context_processors' under TEMPLATES section of settings.py.static tags are usually used to serve static files like css, js etc. Its good to use media_url to serve file downloads.

So based on the model definitions in the answer posted, your download links looks like src="{{MEDIA_URL}}/{{ExcelUploads[0].excel_file.url}}"

Upvotes: 1

Related Questions