Django如何获取表格的选择

时间:2019-06-22 12:02:32

标签: python django forms return-value

如何在我的 views.py 中进一步处理选择(RadioButton选择)?

目前,我正在静态地为btc(比特币)处理此货币,但我还必须使其在ltc,xmr等货币中也可以使用。 如何获得用户对此表格的选择,或者换句话说就是用户选择的所选货币?

我的 views.py

...
if request.method == "POST":
    form = CurrencyBuySelectForm(request.POST)
    currency = form['currency'].value()
    # check account balance
    if form.is_valid:
        if currency == 'btc':
            price = dollar_to_coin(item.price_usd, 'BTC')
            if request.user.acc_btc_balance < price:
                messages.error(request,'Not enough balance to buy this item')
                return redirect('item', pk=item.pk)
            else:
                # do blabla
                ...

我的 forms.py

WALLET_CHOICE = [
    ('btc', 'BTC'),
    ('xmr', 'XMR'),
    ('ltc', 'LTC'),
    ... 
]

class CurrencyBuySelectForm(forms.Form):
    currency = forms.ChoiceField(choices=WALLET_CHOICE, widget=forms.RadioSelect())
    captcha = CaptchaField()

    def __init__(self, *args, **kwargs):
        super(CurrencyBuySelectForm, self).__init__(*args, **kwargs)
        self.fields['currency'].label = mark_safe('')

    def clean(self):
        cleaned_data = super(CurrencyBuySelectForm, self).clean()
        currency = cleaned_data.get(choices=WALLET_CHOICE, widget=forms.RadioSelect())
        if not currency:
            raise forms.ValidationError('Something went wrong')

处理此处所述的操作似乎无效:

https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view

预先感谢

2 个答案:

答案 0 :(得分:0)

您必须:

if request.method == 'POST':
   form = CurrencyBuySelectForm(request.POST)
if form.is_valid()
   request.GET.get['currency']

通过request.GET.get ['currency'],您可以掌握用户选择并发布的内容。

答案 1 :(得分:0)

在我看来,您需要添加字典

my_dict= {'btc': 'BTC', 'xmr': 'XMR', 'ltc': 'LTC'}

,然后通过my_dict.keys()my_dict.values()引用它们。

类似的东西:

if currency in my_dict.keys:
    val = my_dict[currency]

price = dollar_to_coin(item.price_usd, val)

编辑: 关于 views.py currency的分配,最好在CurrencyBuySelectForm类中添加另一种方法。 clean()方法仅应清除数据,然后可以添加一个currency()方法,该方法执行currency的分配和检查并返回它。然后,您可以使用currency = form.currency()

进行引用

类似的东西:

views.py

my_dict= {'btc': 'BTC', 'xmr': 'XMR', 'ltc': 'LTC'}

if request.method == "POST":
    form = CurrencyBuySelectForm(request.POST)
    currency = form.currency()
    # check account balance
    if form.is_valid:
        if currency in my_dict.keys():
            price = dollar_to_coin(item.price_usd, my_dict[currency])
            if request.user.acc_btc_balance < price:
                messages.error(request,'Not enough balance to buy this item')
                return redirect('item', pk=item.pk)
            else:
                # do blabla

forms.py

WALLET_CHOICE = [
    ('btc', 'BTC'),
    ('xmr', 'XMR'),
    ('ltc', 'LTC'),
    ... 
]

class CurrencyBuySelectForm(forms.Form):
    currency = forms.ChoiceField(choices=WALLET_CHOICE, widget=forms.RadioSelect())
    captcha = CaptchaField()

    def __init__(self, *args, **kwargs):
        super(CurrencyBuySelectForm, self).__init__(*args, **kwargs)
        self.fields['currency'].label = mark_safe('')

    def clean(self):
        self.cleaned_data = super(CurrencyBuySelectForm, self).clean()

    def currency(self):
        self.currency = self.cleaned_data.get(choices=WALLET_CHOICE, widget=forms.RadioSelect())
        if not self.currency:
            raise forms.ValidationError('Something went wrong')
        return self.currency