小编knu*_*ler的帖子

如何在forms.Form子类上动态设置models.ModelChoiceField的查询集

构造函数forms.ModelChoiceField需要一个查询集.在请求发生之前我不知道查询集.蒸馏:

# models.py
class Bar(models.model):
    text = models.TextField()

class Foo(models.Model):
    name = models.CharField()
    bar = models.ForeignKey(Bar)

# forms.py
class FooForm(forms.Form):
    name = forms.CharField()
    text = forms.CharField(widget=forms.TextArea)

    bar = forms.ModelChoiceField(queryset='??????')
Run Code Online (Sandbox Code Playgroud)

我目前在做什么:

# forms.py

def get_foo_form_class(bars_queryset):
    class FooForm(forms.Form):
        name = forms.CharField()
        text = forms.CharField(widget=forms.TextArea)

        bar = forms.ModelChoiceField(queryset=bars_queryset)

    return FooForm
Run Code Online (Sandbox Code Playgroud)

然后我可以使用urlconf从url解析出的参数在视图中调用它来构造查询集并获取类.这感觉就像是错误的做法.有没有一种既定的方法在django做到这一点?

python django django-forms

29
推荐指数
2
解决办法
2万
查看次数

标签 统计

django ×1

django-forms ×1

python ×1