I built a view which allow user input some information and inserted that information as a new record into my database with Pyramid framework. The code is like this:
def orderplace_view(request):
user = User.get(authenticated_userid(request))
cart = Cart.get_by_user(user)
if cart.itemtypes == None: # cat is empty
request.session.flash(u'Empty cart')
raise HTTPFound(location = request.route_url('cart'))
placeorderform = PlaceOrderForm(request.POST)
placeorderform.address.query = UserAddress.query_by_user(user)
if request.POST and placeorderform.validate():
# create order
order = Order()
order.address = placeorderform.address.data
# fill order with other attributes...
user.orders.append(order)
# IMPORTANT LINE!!!
raise HTTPFound(location = request.route_url('order_list'))
return {'user': user,
'title': 'place order',
'cart': cart,
'placeorderform': placeorderform}
Here’s the strange thing: If I commented out the “raise HTTPFound()” line, everything works fine, a new order would be inserted into database. But if I keep that line which redirect user to Order List page, the order won’t be inserted! Why this happened?
If Pyramid transaction middleware is in use, it will abort the containing transaction when view function raises an exception: http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/#transaction-usage
Commit explicitly with
transaction.commit(), or, better yet, returnHTTPFoundinstead of raising it.