/:'QueryDict'和'float'不支持的操作数类型

时间:2013-04-12 13:37:04

标签: django django-forms

我收到以下错误:

unsupported operand type(s) for /: 'QueryDict' and 'float'

在'amount'中传递的值是4.90所以我很困惑为什么它不能/。

class OrderForm(forms.Form):
    amount = forms.FloatField()
    credits = forms.FloatField()

 def __init__(self, amount, *args, **kwargs):
    super(OrderForm, self).__init__(*args, **kwargs)
    self.fields['amount'].widget = forms.HiddenInput()
    self.fields['amount'].initial = amount
    total_credits = credit_total(amount)

    self.fields['credits'].widget = forms.HiddenInput()
    self.fields['credits'].initial = total_credits

我曾尝试使用float()但这不起作用。

cal函数

def credit_total(amount):

    credit_total = amount / 0.049
    return credit_total

我必须注意,在我第一次加载表单时,它可以工作......

 cost_amount = float(request.POST['amount'])
        form = OrderForm(amount=cost_amount)

然而,在帖子上,当我再次填充表格时,它不会....

if request.method == 'POST':
        form = OrderForm(request.POST)

但是帐户现在在POST请求中。

也许我需要这样做......

  def __init__(self, amount=None, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)

        if amount is none then make amount from args = ammount????

2 个答案:

答案 0 :(得分:1)

问题出在def __init__(self, amount, *args, **kwargs):。这不是在很多地方编写的,但是你不能通过名称将自己的参数添加到表单的__init__方法的参数列表中。

不要担心,一切都不会丢失。你想要的是这个:

def __init__(self, *args, **kwargs):
    amount = kwargs.pop('amount', None)
    super(OrderForm, self).__init__(*args, **kwargs)
    self.fields['amount'].widget = forms.HiddenInput()
    self.fields['amount'].initial = amount
    total_credits = credit_total(amount)

    self.fields['credits'].widget = forms.HiddenInput()
    self.fields['credits'].initial = total_credits

唯一的问题是,在实例化表单时需要小心。你需要提供一个名为arg的金额,我看你已经在做了。

原因是当您调用form = OrderForm(request.POST)时,您将POST QueryDict分配给amount arg。

答案 1 :(得分:1)

当您从request.POST填充表单时,您将整个request.POST作为amount传递,这是表单__init__的第一个参数。您希望将其作为data传递。您仍然必须将某些内容传递给amount

if request.method == 'POST':
    amount = float(request.POST.get('amount', 0))
    OrderForm(amount=amount, data=request.POST)

我认为最好在表格之外计算初始数据:

class OrderForm(forms.Form):
    amount = forms.FloatField(widget=forms.HiddenInput)
    credits = forms.FloatField(widget=forms.HiddenInput)

...

form = OrderForm(initial={'amount': amount, 'credits': credit_total(amount)})

...

if request.method == 'POST':
     form = OrderForm(data=request.POST)

当方法不是POST时,如何从request.POST获得金额?我希望你发表了你的整个观点。