html - 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 内部服务器错误。
解决方案
推荐阅读
- hyperledger-fabric - Hyperledger 节点 API:注册失败
- authentication - 如何在 Jmeter 中获取 Bearer 访问令牌
- go - 如何在gorm v2中创建外键?
- python - 使用 docker 部署时 Botfront Rasa App 的问题
- mediawiki - 当 LocalSettings.php 已经存在时,如何编写初始化 MediaWiki 数据库的脚本?
- c++ - QGraphicsView 图像打印丢失线定义
- python-3.x - 即使已安装,也没有名为“google.auth”的模块-python3.9.2 no firebase
- c# - SYSTEM 进程和相应的用户进程都需要访问注册表 HKLM 部分 - StartAsCurrentUser.exe 不适用于 VS2019
- java - Maven 资源编译器:无法在 ubuntu 18.04 中复制
- r - 'powerlmm':具有 3 个治疗组的样本量计算 LMM