xlsxwriter to http response (download file) but with user data (forms) in django

Viewed 82

I'm stuck, I want to user on page create template to input data on based witch will be created a template. Here is what I got so far, but it wont work, I have tried with examples online, but those are usually don't take a data from users to create 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})
    else:
        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)
    workbook.close()
    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">
    <table>
      {{ form.as_table }}
    </table>
  </div>
  <div class="btn-block">
    <input type="button" type="submit" value="Create and Download!"/>
  </div>
</form>
{% 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'),
]
1 Answers

I guess the function create_template is duplicated?

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

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

The first one does not contain TemplateForm(). It is always called with this: path('create-template/', views.create_template, name='my-create-template') . Try to remove the first one.

Related