Hello,
I am using Django to create a view in which I do several things:
- Generate a form
- Process validated data to create a table
- Return a template which shows the table
However, I would like to include in the template (that shows the table )a button which allows for the export of the table in csv. Getting the csv from the table is easy using django-tables 2. The issue is how can I return the csv file without having to reprocess the input data once again in another view.
If I were to use Django sessions I could pass the form data to another view, after it is validated, to regenerate the table data and then export but this seems wasteful.
Therefore my question is is there a way to export as csv after a button click?(Avoiding having to reprocess to re generate the table) I dont mind creating a new view but having to regenerate the table data seems wasteful.
Thanks,
You have at least two options here:
-
Save the original data in your database, such that all views can retrieve that data.
-
Create your button to run some JavaScript in the browser to export the data. (If you go this route, I’d suggest “pre-generating” the data as a JSON object within your response so that the JavaScript doesn’t have to try and generate the csv from the data in the html.)
Why do you think this might be a problem? (99+% of the time it’s not.)
Thanks for your reply I have a question:
- If regenerating the results is not a big issue how would you manage passing the user data from one view to another(the form data after it is validated)?(Is the correct way using Django sessions?)
You’re not “passing data” from one view to another.
If you want to persist data between views, you can either store it in the database or in the session (which is frequently stored in the database anyway…)
Thank you again for your prompt reply. How would you go about these two approaches?
I guess that the second one uses the Django sessions but in the case of saving this data to the database how would this be done?
You would define a model for that data. Your first view would create instances of that model (probably one instance per line of the table), and then the second view would query that model to retrieve those lines.