Code


Version 3 (modified by anonymous, 8 years ago) (diff)

notification of amended and improved fly-to-basket script

On dhtmlgoodies.com we can find a very impressing shopping cart which uses DHTML and AJAX, good old “Web 2.0” effects - script documentation and download and demo.

Note: using AJAX in django doesn't really require any widgets, plugins or helpers.

The script uses PHP so our mission is to teach it Django and try use a database to store the data.

  • Download the ZIP file with the script and extract it to an empty folder
  • Create a django project called “shop” and application called “basket” (or use other):
django-admin.py startproject shop
python manage.py startapp basket
  • Create folders: templates and media (in the project main folder)
  • Move fly-to-basket.html to templates folder
  • Move js and images to media folder (from the basket script)
  • Edit fly-to-basket.html and add /site_media/ to every call for images and JS files, like:
<script type="text/javascript" src="/site_media/js/ajax.js"></script>
<script type="text/javascript" src="/site_media/js/fly-to-basket.js"></script>
  • the same in media/js/fly-to-basket.js:
    img.src = 'site_media/images/remove.gif';
    
  • Edit urls.py and change the content of the file to:
    from django.conf.urls.defaults import *
    
    urlpatterns = patterns('',
    (r'^/?$', 'shop.basket.views.show_basket'),
    (r'^site_media/(.*)$', 'django.views.static.serve', {'document_root': '/path/to/folder/media'}),
    )
    

Enter a full path to the media folder (we use this to get the static files under development server).

No we make the show_basket view function for the main URL. Edit views.py

from django.shortcuts import render_to_response

def show_basket(request):
	return render_to_response('fly-to-basket.html')
  • Start the development server
    python manage.py runserver 8080
    

When you open in a browser the main URL - http://localhost:8080/ you should the page and a working script (visual effects)

Now we need to teach it django. Edit media/js/fly-to-basket.js and change the php filenames of add/remove to:

var url_addProductToBasket = 'addProduct/';
var url_removeProductFromBasket = 'removeProduct/';
  • add to urls.py:
    (r'^addProduct/$', 'shop.basket.views.addProduct'),
    (r'^removeProduct/$', 'shop.basket.views.removeProduct'),
    
  • add to views.py:
    def addProduct(request):
    	print request.GET['productId']
    def removeProduct(request):
    	print request.GET['productIdToRemove']
    

Refresh the page and add few products to basket and the see the output of the terminal which runs your development server. You should see the product Ids. We got them so we nearly home.

To see a list of products in the basket (right panel of the site) the addProduct must return a page with a string:

product ID|||product name|||price

removeProduct should return “OK”.

Now let us try to connect it with a database. We need a table that will contain products in the basket. In very simple example we need one table with the product_id column:

  • In settings.py add to INSTALLED_APPS the basket application:
    'shop.basket'
    
  • Edit basket/models/py:
    from django.db import models
    
    class Basket(models.Model):
        product_id = models.IntegerField()
    
  • Create tables
    python manage.py syncdb
    
  • Update view.py
    from django.shortcuts import render_to_response
    from django.http import HttpResponse
    from shop.basket.models import *
    
    # taken from the template/example
    products = {
    '1': ['Callendar', '50'],
    '2': ['Shopping module', '250'],
    '3': ['Menu package', '35'],
    '4': ['Ajax package', '50'],
    '5': ['Week planner', '60'],
    '6': ['Forum package', '150'],
    '7': ['HTML editor', '150'],
    '8': ['CSS creator', '125']
    }
    
    def show_basket(request):
    	return render_to_response('fly-to-basket.html')
    def addProduct(request):
    	product = Basket(product_id = int(request.GET['productId']))
    	product.save()
    	res = products[request.GET['productId']]
    	return render_to_response('add.html', {'result': res, 'id': request.GET['productId']})
    def removeProduct(request):
    	# whe have only product id so we need to delete one entry that has it.
    	Basket.objects.filter(product_id__exact=int(request.GET['productIdToRemove']))[0].delete()
    	# JavaScript wants this
    	return HttpResponse("OK")
    
  • Create template add.html with:
    {{ id }}|||{{ result.0 }}|||{{ result.1 }}
    

Now the JS/Ajax products-in-basket on the right will work and adding a product to the basket will be also saved in the database. Deleting a product will also delete it from the database.

Note that this example is very limited – when you refresh the page the products in the basket list is gone – we don't get it from the database. Also it we want to make a shop we should make a table for products and add “user ID” field to the basket table so it can be used by many users (and many other features...)

19 Sep 2006 - note from user: I have modified the script on my side to be entirely database-driven. In other words, the fly-to-basket.html as well as the array in views.py are fed from a mysql table. Also, the database now carries product name and price - redundant in practice, but good for my learning purposes. I am running this on WinXP on a virtual domain I called django.com. If anyone is interested in the scripts or setup help, please get in touch with me via www.helmar.org, where I will post it. Better still, find me using 'django' under www.qunu.com --Helmar

Attachments (1)

  • shop.zip (26.2 KB) - added by caputo 5 years ago. I just change "request.GET" to "request.POST" into the view

Download all attachments as: .zip