问题
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:
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
来源:https://stackoverflow.com/questions/24225928/how-to-customize-a-django-modelform