#StackBounty: #python #django #xlsxwriter Why I'm unable to download my document with django? and how to do it?

Bounty: 50

I’m new to django and still learning, and I got here, in my own infinite loop, if I do how I sholud it be but i have an errors and it won’t work, but if I do it like this there are no errors but it won’t work. I want to user to be able to create excel template as he wish, this is simplified version that I want to work, just input few information and on base of that to be able to create excel template.

This is views.py

from django.http import HttpResponse
from django.shortcuts import render
import xlsxwriter
from xlsxwriter import workbook
from django.forms import Form, CharField, ChoiceField, IntegerField
from django.core.validators import MaxValueValidator, MinValueValidator

def home(request):
    return render(request, 'my_app/home.html')

class TemplateForm(Form):
    doc_name = CharField(label='Document name')
    sheetnames = CharField(label='Sheetnames')
    choices = []
    for year in range (1900, 2050):
        choices.append( (year, year) )
    year1 = ChoiceField(label='Starting Year', initial=2021, choices=choices)
    year2 = ChoiceField(label='Ending Year', initial=2022, choices=choices)    
    row_names = CharField(label='Column names')

def create_template(request):
    if request.method == 'GET':
        form = TemplateForm()
        return render(request, 'my_app/create_template.html', {'form':form})
        form = TemplateForm(request.POST)

def create_form(doc_name, sheetnames, years, row_names):
    workbook = xlsxwriter.Workbook(doc_name + '_template.xlsx')
    worksheet_introduction = workbook.add_worksheet( "introduction" )
    for i in sheetnames:
        worksheet_data = workbook.add_worksheet(i)
        worksheet_data.write_row(0, 1, years)
        worksheet_data.write_column(1, 0, row_names)
    return workbook

This is my_app/templates/my_app/create_template.html

{% extends "my_app/base.html" %}
{% block content %}

<form action="create_template" method="GET">
  {% csrf_token %}
  <h1>Create your template</h1>
  <div class="item">
      {{ form.as_table }}
  <div class="btn-block">
    <input type="button" type="submit" value="Create and Download!"/>
{% endblock content %}

This is my_app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='my-home'),
    path('create-template/', views.create_template, name='my-create-template'),

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.