0

I want to build a form based on my customer model.

In the form, the logged-in user specifies the payee, types in an amount and selects the account he wants to pay from.

This is the model and the form thus far:

class Payment(models.Model):
    payee = models.ForeignKey(Customer)
    amount = models.IntegerField()
    accounts = models.ManyToManyField(BankAccount)


class PaymentForm(forms.ModelForm): 

    class Meta:    
        model = Customer
        widgets = {
            'accounts': forms.CheckboxSelectMultiple(),
        }

The problem with this form is that it generates a checkbox for every single possible account that exists in the system, whether or not the user actually it. There could be dozens of types of accounts while the user might only have 3 or 4.

I want the form to only offer checkboxes for the accounts that the user has.

Is there any way to do this?

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • I reply you in your other similar question. http://stackoverflow.com/questions/24225605/how-do-you-generate-a-custom-form-in-django. The same is applies here. Override the __init__ method in the PaymentForm class. – elmonkeylp Jun 15 '14 at 02:53

1 Answers1

0

You can override it in the form's __init__ or in your view:

# whatever you use as user/customer, filter out accounts owned
accounts = BankAcount.objects.filter(user=request.user) 
form = PaymentForm()
form.fields['accounts'].queryset = accounts
lehins
  • 9,642
  • 2
  • 35
  • 49