Use the Python Django framework and jQuery to implement the AJAX shopping cart page.

Source: Internet
Author: User

Use the Python Django framework and jQuery to implement the AJAX shopping cart page.

Integrate jquery in Django
First, static resources are usually put in the static Folder:

static/  css/    djquery.css    samples/      hello.css  js/    jquery-1.7.1.min.js    samples/      hello.js

Css and js both divide folders according to the application name (samples here). If there are many files, you can drag the molecular folder.

Django usually uses a template to display html, and we usually use an inherited template, so we need to share elements, such as global css, for jquery. the introduction of js is written to the base template, and the elements of the specific page are put into the specific template. This involves the issue of nesting. See the following example:
Base.html

<Html> 

Samples/hello.html

{% extends "base.html" %}{% block title %}hello, djquery! {% endblock %}{% block styles %}{% endblock %}{% block content %}<div><input type="button" id="myField" value="Click me!"/></div>{% endblock %}{% block scripts %}<script language="JavaScript" type="text/javascript" src="/static/js/djquery/hello.js"></script>{% endblock %}

Hello, Djquery!
With the above "Framework", we can easily verify our ideas, such as "Hello Djquery ". You only need to configure in urls. py:

Copy codeThe Code is as follows:

(R 'Hello/$ ', 'django. views. generic. simple. direct_to_template', {'template': 'samples/hello.html '}),

Direct_to_template is a general view provided by django.


AJAX implementation example
Let's look at an example of a shopping cart. Suppose we have a RESTful API in json format to implement this function: to avoid switching back and forth between the product list and the shopping cart, We need to display the shopping cart on the product list interface, in addition, the display content of the shopping cart is updated without refreshing the interface through ajax, and jQuery integrated in Django is used.
1. Embedded shopping cart Interface
To implement the product Directory Interface embedded in the shopping cart as shown in, we need to do two things:

(1) modify the template:

Depot/templates/depotapp/store.html:

{% Extends "base.html" % }{% block title %} product directory {% endblock % }{% block pagename %} product directory {% endblock %} {% block content %} <div class = "row"> <div class = "span10" >{% for item in products %} <div class = "row" style = "padding-top: 10 "> <div class =" span3 media-grid "> <a href =" # ">  </a> </div> <div class = "span6"> 

(2) Add a line to the store_view function in depotapp/views. py:

Cart = request. session. get ("cart", None)
The above interface is displayed.

2. Compile javascript to implement ajax
Now let's request the background service through ajax. Of course, the first choice is to implement background services. For "add to shopping cart", the services we need are defined as follows:

Url: http: // localhost: 8000/depotapp/API/cart/items/post
Post Data: product = product_id
Process: add the product to the shopping cart according to product_id.
Return: all entries in the shopping cart
The definition of this API does not seem to be so RESTful, but does not care about it for the moment. To implement this service, you need to add a method for RESTforCart class in RESTful web service (depotapp/views. py:

def post(self, request, *args, **kwargs):print request.POST['product']product = Product.objects.get(id=request.POST['product'])cart = request.session['cart']cart.add_product(product)request.session['cart'] = cartreturn request.session['cart'].items

You can test the service interface through http: // localhost: 8000/depotapp/API/cart/items/post (it is very convenient to debug using Firebug ):

As you can see, our interface definition is not completely RESTful. In the generated form, we only need to select the Product, regardless of the other two form items, after the POST, you can see the newly added product items in the previously implemented shopping cart interface.

After the service interface is tested, you can call it through ajax on the interface. Jquery provides rich support for ajax. To make it easier to use jquery selector, you must transform html. In the preceding Implementation of depot/templates/depotapp/store.html, the iterative product section is changed to the following:

{% For item in products %} <divclass = "row" style = "padding-top: 10 "> <divclass =" span3 media-grid "> <ahref =" # ">  </a> </div> <divclass = "span6"> 

The <a> label of "add to shopping cart" is changed, the productid attribute is added, and href is changed to "#". In this way, we can easily add events for it:

//store.html on ready$('a.btn[productid]').bind("click",function(){alert($(this).attr("productid"));});

This code implements the following functions: For all labels <a>, if the class includes "btn" and has the "productid" attribute, add a click event, the "productid" attribute value is displayed in the dialog box.


Open the product list interface and test it. The product ID is displayed correctly, and then you can write ajax processing. Here we use the jquery. post () method. jquery. post () is a simplified method of jquery. ajax, as follows:

//store.html on ready$('a.btn[productid]').bind("click",function(){var product_id=$(this).attr("productid");//alert(product_id);$.post("/depotapp/API/cart/items/post",{product:product_id},function(data){alert(data);});});

The data displayed in the pop-up dialog box is the returned value of the previously defined API interface, that is, the list of entries in the existing shopping cart.

Finally, you need to change the display of the shopping cart on the page based on the returned data. Html is transformed for convenience. The entire completed depot/templates/depotapp/store.html is as follows:

{% Extends "base.html" % }{% block title %} product directory {% endblock % }{% block pagename %} product directory {% endblock %} {% block content %} <divclass = "row"> <divclass = "span10"> {% for item in products %} <divclass = "row" style = "padding-top: 10 "> <divclass =" span3 media-grid "> <ahref =" # ">  </a> </div> <divclass = "span6"> 

Defines a refreshCart function, based on the parameter "re-painting" Shopping Cart interface. In the $ (document). ready section, first call the previously implemented API to display the shopping cart, so that we can remove the originally implemented "Shopping Cart" in the template and change it to javascript.

Then, add a click event for each "add to shopping cart" button, call the interfaces implemented at the beginning of this section, and call the refreshCart function to re-paint the Shopping Cart Based on the returned latest entry data.

In the template above, the javascript part is divided into two blocks: {% block js %} js functions used to embed a specific page (corresponding to the parent template; {% block on_ready %} is used to embed a specific page $ (document ). ready processing. Combined with the block defined in base.html, you can make the combined page and template page comply with Unobtrusive JavaScript. This should be the best practice for implementing ajax with Django + jquery.

 

 

Articles you may be interested in:
  • How to perform unit tests on projects in the Python Django framework
  • Serialization, request, and return in the Django REST framework of Python
  • Details about the templates settings in the Python Django framework
  • How to obtain the IP address of a user using django in Python
  • Analyze the running mode and processing process of the Python Django framework
  • How to configure mysql database in Django1.7 + python 2.78 + pycharm
  • Share the simple Performance Test Results of common python web frameworks (including django, flask, bottle, tornado)
  • Python django integrated cas Verification System
  • How to Make Sublime 3 a powerful tool for Python/Django IDE development
  • How to Use and extend manage commands in Python Django framework

Related Article

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.