Example of checking box usage in Django development, django example

Source: Internet
Author: User

Example of checking box usage in Django development, django example

This example describes how to use the check box in Django development. We will share this with you for your reference. The details are as follows:

1. query check boxes for database Traversal

1. query all tags of a database using python

# Add 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 () # obtain the value of the check box, which is a selected array tags = request. POST. getlist ('tags') # cyclically traverse all selected check boxes and append them to the database using the many-to-many relationship. for tag in tags: blogModel. tag. add (tag) return HttpResponseRedirect ('book _ add') else: return HttpResponse (U' is the method of request not being processed ')

2. Front-end page

<Div class = "form-group"> <label class = "col-sm-2 control-label"> 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. Go to the editing page and obtain all the check boxes and the selected id.

# Edit blog def edit (request, blog_id): tags = TagModel. objects. all () # Use forward lookup to find the tag blogModel = BlogModel selected for this blog. objects. filter (id = blog_id ). first () # obtain all tags check_tag = blogModel. tag. all () # obtain the selected 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. Check if selected.

<Div class = "form-group"> <label class = "col-sm-2 control-label"> 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>

2. When submitting ajax requests, make sure to convert the check box to string submission.

1. Front-end code

$ ('# Btn '). on ('click', function (e) {// sets an empty array var holobby = []; $ ('# holobby-group '). find ('input [type = checkbox] '). each (function () {if ($ (this ). prop ("checked") {var hobbyId = $ (this ). val (); holobby. push (hobbyId) ;}}) console. log (holobby); $. ajax ({'url': '/ajaxpost/', 'method': 'post', 'data': {'username': $ ('. username '). val (), 'hobby': holobby}, 'traditional': true, 'beforesend': function (xhr, settings) {var csrftoken = ajaxpost. getCookie ('csrftoken'); // 2. set the csrf_token value xhr in the header. setRequestHeader ('x-CSRFToken ', csrftoken);}, 'success': function (data) {console. log (data );}})})

2. backend code

@ Require_http_methods (['post']) def ajaxpost (request): form = LoginForm (request. POST) if form. is_valid (): username = form. cleaned_data.get ('username', None) # obtain the value of the check box holobby = request. POST. getlist ('jobby') print '* 100 print hobbyprint' * 100 return HttpResponse (u'success') else: return HttpResponse (u'verification error ')

I hope this article will help you with the Python programming of the Django framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.