如何自定义Django ModelForm [英] How to customize a Django ModelForm
问题描述
我想根据我的客户模型构建表单。
在表单中,登录用户指定收款人,输入金额并选择他想要从中支付的账户。
这是迄今为止的模型和表单:
class Payment(models.Model):
payee = models.ForeignKey(Customer)
amount = models.IntegerField()
accounts = models.ManyToManyField(BankAccount)
class PaymentForm(forms.ModelForm):
$ b $ class Meta:
model = Customer
widgets = {
'accounts':forms.CheckboxSelectMultiple() ,
}
这种形式的问题在于它会为每一个可能的生成一个复选框在系统中存在的帐户,无论用户是否真实存在。可能有几十种类型的帐户,而用户可能只有3或4个。
我希望表单只提供用户帐户的复选框。 / p>
有没有办法做到这一点?
它在表单的 __ init __
中或在您的视图中:
#无论你作为用户/客户使用,过滤出拥有
帐户的帐户= BankAcount.objects.filter(user = request.user)
form = PaymentForm()
form.fields ['accounts']。 queryset = accounts
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?
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
这篇关于如何自定义Django ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!