【问题标题】:submit a form with post based on conditions in django根据 django 中的条件提交带有帖子的表单
【发布时间】:2015-07-24 06:38:12
【问题描述】:

我的 forms.py 中有以下表单:

class PaymentMethodForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(PaymentMethodForm, self).__init__(*args, **kwargs)
        payment_choices = ['online payment', 'payment at delivery']
        self.payment_method_choice = forms.ChoiceField(choices=payment_choices, widget=forms.RadioSelect)

现在这是在线商店中您选择付款方式的页面。如您所见,我们有两种方法,一种是交货时付款,这意味着网站不应该有任何付款,另一种是在线支付。在用户选择在线支付的情况下,我应该通过帖子提交一个看起来像这样的表单,然后将用户重定向到操作 url:

<form id="Form2" method="post" Action="https://somepaymentsite.com/gateway.aspx"
>
<input type="hidden" name="invoiceNumber" value="<%= invoiceNumber %>"
/>
<input type="hidden" name="invoiceDate" value="<%= invoiceDate %>" />
<input type="hidden" name="amount" value="<%= amount %>" />
<input type="hidden" name="terminalCode" value="<%= terminalCode %>" />
<input type="hidden" name="merchantCode" value="<%= merchantCode %>" />
<input type="hidden" name="redirectAddress" value="<%= redirectAddress
%>" />
<input type="hidden" name="timeStamp" value="<%= timeStamp %>" />
<input type="hidden" name="action" value="<%= action %>" />
<input type="hidden" name="sign" value="<%= sign %>" />
<input type="submit" name="submit" value="‫"continue‬ />
</form>

现在我这样做的想法是,我将获得用户选择的单选按钮选项,而不是将这些 html 内容放在我的模板(html 文件)中,如果他们选择在线支付,我将提交一个表单像上面我的 views.py 。问题是,我不知道该怎么做。我用谷歌搜索了一些东西,但我没有找到任何关于如何在 django 的视图中发布表单的好处。有谁能够帮我?谢谢。

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    如果我理解正确,“从视图提交表单”与使用数据 {'invoiceNumber': 12345, 'invoiceDate': '10.10.2015', ...}https://somepaymentsite.com/gateway.aspx 发送 POST 请求相同。在这种情况下,您可以使用requests 库。

    # in view
    # if online payment then
    r = request.post('https://somepaymentsite.com/gateway.aspx', data=payload)
    # processing r (error handling or something else)
    

    其中payload 是您以某种方式构建的字典{'invoiceNumber': 12345, 'invoiceDate': '10.10.2015', ...}

    【讨论】:

    • 这是一个很棒的答案先生或女士!但我可能忘记澄清我的问题,我现在会这样做,做这篇文章也会重定向用户吗?因为我还需要在发布后将用户重定向到支付网站。
    • 返回 HttpResponseRedirect()?
    • 不,我想同时发布数据和重定向,否则我不确定先发布和重定向是否有效。会这样吗?如果没有,我可以同时做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2014-11-11
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多