【问题标题】:How to open a csv file in another directory from a HTML file如何从 HTML 文件打开另一个目录中的 csv 文件
【发布时间】:2020-09-10 00:06:44
【问题描述】:

我是 Django 新手。这是我的项目结构My project structure

当我在模板文件夹中呈现 table.html 文件时,我想在 html 文件中访问输出文件夹中的 tomsim_FruitDev.csv 文件。

      ```
         <script>
         $(document).ready(function(){
          $.ajax({
           url:"output/tomsim_FruitDev.csv",
           dataType:"text",
           success:function(data)
           {
             var radiation_data = data.split(/\r?\n|\r/);
             var table_data = '<table class="table table-hover">';
          for(var count = 0; count<radiation_data.length; count++)
            {
              var cell_data = radiation_data[count].split(",");
              table_data += '<tr>';
              for(var cell_count=0; cell_count<cell_data.length; cell_count++)
              {
               if(count === 0)
               {
                table_data += '<th>'+cell_data[cell_count]+'</th>';
                }
               else
              {
               table_data += '<td>'+cell_data[cell_count]+'</td>';
              }
            }
             table_data += '</tr>';
           }
           table_data += '</table>';
           $('#datatable').html(table_data);
         }
       });
      });
      </script>

我不断收到此错误 http://localhost:8000/output/tomsim_FruitDev.csv 404(未找到)>。如何让我的应用程序查看输出文件夹。 我尝试编辑我的 settings.py 文件。我不确定在哪里添加文件的路径。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    由于 url,您收到此错误

    url:"output/tomsim_FruitDev.csv",
    

    首先您需要设置静态内容的设置。

    Managing static files

    现在您有 2 种方法来呈现您的 .CSV 文件。

    1. 将您的 .CSV 文件渲染到服务器上的模板并返回 使用 AJAX 响应。您可以使用 render_to_string 方法。

    2. 使用 AJAX 获取文件。


    如何使用第二种方法进行配置

    在settings.py中

    STATIC_ROOT  = '/static/'
    STATIC_URL = '/files/'
    
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "static"),
    
    ]
    
    MEDIA_ROOT = BASE_DIR + '/media/' # actual media directory   
    MEDIA_URL = '/media/' # URL which is display 
    

    在根 urls.py 中

    urlpatterns = [
        path('admin/', admin.site.urls),
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    

    在您的根目录中创建媒体目录。 将您的文件放在媒体文件夹中。

     url: "{{MEDIA_URL}}file.csv",
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多