Django:从视图函数向复选框提供选择列表

发布于 2024-08-11 10:38:10 字数 653 浏览 4 评论 0原文

在我的 Django 应用程序中,我有一个带有 ChoiceField 的表单,通常允许在一系列整数值之间进行选择。

class FormNumber(forms.Form):
list=[]
for i in range(1, 11):
    list.append((i,i))
number=forms.ChoiceField(choices=list, initial=1)

现在,在某些情况下,我需要使用较小的范围覆盖视图方法中的默认选择列表,但尝试以这种方式执行此操作时,

n=10-len(request.session["items"])
    if n>0:
        list=[]
        for i in range(1, n+1):
            list.append((i,i))
        form=FormNumber(choices={'number':list}, initial={'number':1})

我收到 TypeError - __ init__() 获得了意外的关键字参数“选择”。我还尝试从表单类中删除参数,但得到了相同的结果。

有没有一种方法可以通过与上面类似的方式从视图中使用新的选择列表来初始化 ChoiceField ? 提前致谢 :)

in my Django application I've got a form with a ChoiceField that normally allows to choice between a range of integer values.

class FormNumber(forms.Form):
list=[]
for i in range(1, 11):
    list.append((i,i))
number=forms.ChoiceField(choices=list, initial=1)

Now I need to override the default choices list from a view method in some cases, using a smaller range, but trying to do it in this way

n=10-len(request.session["items"])
    if n>0:
        list=[]
        for i in range(1, n+1):
            list.append((i,i))
        form=FormNumber(choices={'number':list}, initial={'number':1})

I get a TypeError - __ init__() got an unexpected keyword argument 'choices'. I tried also to remove the parameters from the form class, but I get the same result.

Is there a way to initialize the ChoiceField with a new choices list from the view in a way similar to the one above?
Thanks in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独岁月 2024-08-18 10:38:10

我把代码贴出来,也许将来有人需要解决类似的问题。

现在的表单代码是这样的:

class FormNumber(forms.Form): 
    def __init__(self, list=None, *args, **kwargs):
        super(FormNumber, self).__init__(*args, **kwargs)
        self.fields["number"]=forms.ChoiceField(choices=list)

我从视图中简单地调用它

form=FormNumber(list=number_list) 

I post the code, maybe someone in future needs to solve a similar problem.

The form code now is this one:

class FormNumber(forms.Form): 
    def __init__(self, list=None, *args, **kwargs):
        super(FormNumber, self).__init__(*args, **kwargs)
        self.fields["number"]=forms.ChoiceField(choices=list)

and I call it from the view simply with

form=FormNumber(list=number_list) 
不即不离 2024-08-18 10:38:10

我将向表单类 FormNumber 添加一个 __init__(choices=None) 函数,并使用该函数初始化 ChoiceField number ,除非它是 None
如果未提供choices(默认为None),初始化将执行默认情况下的操作。

I would add an __init__(choices=None) function to the form class FormNumber and initialize the ChoiceField number using that unless it's None.
If choices is not provided (defaults to None), initialization would do what it does by default.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文