本文实例讲述了Django开发中复选框用法。分享给大家供大家参考,具体如下:

一、查询数据库遍历所有的复选框
1、python查询数据库所有的tag
# 新增文章
def add(request):
if request.method == 'GET':
tags = TagModel.objects.all()
return render(request, 'books_add.html', {'tags': tags})
elif request.method == 'POST':
title = request.POST.get('title', None)
content = request.POST.get('content', None)
blogModel = BlogModel(title=title, content=content, author=AuthorModel.objects.get(id=1))
blogModel.save()
# 获取复选框的值,是一个选中的数组
tags = request.POST.getlist('tags')
# 循环遍历所有选中的复选框,利用多对多的关系追加到数据库
for tag in tags:
blogModel.tag.add(tag)
return HttpResponseRedirect('book_add')
else:
return HttpResponse(u'是不被处理的请求方式')