Django + Forms:ChoiceField的动态选择 [英] Django + Forms: Dynamic choices for ChoiceField

查看:762
本文介绍了Django + Forms:ChoiceField的动态选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为ChoiceField创建一个动态列表,但我似乎无法调用请求。以下是代码:

I'm trying to create a dynamic list of choices for the ChoiceField but I can't seem to call request. Here's the code:

错误:

AttributeError: 'CreationForm' object has no attribute 'request'

strong>

Forms

class FooForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        bars = self.request.session['bars']
        foo_list = []
        for bar in bars:
            foo_list.append((bar['id'], bar['name']),)
        self.fields['foo'].choices = foo_list
    foo = forms.ChoiceField(choices=foo_list, required=True)


推荐答案

当您实例化表单时,为什么不从视图中传递选项?

Why not pass the choices in from the view when you instantiate the form?

例如

Form:

class FooForm(forms.Form):
    def __init__(self, foo_choices, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        self.fields['foo'].choices = foo_choices

    foo = forms.ChoiceField(choices=(), required=True)

查看:

... 
bars = request.session['bars']
foo_list = []
for bar in bars:
    foo_list.append((bar['id'], bar['name']),)
form = FooForm(foo_list)
...

这篇关于Django + Forms:ChoiceField的动态选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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