如何在 forms.Form 子类上动态设置 models.ModelChoiceField 的查询集 [英] How to dynamically set the queryset of a models.ModelChoiceField on a forms.Form subclass

查看:21
本文介绍了如何在 forms.Form 子类上动态设置 models.ModelChoiceField 的查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The constructor for forms.ModelChoiceField requires a queryset. I do not know the queryset until the request happens. Distilled:

# 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='??????')

我目前在做什么:

# 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

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

I can then call it in the view using arguments parsed out of the url with a urlconf to construct the queryset and get the class. This feels like the wrong way to do it. Is there an established way to do this in django?

推荐答案

覆盖表单的 __init__ 方法并在那里设置查询集.

Override the form's __init__ method and set the queryset there.

class FooForm(forms.Form):
    bar = forms.ModelChoiceField(queryset=Bar.objects.none())

    def __init__(self, *args, **kwargs):
        qs = kwargs.pop('bars')
        super(FooForm, self).__init__(*args, **kwargs)
        self.fields['bar'].queryset = qs

这篇关于如何在 forms.Form 子类上动态设置 models.ModelChoiceField 的查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆