我如何使用复选框传递值给视图django?



我试图使用复选框从用户获得选定的选项,并将其传递给视图,以使用该值创建一个新的实例,但是,我发现很难获得输入值,因为它一直显示None,我尝试使用标签内的输入名称获取值。

模板

<form action='/print_from_button' method='GET'>
<table id="id_list_table" class="table table-condensed">
<thead>
<tr>
<th id="input">Input</th>
</tr>
</thead>
<tbody id="fbody">
{%for m in matches%}
<tr>
<td><br>{{ m.match }}</br> ({{m.datespent}})</td>
<td>
<input type="checkbox" name="inputs" class="checkvalue" value={{m.match}} />
</td>
</tr>
{%endfor%}
</tbody>
</table>
<input type="text" name="checkval" id="checkallvalues" size="50">
<button type='submit'> Confirm </button>
</form>

urls . py

from django.urls import path
from . import views
from .views import matchpaymentsoverview
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('matchpayment/overview/',views.matchpaymentsoverview, name="matchpaymentsoverview"),
path('print_from_button', views.print_from_button)    
]

views.py

def print_from_button(request):
print("button clicked")
if request.POST.get('checkval'):
vi = request.POST.get('checkval')
print(vi)
vi1 = request.GET.get('checkval')
print(vi1)
list_of_input_ids=request.POST.getlist('inputs')
print(list_of_input_ids)
return HttpResponse("""<html><script>window.location.replace('/');</script></html>""")

当我打印上面的名称标签时,我一直没有得到任何东西,我需要按钮来触发函数吗?或者我可以创建一个函数并使用get来获取值。希望这说得通。由于

你可以这样设置HTML复选框:

<p>Choose your monster's features:</p>
<div>
<input type="checkbox" id="scales" name="scales"
checked>
<label for="scales">Scales</label>
</div>
<div>
<input type="checkbox" id="horns" name="horns">
<label for="horns">Horns</label>
</div>

这就是一个输入字段,类型为复选框. 你也可以使用Django的输入字段:

https://docs.djangoproject.com/en/3.2/ref/forms/

这是我的源代码:

https://developer.mozilla.org/de/docs/Web/HTML/Element/input/checkbox

如果你对html, javascript或css有任何疑问,Mozialla通常是一个不错的选择

最新更新