[英]Dynamically alter form fields in views.py file of django
I was wondering if there is a way that I can alter a model form within the views.py file to create a multiple choice dropdown field for form choices. 我想知道是否有一种方法可以更改views.py文件中的模型表单,以为表单选择创建多选下拉列表字段。 I want to set each option on the choice field from the results of a queryset. 我想根据查询集的结果在选择字段上设置每个选项。
for example: I want to from_acct field to have a scroll down option with the following list.. wells fargo chase tabz bank of america 例如:我希望from_acct字段具有以下列表的向下滚动选项。.wells fargo chase tabz美国银行
the list of banks are results of a query set 银行列表是查询集的结果
Here is what i have so far in the views.py file. 这是我到目前为止在views.py文件中所拥有的。
form = TransferForm()
form.fields['from_acct'].queryset = Accounts.objects.filter(user = currentUser).all()
message = 'please fill out the below form'
parameters = {
'form':form,
'currentUser':currentUser,
'message':message,
}
return render(request, 'tabs/user_balance.html', parameters)
here is the forms.py file 这是forms.py文件
class TransferForm(forms.ModelForm):
class Meta:
model = Transfers
fields = ['from_acct', 'to_acct', 'amount', 'memo']
labels = {
'from_acct':'from',
'to_acct':'to',
}
here is the model.py file 这是model.py文件
class Transfers(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
from_acct = models.CharField(max_length=150, default='account')
to_acct = models.CharField(max_length=150, default='accont')
amount = models.DecimalField(decimal_places=2, max_digits=9, default=0)
memo = models.CharField(max_length=200, default='memo')
frequency = models.SmallIntegerField(default=1)
status = models.SmallIntegerField(default=1)
create = models.DateTimeField(auto_now_add=True)
You can try to set choices arg for CharField by function. 您可以尝试按功能为CharField设置选项arg。
Like that: 像那样:
class Transfers(models.Model):
field = models.CharField(max_length=255, choices=result_query())
def result_query(self):
# you can use that with self if u need transfers.pk for querying
return Something.objects.exclude(bank_id__in=[bank.id for bank in self.banks.all())
def result_query():
# or there if not
return Something.objects.filter(any_field__gte=123)
For sure, you can realize any logic in the function, so you can dynamically change options for char field. 当然,您可以在函数中实现任何逻辑,因此可以动态更改char字段的选项。
UPDATE: 更新:
Sure, u haven't pass request into the function. 当然,您尚未将请求传递到函数中。 That should be like that: 那应该是这样的:
view.py: view.py:
def my_view(request):
if request.method == 'GET':
form = TransferForm(user=request.user)
...
return something here
forms.py forms.py
class TransferForm(ModelForm):
class Meta:
model = Transfer
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(TransferForm, self).__init__(*args, **kwargs)
self.fields['accounts'].choices = Accounts.objects.filter(user = currentUser).all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.