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

Error while excel exporting using Django xlwt

I am trying to export information to an Excel file from my web application using the xlwt library, but the following error appears in urls.py

TypeError: export_excel_av_items() missing 1 required positional
argument: ‘request’

models.py:

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

class Stock(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30, unique=True)
    quantity = models.IntegerField(default=1)
    is_deleted = models.BooleanField(default=False)

    def __str__(self):
        return self.name

views.py:

def export_excel_av_items(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="available-items.xls"'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Available Items')
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns= ['Name', 'Qty']

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()

    rows = Stock.objects.all().values_list(
        'name', 'quantity')

    for row in rows:
        row_num += 1

        for col_num in range(len(row)):
            ws.write(row_num, col_num, str(row[col_num]), font_style)
    wb.save(response)

    return response

urls.py:

path('', views.StockListView.as_view(), name='inventory'),
path('new', views.StockCreateView.as_view(), name='new-stock'),
path('stock/<pk>/edit', views.StockUpdateView.as_view(), name='edit-stock'),
path('stock/<pk>/delete', views.StockDeleteView.as_view(), name='delete-stock'),
path('inventory/export-excel', views.export_excel_av_items(), name='export-excel'),

>Solution :

In URLs, you point to the function, you don’t call it so the following line

path('inventory/export-excel', views.export_excel_av_items(), name='export-excel'),

shall be

path('inventory/export-excel', views.export_excel_av_items, name='export-excel'),
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