Django Integrated jquery
First, static resources are usually placed in the static folder:
static/ css/ djquery.css samples/ hello.css js/ jquery-1.7.1.min.js samples/ Hello.js
Where CSS and JS are in accordance with the application name (here is samples) partition folder, if more files, you can also scratch the molecular folder.
Django usually uses templates to represent HTML, and we usually use inherited templates, so we need to put common elements, such as global CSS, the introduction of Jquery.js, into the base template, and place the elements of specific pages into a specific template. This involves the question of how to nest. Look at the following example:
Base.html
{% block title%} title {% Endblock%}
{% block styles%}
{% Endblock%} {% block content%} content {% Endblock%} {% block scripts%}
{% Endblock%}
Samples/hello.html
{% extends "base.html"%} {% block title%}hello, djquery! {% Endblock%} {% Block styles%} {% Endblock%} {% block content%}{% Endblock%} {% block scripts%} {% Endblock%}
Hello, djquery!.
With the "framework" above, we can easily verify our ideas, such as this "Hello djquery". You only need to configure it in urls.py:
Copy the Code code as follows:
(R ' hello/$ ', ' django.views.generic.simple.direct_to_template ', {' template ': ' samples/hello.html '}),
Where direct_to_template is a common view provided by Django.
Ajax implementation Examples
Let's look at a shopping cart example. Let's say we now have a restful API in JSON format that allows you to do this: to avoid switching back and forth between the product list and the shopping cart, you need to display the shopping cart in the Product List screen and update the shopping cart display with Ajax without refreshing the interface. Take advantage of our jquery integration above in Django.
1. Embed the shopping Cart interface
To implement the product catalog interface as shown in the embedded shopping cart, we need to do two things:
(1) Modify the template:
Depot/templates/depotapp/store.html:
{% extends "base.html"%} {% block title%} Product catalog {% Endblock%} {% block pagename%} product catalog {% Endblock%} {% block content%} {% fo R item in products%}{{Item.title}}
{{Item.description}}
¥{{item.price|floatformat: "2"}}
Add to cart {% ENDFOR%}
My Shopping Cart
{% for item in cart.items%}
| {{Item.quantity}}x |
{{Item.product.title}} |
¥{% widthratio item.quantity 1 item.unit_price%} |
{% ENDFOR%}
|
Total: |
¥{{cart.total_price|floatformat: "2"}} |
Clear Checkout
{% Endblock%}
(2) Add a line to the Store_view view function in depotapp/views.py:
Cart = Request.session.get ("cart", None)
You can show the interface as above.
2. Writing JavaScript for Ajax
Now let's request a background service through Ajax. Of course preferred to implement background services. Regarding the "Add to Cart", the service we need is defined as:
Url:http://localhost:8000/depotapp/api/cart/items/post
Post data: Product = product_id
Process: Add product to cart according to product_id
Back to: All items in the shopping cart
The definition of this API does not seem to be restful, but it is not to be managed. Implementing this service requires adding a method to the RESTful Web service (the Restforcart class in depotapp/views.py):
Def post (self, request, *args, **kwargs):p rint 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
The service interface can be tested with Http://localhost:8000/depotapp/API/cart/items/post (using Firebug debugging is a very handy way):
As you can see, our interface definition is not completely restful, and in the generated form we just need to select product, without the addition of two additional form items, after post to see the new additions from the previously implemented shopping cart interface.
The service interface test passes, and it can be called through Ajax in the interface. jquery has a lot of support for Ajax, and in order to facilitate the use of jquery's selector, HTML should be transformed first. In the depot/templates/depotapp/store.html implemented above, the part of the iteration product is changed to look like this:
{% for item in products%}{{Item.title}}
{{Item.description}}
¥{{item.price|floatformat: "2"}}
Add to cart {% ENDFOR%}
The main change is the "Add to Cart" tab, add the ProductID attribute, and change the href to "#". So that we can easily add events to it:
store.html on ready$ (' A.btn[productid] '). Bind ("click", Function () {Alert ($ (this). attr ("ProductID"));});
This code implements the function: for all tags, if the class includes "BTN", and the element with the "ProductID" attribute, add the click event, the popup dialog box displays its "ProductID" property value.
Open the Product list interface to test, you can correctly eject the product ID, and then you can write the processing of Ajax. Here we use the Jquery.post () method, Jquery.post () is a simplified notation for 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 popup dialog box is the return value of the API interface defined earlier, which is the list of entries in the existing shopping cart.
Finally, you change the display of the shopping cart on the interface based on the returned data. The HTML is also modified for convenience. The complete depot/templates/depotapp/store.html is as follows:
{% extends "base.html"%} {% block title%} Product Catalog {% endblock%}{% block pagename%} product catalog {% Endblock%}{% block content%}{% for item in products%}{{Item.title}}
{{Item.description}}
¥{{item.price|floatformat: "2"}}
Add to cart {% ENDFOR%}
My Shopping Cart
Total:
¥{{cart.total_price|floatformat: "2"} Empty settlement
{% endblock%}{% block js%}
{% Endblock%}{% block On_ready%}//store.html on Ready$.getjson ('/depotapp/api/cart/items/', Refreshcart); $ (' a.btn[ ProductID]. Bind ("click", Function () {var product_id=$ (this). attr ("ProductID");//alert (product_id); $.post ("/ Depotapp/api/cart/items/post ", {Product:product_id},refreshcart);}); {% Endblock%}
Defines a refreshcart function that "redraws" the shopping Cart interface according to the parameters. In the $ (document). Ready section, first call the implemented API to display the shopping cart, so that we can remove the original implementation of the "shopping cart" in the template, and change the way to JavaScript.
Then add a click event for each "Add to Cart" button, invoke the interface implemented at the beginning of this section, and call the Refreshcart function to redraw the cart based on the most recent entry data returned.
In the above template, the JavaScript section is divided into two block:{% block js%} for embedding specific pages (relative to the parent template) of the JS function; {% block On_ready%} is used to embed the $ (document) of a specific page. Ready processing. By combining the blocks defined in base.html, you can make the specific pages and template pages that are grouped together conform to unobtrusive JavaScript. This should be the best practice for django+jquery to implement Ajax.