简体   繁体   中英

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

I am trying to import a list of account numbers in django from a model called Accounts in views.py and then trying to pass them to the MoneyTransfer form in form.py but id doesn't work correctly why is that?

views.py code

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 code

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()

replace your form with this form.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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