0

我收到以下错误:

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() 但这不起作用。

校准函数

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????
4

2 回答 2

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 分配给amountarg。

于 2013-04-12T13:58:01.440 回答
1

当您从 填充表单时request.POST,您将传递整个request.POSTas 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)

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

于 2013-04-12T13:58:48.863 回答