繁体   English   中英

如何从 views.py 文件中导入 django 的 ChoiceField 中的所有选项?

[英]how can i import all choices in a ChoiceField in django from the views.py file?

我正在尝试从views.py中名为Accounts的model导入django中的帐号列表,然后尝试将它们传递给form.py中的MoneyTransfer表单,但id无法正常工作,这是为什么?

view.py 代码

def transfer (request):
    if request.method == 'POST':
        accs1=[]
        num=[]
        accs=Account.objects.filter(Account_User=request.user)
        for acc in accs:
            accs1.append(str(acc.Account_ID))
        acc_dictionary =dict(zip(accs1,accs1))
        print(acc_dictionary)
        form= MoneyTransfer(request.POST,acc=acc_dictionary)
        if form.is_valid():
            from_acc = form.cleaned_data.get('from_account')
            to_acc = form.cleaned_data.get('to_account')
            amount = form.cleaned_data.get('amount')
            acc1=Account.objects.filter(Account_ID=from_acc).first()
            acc2=Account.objects.filter(Account_ID=to_acc).first()
            acc1.Account_Balance -=amount
            acc2.Account_Balance +=amount
            acc1.save()
            acc2.save()
            logger.info(f'{amount} transaction was made from {acc1} to {acc2}')
            messages.success(request, f'Money Has Been Successfuly Transfered ')
            return redirect('dashboard-page')   
    else:
        form = MoneyTransfer()
    return render(request, 'website/transfer.html',{'form':form})

forms.py代码

class MoneyTransfer(forms.Form):
    def __init__(self, *args, **kwargs):
        self._acc = kwargs.pop('acc', None)
        super().__init__(*args, **kwargs)
        accs = self._acc
        
        from_account = forms.ChoiceField(choices = tuple([(accs, accs)]))
        to_account = forms.IntegerField()
        amount = forms.IntegerField()

用此表格替换您的表格。

class MoneyTransfer(forms.Form):

    # your fields

    from_account = forms.ChoiceField()
    to_account = forms.IntegerField()
    amount = forms.IntegerField()

    def __init__(self, *args, **kwargs):
        self._acc = kwargs.pop('acc', None)
        super(MoneyTransfer, self).__init__(*args, **kwargs)
        print(tuple([(self._acc, self._acc)]))
        self.fields['from_account'].choices = tuple(map(lambda x: (x[0], x[1]), self._acc.items())) # x[0] is key & x[1] is the value of key

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM