How to customize a Django ModelForm

不打扰是莪最后的温柔 提交于 2019-12-25 02:53:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!