名字叫get_checkbox.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
<input type="checkbox" name="my_value" value="1"> 值為1
<input type="checkbox" name="my_value" value="2"> 值為2
<input type="checkbox" name="my_value" value="3"> 值為3
<input type="checkbox" name="my_value" value="4"> 值為4
<input type="checkbox" name="my_value" value="5"> 值為5
<input type="submit">
{% csrf_token %}
</form>
{
{ select_value }}
</body>
</html>
from django.views.generic import View
class CheckBoxView(View):
def get(self, request):
return render(request, "get_checkbox.html")
def post(self, request):
value_list = request.POST.getlist("my_value", [])
return render(request, "get_checkbox.html", {
"select_value": value_list,
})
from django.urls import path
from .views import CheckBoxView
urlpatterns = [
path("check_box/", CheckBoxView.as_view())
]
訪問:http://127.0.0.1:8000/check_box/
可以看到:
選中幾個數之後,點擊提交:
然後可以看到結果: