2017-08-17 84 views
0

我正在創建一個用戶可以上傳csv文件的站點,並且當前正在處理用戶可以在不下載文件的情況下查看文件內容的頁面。要做到這一點,我讀了CSV的意見,像這樣:使用視圖/模板在表格中顯示CSV內容

def source_details(request, source_id): 
    context_dict = {} 

    # Get a specific object 
    data_source = Source.objects.get(id=source_id) 
    context_dict['data_source'] = data_source 

    # Open the csv and print it to terminal 
    with open(MEDIA_ROOT+data_source.sample, newline='') as csvfile: 
     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
     for row in spamreader: 
      print(', '.join(row)) 


    return render(request, 'data/source-details.html', context_dict) 

正如你可以看到到目前爲止,我沒有問題打開上傳CSV文件,並將其打印到終端,但是我想在顯示它瀏覽器作爲表格。任何想法如何我可以做到這一點?謝謝。

回答

0

您可能要作出這樣一個列表的列表:

csv_preform = [[row1],[row2],[row3]] 

,然後把它傳遞給環境和循環它在模板如表:

<table> 
<tr> 
    <th>Test1</th> 
    <th>Test2</th> 
     ... 
</tr> 

{% for row in csv_preform %} 
<tr> 
    {% for sub_row in row %} 
     <td>{{sub_row}}</td> 
    {% endfor %} 
</tr> 
{% endfor %} 
</table>