Django框架中复选框数据的查询、回显与AJAX提交实现
本文详解Django开发中复选框的完整处理流程。涵盖从数据库查询所有标签、前端页面渲染,到编辑时获取选中ID并实现回显勾选的逻辑。重点解析如何通过JavaScript将复选框数组转换为字符串,利用AJAX进行POST提交,并在后端通过getlist正确接收多值数据,确保前后端数据交互准确无误。
本文详细介绍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'是不被处理的请求方式')
2、前端HTML页面展示逻辑
<div class="form-group">
<label class="col-sm-2 control-label">标签</label>
<div class="col-sm-9">
{% for tag in tags %}
<label class="checkbox-inline">
<input value="{{ tag.id }}" type="checkbox" name="tags"/>{{ tag.name }}
</label>
{% endfor %}
</div>
</div>
编辑页面复选框回显逻辑
3、进入编辑页面时,需先获取所有复选框列表以及当前已选中的ID集合
# 编辑博客
def edit(request, blog_id):
tags = TagModel.objects.all()
# 利用正向查找关于本博客选择的tag
blogModel = BlogModel.objects.filter(id=blog_id).first()
# 获取全部的tag
check_tag = blogModel.tag.all()
# 获取选中的id
check_id = [int(x.id) for x in check_tag]
print check_id
return render(request, 'books_edit.html', {'tags': tags, 'check_id': check_id})
4、遍历判断逻辑:若某选项ID存在于选中列表中,则自动勾选该复选框
<div class="form-group">
<label class="col-sm-2 control-label">标签</label>
<div class="col-sm-9">
{% for tag in tags %}
{% if tag.id in check_id %}
<label class="checkbox-inline">
<input value="{{ tag.id }}" type="checkbox" name="tags" checked="checked"/>{{ tag.name }}
</label>
{% else %}
<label class="checkbox-inline">
<input value="{{ tag.id }}" type="checkbox" name="tags"/>{{ tag.name }}
</label>
{% endif %}
{% endfor %}
</div>
</div>
AJAX提交与后端数据接收
二、使用AJAX提交时需将复选框数据转换为字符串格式
1、前端JavaScript提交代码
$('#btn').on('click', function (e) {
// 设置空数组
var hobby = [];
$('#hobby-group').find('input[type=checkbox]').each(function () {
if ($(this).prop("checked")) {
var hobbyId = $(this).val();
hobby.push(hobbyId);
}
})
console.log(hobby);
$.ajax({
'url': '/ajaxpost/',
'method': 'post',
'data': {
'username': $('.username').val(),
'hobby': hobby
},
'traditional': true,
'beforeSend': function (xhr, settings) {
var csrftoken = ajaxpost.getCookie('csrftoken');
//2.在header当中设置csrf_token的值
xhr.setRequestHeader('X-CSRFToken', csrftoken);
},
'success': function (data) {
console.log(data);
}
})
})
2、后端Django视图处理代码
@require_http_methods(['POST'])
def ajaxpost(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username', None)
# 获取复选框的值
hobby = request.POST.getlist('hobby')
print '*' * 100
print hobby
print '*' * 100
return HttpResponse(u'成功')
else:
return HttpResponse(u'验证错误')
希望上述关于Django框架中Python程序设计的复选框处理技巧,能对各位开发工作有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













