Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant create CSV file with django although already copaste from the documentation

Tags:

python

django

So i try to follow the documentation from django itself how to create CSV file, i copaste the code but it didnt work , it should be the browser download the somefilename.csv when it success , is there anything wrong? or do i need to set something in settings.py? Here's the code (HTML and Views)

  <div class="col-lg-12">
            <div class="form-panel">
              <form action="#" class="form-horizontal style-form" id="form1">
                <div class="form-group">
                  <label class="control-label col-md-3">Campaign Name</label>
                   <div class="col-md-3 col-xs-11">
                    <input id = "campaign_name" type="text" class="form-control form-width">
                  </div>
                </div>
                <div class="form-group">
                 <label class="control-label col-md-3">Campaign Type</label>
                  <div class="col-md-3 col-xs-11">
                   <div class="btn-group">
                     <select id = "campaigntype"  style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">   
                            <option disabled selected value>-- Choose --</option>                      
                            <!-- <li><a href="#"></a></li> -->                            
                            <option value = "Informasi" >Informasi</option>                                                  
                            <option value = "Promosi" >Promosi</option>                                                  
                            <!-- <li><a href="#">Dropdown link</a></li> -->                            
                            </select>    
                   </div>
                  </div>
                </div>
                <div class="form-group">
                 <label class="control-label col-md-3">Segment</label>
                  <div class="col-md-3 col-xs-11">
                   <div class="btn-group">
                     <select id = "segment_list_name"  style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">   
                            <option disabled selected value>-- Choose --</option>                      
                            <!-- <li><a href="#"></a></li> -->
                            {% for x in segmentname %}
                                    <option value = "{{x}}" >{{ x }}</option>
                            {% endfor %}                          
                            <!-- <li><a href="#">Dropdown link</a></li> -->                          
                            </select>                         
                   </div>
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Channel</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                      <div class="btn-group">
                         <select id="channeltype" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">   
                            <option disabled selected value>-- Choose --</option>                      
                            <!-- <li><a href="#"></a></li> -->
                            {% for y in channel %}
                                    <option value = "{{y}}" >{{ y }}</option>
                            {% endfor %}                          
                            <!-- <li><a href="#">Dropdown link</a></li> -->                          
                            </select>       
                      </div>
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Product</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                      <div class="btn-group">
                         <select id="producttype" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">   
                            <option disabled selected value>-- Choose --</option>                      
                            <!-- <li><a href="#"></a></li> -->
                            {% for z in product %}
                                    <option value = "{{z}}" >{{ z }}</option>
                            {% endfor %}                          
                            <!-- <li><a href="#">Dropdown link</a></li> -->                            
                            </select>       
                      </div>
                    </div>
                    <br>
                    <div id="rowselect">                       
                    </div>
                  </div>
                  <div class="col-md-1">
                        <button type="button" id="countbutton" class="btn btn-info" onclick="return button()">Count</button>
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Order By</label>
                  <div class="col-md-4">
                    <div class="input-group bootstrap-timepicker">
                      <div class="btn-group">
                        <select id="columnsegment" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">                               
                        </select>      
                      </div>
                    </div>
                    <br>
                    <div id="sortby">
                        <input type="radio" name="order" value="asc" checked> Ascending
                        <input type="radio" name="order" value="desc"> Descending
                    </div>
                  </div>
                  </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Max Row</label>
                   <div class="col-md-3 col-xs-11">
                    <input id="maxrow" type="number" min="1" class="form-control form-width">
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Output File</label>
                   <div id="outputfile" class="col-md-3 col-xs-11">
                        <input type="radio" name="output" value="csv" checked> csv
                        <input type="radio" name="output" value="txt"> txt
                  </div>
                </div>
                <div class="form-group">
                 <label class="control-label col-md-3">Description</label>
                  <div class="col-md-3 col-xs-11">
                   <textarea id="desc" name="desc" class="form-control form-width" maxlength="150"></textarea>
                  </div>
                </div>
              </form>
            </div>
            <!-- /form-panel -->
          </div>
          <!-- /col-lg-12 -->
        </div>
        <button id="export" class="btn btn-theme03" onclick="return button()">Export</button>
<script>
      $(document).ready(function() {
      $("#export").click(function () {
          var urls = "{% url 'polls:export' %}";
          var camp_name = $('#campaign_name').val();        
          var seg_name = $('#segment_list_name').val();         
          var col_seg = $('#columnsegment').val();
          var sortby = $('#sortby').val();
          var maxrow = $('#maxrow').val();
          var outfile = $('#outputfile').val();          
          var path_upload = $('#flup').val();


      data = {
        'camp_name' : camp_name,                
        'seg_name' : seg_name,        
        'col_seg' : col_seg,
        'sortby' : sortby,
        'maxrow' : maxrow,
        'outfile' : outfile,        
        'path_upload' : path_upload,        
      };

        $.ajax({                     
          url: urls,
          data: data,
          success: function(data) {   
            return(data);
          },
          error: function(data)
          {

          }
        });
      });
      });
  </script>


Views.py

from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect

def export_script(request):
    campaign_name = request.GET.get('camp_name')
    segment_name = request.GET.get('seg_name')
    column_segment = request.GET.get('col_seg')
    sort_by = request.GET.get('sortby')
    max_row = request.GET.get('maxrow')
    out_file = request.GET.get('outfile')
    path_upload = request.GET.get('path_upload')

    import cx_Oracle
    dsn_tns = cx_Oracle.makedsn('', '', sid='') 
    conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)    
    c = conn.cursor() 
    curr = conn.cursor()
    c.execute("select script from arman_segment_dimension where segment_name = '"+segment_name+"'")
    c.rowfactory = makeDictFactory(c)
    columnalldata = []

    for rowDict in c:
        columnalldata.append(rowDict['SCRIPT'])

    import re

    queryscript = columnalldata[0]
    query_con = queryscript + " order by " + column_segment + sort_by + " fetch next " + max_row + " rows only"

    upr = queryscript.upper()   
    splitter = upr.split()
    comparison = splitter[-2]
    filtering = re.search('SELECT (.*) FROM', upr)   

    if comparison == "FROM":
        filtering2 = re.search('FROM (.*)', upr)
    else:
        filtering2 = re.search('FROM (.*) WHERE', upr)

    table_name = filtering2.group(1)
    result = filtering.group(1)
    data_names = result.split(',')

    import cx_Oracle
    dsn_tns = cx_Oracle.makedsn('', '', sid='') 
    conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) 
    c = conn.cursor() 
    c.execute(query_con)

    c.rowfactory = makeDictFactory(c)
    columnalldata = []

    response = HttpResponse(content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="somefile.txt"'
    writer = csv.writer(response)
    if result == "*":
        connection = conn.cursor()
        connection.execute("select column_name from all_tab_cols where table_name = '"+table_name+"'")
        connection.rowfactory = makeDictFactory(connection)
        columnallname = []

        for rowDict in connection:
            columnallname.append(rowDict['COLUMN_NAME'])            
            writer.writerow(rowDict[name] for name in columnallname)

        for row in c:
            columnalldata.append([row[data_name] for data_name in columnallname])
            writer.writerow([row[data_name] for data_name in columnallname])
    else:        
        writer.writerow(data_names)

        for row in c:
            columnalldata.append([row[data_name] for data_name in data_names]) 
            writer.writerow([row[data_name] for data_name in data_names])                                       

    return  response

enter image description here

i just want to do it automatically, dont want to press F12 then double click so the browser can download it

like image 698
trytocode Avatar asked Feb 11 '20 03:02

trytocode


People also ask

How do I read a csv file in Visual Studio code?

For any text file that is open in the built-in editor, regardless of extension, you can right-click its tab and execute the Reopen Editor With command, then select the CSV Viewer option when prompted.


1 Answers

You are not setting correctly the content_type.

response = HttpResponse(content_type='text/plain')

And also setting the filename as TXT instead of CSV

response['Content-Disposition'] = 'attachment; filename="somefile.txt"'

The following code works just fine for me.

import csv
from django.http import HttpResponse

def CsvOutputView(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    data = your_model.objects.all().values_list()
    for this_data in data:
        writer.writerow(this_data)

    return response

Hope it helps.

like image 143
Francisco Ghelfi Avatar answered Oct 11 '22 18:10

Francisco Ghelfi