python - 复选框值未在 Views.py Django 中发布
问题描述
我有代码应该在单击按钮后将选定复选框的值发布到 Views.py,但对我来说,当尝试在 views.py 中打印复选框值时,它会向我发送一个空列表
所以下面是我的代码。
视图.py
if request.method=='POST':
if 'submit' in request.POST:
user_list = request.POST.getlist('myarray')
print(user_list)
html
<form method="post">{% csrf_token %}
<!-- <div class="w-full sm:w-auto flex items-center sm:ml-auto mt-3 sm:mt-0">
<label class="form-check-label ml-0 sm:ml-2" for="show-example-5">Show Server List</label>
<input data-target="#document-editor" class="show-code form-check-switch mr-0 ml-3" type="checkbox" id="show-example-5">
</div> -->
<button id= "AnchroTagForButton" name="submit" href="">
<span></span>
<span></span>
<span></span>
<span></span>
button
</button>
</div>
<div class="p-5" id="document-editor">
<div class="preview">
<!-- <div class="alert alert-primary alert-dismissible show flex items-center mb-2" role="alert">
<i data-feather="alert-octagon" class="w-6 h-6 mr-2"></i>{{note}}<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> <i data-feather="x" class="w-4 h-4"></i> </button> </div> -->
<!-- <div data-editor="document" class="editor document-editor"> -->
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th></th>
<th>Server</th>
<th>Name</th>
<th>Labels</th>
</tr>
</thead>
<tbody>
{% for datas in customerserver %}
<tr>
<td>
<div class="form-check form-switch">
<input class="form-check-input" name="Servers" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault">
<label class="form-check-label" for="flexSwitchCheckDefault">
</form>
所以在这里我必须收集所有选中的复选框值 /(Checkbox name:Servers) ,并将其发布在 views.py 中,但是当我尝试在 views.py 中打印它时。表明 []
这是我的 AJAX 调用:
$("submit").click(function(){
var myarray = [];
$(".form-check-input:checked").each(function() {
myarray.push($(this).val()); //push each val into the array
});
$.ajax({
url: "secondtableonDashboard", //replace with you url
method: 'POST',
data: myarray,
enctype: 'application/x-www-form-urlencoded',
processData: false,
contentType: false,
success: function(data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
$('#example').hide();
$('#exampleSecond').DataTable();
},
error: function(error) {
}
});
});
解决方案
可能是您忘记添加action="/your-name/"
到您的<form>
标签中。
要解决您的问题,只需添加action="/your-name/"
到您的<form>
标签中。
这是一个例子:
<form action="/your-name/" method="post">{% csrf_token %}
.... lots of removed....
</form>
推荐阅读
- python - 如何为这个稍微复杂的方法调用添加参数?
- amazon-web-services - 在 DynamoDB 中使用 json 作为排序键/分区键值的好习惯吗?
- typescript - Typescript:为库类方法创建类型
- c - 如何在一行源代码中包含多行 C 代码(AVR-GCC)
- html - 如何在 css 和 html5 中创建曲线和圆?
- python - Python程序在写入文件时不断崩溃
- latex - 如何用乳胶超级表格修复长桌?
- android - 我正在尝试在片段中显示对话框,它在上下文中显示一些错误,相同的方法在 Activity 类中工作正常
- java - Java在单元测试中验证graphQL查询语法
- javascript - onChange 回调和钩子顺序