前端页面
名字叫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,
})
URL连接
from django.urls import path
from .views import CheckBoxView
urlpatterns = [
path("check_box/", CheckBoxView.as_view())
]
展示示例
访问:http://127.0.0.1:8000/check_box/
可以看到:
选中几个数之后,点击提交:
然后可以看到结果: