python - 在 __init__ of forms.Form 中更改 ModelChoiceField 的查询集

标签 python django forms

我目前在为 forms.Form 覆盖 __init__() 时遇到问题。

基本形式

class ReportsMainForm(forms.Form):
 ---- #Some fields
    def __init__(self, *args, **kwargs):
        super(ReportsMainForm, self).__init__(*args, **kwargs)

子窗体

class Child(ReportsMainForm):
    customer = forms.ModelChoiceField(
        queryset=Customer.objects.none(), label="Customer", empty_label=None, required=False)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(Child, self).__init__(*args, **kwargs)
        self.fields['customer'].queryset = Customer.objects.filter(user=self.request.user)

问题

这里的问题是,我的queryset 还没有更新。我错过了什么?

最佳答案

尝试更改小部件的查询集(嗯...选择):

self.fields['customer'].queryset = ...
self.fields['customer'].widget.choices = self.fields['customer'].choices

为什么?

检查代码(参见 django.forms.model.ModelChoiceField),当在字段上设置查询集时,小部件的选择也会更新(这很好):

但是选择缓存在字段中,所以它们总是相同的...

我认为这是一个错误,因为字段 init 上有显式选项“cache_choices”,默认为 False。

关于python - 在 __init__ of forms.Form 中更改 ModelChoiceField 的查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27480885/

相关文章:

python - 模拟 xmlrpc.client 方法 python

python - 使嵌套循环运行得更快,例如通过 Python 中的矢量化

Django-rest-auth (dj-rest-auth) 自定义用户注册

django - Procfile 中的 heroku $PORT 变量

ruby-on-rails - ActiveAdmin 嵌套表单重复

python - 使用全局变量的 WebSocket 线程

python - 如何在 XGBoost 中释放 GPU 上的所有内存?

python - Django:生成 CSV 文件并将其存储到 FileField

javascript - 如何将模板中的动态表传递到我的 View 以迭代地将它们保存到我的数据库中

html - 包装 Label 和 Input 元素的最佳方式是什么