1

Currently, my application is to select the stock data, then analyzing it by using another python script and output the result(in JSON format). Now I would like to add a button to output the result(w_df_split) to CSV, then when the user clicks the button and download the csv file. But I am stuck in how to return the output CSV function in this view.

views.py:

def efficient_frontier_select(request):
    user_holding = Position.objects.filter(created_by = request.user)
    selected_stock = None
    
    w_df_split = None
   
    if request.method == 'POST':
        selected_stock = request.POST.getlist('stock_symbol')
        ta, tb, tc = ef.combination_frontier(selected_stock)
        fy_df, fx_df, w_df, fxfy_df, ef_df = ef.transform_frontier_todf(ta,tb,tc, selected_stock)
        w_df_split = json.loads(ef.json_format_split(w_df))

    context = {
        'w_df_split' : w_df_split,  
    }
    
    return render(request, 'portfolio/efficient_frontier.html', context)
Zii Lam
  • 11
  • 2
  • check this out: [https://stackoverflow.com/questions/3345336/save-results-to-csv-file-with-python](https://stackoverflow.com/questions/3345336/save-results-to-csv-file-with-python) – Nick Ven Apr 12 '21 at 16:34
  • Does this answer your question? [Save results to csv file with Python](https://stackoverflow.com/questions/3345336/save-results-to-csv-file-with-python) – Nick Ven Apr 12 '21 at 16:36
  • I edited.. sorry for the not clear question.. Now I would like to add a button to output the result(w_df_split) to CSV, then when the user clicks the button and download the csv file. But I am stuck in how to return the output CSV function in this view. – Zii Lam Apr 12 '21 at 16:39

2 Answers2

0

Asumming df is a dataframe, you you could use pandas's df.to_csv(). Like that: csv_data = w_df.to_csv(). You could do the same to json with w_df.to_json()

jvrn3
  • 600
  • 1
  • 5
  • 18
  • I try this, but df.to_csv() is to output the string in Django when I am applying this to button. – Zii Lam Apr 12 '21 at 17:15
0

Just an update! Django view design - export CSV from user-generated content

This works by setting the hidden input field to store the JSON data.

Zii Lam
  • 11
  • 2