首页 > 解决方案 > Ajax 未将选定项目发送到 django 视图

问题描述

我对 Django 很陌生,所以对我来说很赤裸裸。我正在处理一个 Django 视图,我在其中上传了一个数据框,并且用户有一个下拉列表来选择目标变量。我面临的问题是我无法在我的视图中获取所选项目:

def profile_upload(request):
    
    template = "profile_upload.html"
    my_class = MyClass()
    if request.method == "GET":
        prompt = {'order': 'First Page'}
        return render(request, template, prompt)
    if request.method == 'POST':
        csv_file = request.FILES['file']
        if not csv_file.name.endswith('.csv'):
            messages.error(request, 'THIS IS NOT A CSV FILE')
        df = pd.read_csv(csv_file)
        my_class.df=df
        head = df.head(n=5)
        head = head.to_html(classes='table table-striped')
        thrsh = 0.1
        dataframe_stats = utils.DfStats(df,thrsh)
        df_stats = dataframe_stats.get_df_stats()
        cat_cols,num_cols = dataframe_stats.get_type_var()
        my_class.quali_col = cat_cols
        my_class.quanti_col = num_cols
        dtype_counts = {"Variables qualitatives:  ": len(cat_cols), "Variables quantitatives:  ": len(num_cols)}
        context = {'table': head, 'stats': df_stats, "dtypes": dtype_counts, 'vars': df.columns}
        return render(request, template, context)
  
    if request.is_ajax() and request.method== "POST" :
            data = request.POST.get['mydata']
            my_class.target_var = data
            
            return HttpResponse('<h1> Page was found</h1>')

上面的视图工作正常,但最后一个 if 语句没有执行我不知道哪里出了问题。

这是下拉脚本

<label for="tar_col">

            Select target variable
                <select class="js-example-basic-single js-states form-control" id="tar_col" name="tar_col" title="tar_col" style="width: 50%">
                  {% for col in vars %}
                        <option value={{col}}>{{col}}</option>
                    {% endfor %}
                </select>

        </label>

这是ajax请求。我检查了变量 tar_col 确实有选定的项目

<script>
    $("#tar_button").click(function(e) {
        var tar_col= $("#tar_col option:selected").text();
      
        alert("You have selected " + tar_col );

        e.preventDefault();
            $.ajax({
              type: "POST",
              url: "/description/upload-csv/",
              data: {'mydata': tar_col},
              headers: { "X-CSRFToken": "{{ csrf_token }}" },
              error: function(data){
               alert(data.status); // the status code
               }

            }); // End ajax method

    });
</script>

当我检查控制台时,我收到 500 内部服务器错误。

标签: htmljquerydjangoajaxpost

解决方案


推荐阅读