本文實例講述了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程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。