Django对象函数在views.py中不起作用

时间:2015-04-09 02:25:45

标签: python django

所以我有一个带有函数buy()的对象User,它在shell中运行得很好。我遇到的问题是当我尝试在views.py中使用它时。

def makeOffer(request, commodity_id):
    commodity = get_object_or_404(Commodity, pk=commodity_id)
    context = {}
    buysell = "no"
    #For some reason Try and Except must work this way....?
    try:
        user = User.objects.get(name=request.GET['user'])
        buysell = request.GET['buysell']
        shares = request.GET['shares']
        price = request.GET['price']
        if buysell == "buy": user.buy(commodity,shares,price)
        elif buysell == "sell": user.ask(commodity,shares,price)
        return HttpResponse('/trading/orders/%s/ %s %s x %s'%(commodity.id,buysell,shares,price))
    except Exception as e:
        pass
    return render(request, 'trading/makeoffer.html')

我只是使用HttpResponse进行调试,看看我是否得到了GET变量。现在if和elif语句工作,我尝试回显关键字,它是user.buy()触发Try语句来运行异常,从而带我回到表单。如果您想知道代码是什么,那就是模拟市场交易。 如果你想看看它在shell中是如何工作的:

>>> from trading.models import*
>>> justin,jack = User.objects.all();denarii,gold = Commodity.objects.all()
>>> justin.holding(gold)
<Holding: Justin holds 0 x Gold>
>>> jack.holding(denarii)
<Holding: Jack holds 0 x Denarii>
>>> justin.holding(denarii)
<Holding: Justin holds 1600 x Denarii>
>>> jack.holding(gold)
<Holding: Jack holds 300 x Gold>
>>> justin.buy(gold, 200, 8) #This makes a buy order for 200 at 8 denarii a piece
>>> gold.offersList()
[<Offer: Buy: Gold: user: Justin --> 200 x 8>]
>>> jack.ask(gold, 300, 8) #This makes a ask order for 300 at 8 denarii a piece
>>> gold.offersList() #Leftovers of all offers
[<Offer: Sell: Gold: user: Jack --> 100 x 8>]
>>> gold.ordersList() #All orders that can get through are done
[<Order: Justin --> Jack: Gold: 200 x 8]

我不得不费力地手工编写代码,因为我的虚拟框不允许我复制和粘贴,但基本上shell的其他提示只显示了对象,denarii和其他东西都是由对象自动完成的

1 个答案:

答案 0 :(得分:0)

Oozemaster解决了它,我正在传递一个str,我应该通过一个int。