Hi all,
I am a newbie in web design. I followed the instructions in the video
"Build an online store with web2py" at http://vimeo.com/20768689
I don't know why I can not add any items to cart. Please help me to show
where I was wrong. Thank you a lot.
~ Ton Dong
The code:
- Model: hmw.py
# coding: utf8
db.define_table(
'product',
Field('nameproduct', 'string',notnull=True,unique=True, length=30),
Field('price', 'double'),
Field('desciption', 'text'),
Field('image','upload'),
Field('sortable','integer'),
auth.signature,
format = '%(nameproduct)s',
singular = 'product',
plural = 'products',
)
db.define_table(
'sale',
Field('invoice'),
Field('creditcard'),
Field('buyer',db.auth_user),
Field('product',db.product),
Field('quantity','integer'),
Field('price', 'double'),
Field('shipped', 'boolean', default=False),
auth.signature,
)
- Conntroller:
def index():
session.cart = session.cart
products = db(db.product).select(orderby=db.product.sortable)
return locals()
def user():
return dict(form=auth())
def download():
return response.download(request,db)
def call():
session.forget()
return service()
@auth.requires_login()
def cart():
return dict(cart=session.cart)
@auth.requires_login()
def pay():
import uuid
invoice = str(uuid.uuid4())
total = sum(db.product(id).price*qty for id, qty in
session.cart.items())
form = SQLFORM.factory(Field('creditcard',default='000000000000000'),
Field('expiration', default='12/2015'),
Field('cvv', default='111'),
Field('total','double',default=total,writable=False))
if form.accepts(request,session):
if process(form.vars.creditcard, form.vars.expiration, total,
form.vars.cvv,0.0,'invoice'):
for key, value in sesssion.cart.items():
db.sale.insert(invoice=invoice,
buyer=auth.user.id,
product=key,
quantity = value,
price = db.product(key).price,
creditcard = form.vars.creditcard)
session.cart.clear()
session.flash = 'Thanks for your order'
redirect(URL('index'))
return dict(cart=session.cart, form=form)
def cart_callback():
id = int(request.vars.id)
if request.vars.action == 'add':
session.cart[id] = int(session.cart.get(id,0))+1
if request.vars.action == 'sub':
session.cart[id] = max(0,session.cart.get(id,0)-1)
return str(session.cart[id])
- index.html
{{extend 'layout.html'}}
{{for p in products:}}
<div>
<h5> {{=p.nameproduct}} - ${{=p.price}} </h5>
<br>
<img width="200px"
src="{{=URL
<http://127.0.0.1:8000/examples/global/vars/URL>('download', args=p.image)}}" />
<br>
<span id='item{{=p.id}}'>{{=session
<http://127.0.0.1:8000/examples/global/vars/session>.cart.get(p.id,0)}}</span>
in cart
<button onclick='ajax('{{=URL
<http://127.0.0.1:8000/examples/global/vars/URL>('cart_callback',
vars=dict(id=p.id,action='add'))}}',[],'item{{=p.id}}')'>add </button>
</div>
{{pass}}
--