Django开发中复选框用法示例

yipeiwu_com5年前Python基础

本文实例讲述了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、前端页面

<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、判断如果选中的就勾选

<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提交的时候注意要把复选框转换字符串提交

1、前端代码

$('#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、后端代码

@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程序设计有所帮助。

相关文章

pandas 使用apply同时处理两列数据的方法

多的不说,看了代码就懂了! df = pd.DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3,...

PYTHON基础-时间日期处理小结

步骤: 1. 掌握几种对象及其关系 2. 了解每类对象的基本操作方法 3. 通过转化关系转化 涉及对象 1. datetime >>> import datetim...

Win下PyInstaller 安装和使用教程

Win下PyInstaller 安装和使用教程

简介: PyInstaller可以将Python源代码发布成Win/MacOS等系统中的可执行文件。对开发者而言隐藏了源码实现,保护了知识产权。对使用者而言不用装环境,傻瓜式的双击就可以...

Mac下Anaconda的安装和使用教程

前提 在刚接触python的时候我想大多数人都会面临一个问题,我到底是选择2还是3,因为现在网上好多的资料和视频项目中都还是用的2,我们跟着学习的时候肯定也是首先从2开始学的,但是我们心...

Python函数可变参数定义及其参数传递方式实例详解

本文实例讲述了Python函数可变参数定义及其参数传递方式。分享给大家供大家参考。具体分析如下: python中 函数不定参数的定义形式如下: 1、func(*args) 传入的参数为以...