6

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

trytocode
  • 393
  • 4
  • 22
  • Can you *describe* your problem? – JPG Feb 11 '20 at 03:46
  • @ArakkalAbu the problem is when i click the button in html to create csv file , it should be create a csv file that the browser download it(like when we want to download file or something) , but it didnt give any response , when i click it , and i already check in the command prompt and it print the word "Halo" so it means , it should be work – trytocode Feb 11 '20 at 03:49
  • Your code is working fine for me. Please check with brower download setting. Which browser are you using? – Epsi Vennila Feb 11 '20 at 04:48
  • @Vennila , i try with chrome and edge and it s the same , hmm i really confuse right now – trytocode Feb 11 '20 at 06:36
  • Is there any errors that you get? or any response codes? – Pradeep Feb 11 '20 at 07:43
  • @Pradeep No error , i put alert when it success and it says success export data , but nothing happen hehe – trytocode Feb 11 '20 at 08:27
  • @Pradeep No error , i put alert when it success and it says success export data , but nothing happen hehe – trytocode Feb 11 '20 at 08:27
  • Have you imported HttpResponse in your code @trytocode – Epsi Vennila Feb 11 '20 at 08:55
  • Already , from django.http import HttpResponse @Vennila M – trytocode Feb 11 '20 at 09:00
  • 1
    It seems your problem is where you are sending the request using `ajax`. What is returning the `data` supposed to do? Check out this thread, I think you will find your answer. https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – nima Feb 18 '20 at 08:08
  • I have a solution that doesn't use Django, but works from the front end using Javascript. It isn't exactly for the same problem but I had used a code to export an HTML table to a CSV file from the DOM itself. – Anshuman Kumar Feb 24 '20 at 13:08

1 Answers1

5

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.

Francisco Ghelfi
  • 872
  • 1
  • 11
  • 34