How to customize a Django ModelForm

2019-08-29 10:32发布

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?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-29 10:54

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
查看更多
登录 后发表回答