django - 表单中的动态选择字段 [英] django - dynamic select fields in forms

查看:201
本文介绍了django - 表单中的动态选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为picks的模型,允许用户选择一个nfl团队(从静态列表中)。每当他们选择一个团队时,他们再也不能再选择那个团队,所以选择的选择可以由他们选择的任何一个团队来减少。

我有一个函数,在我看来,他们还没有选择,但我不知道如何将这些信息传递给表单。我已经在线查看了许多表单示例,但并没有真正找到一个显示如何完成这一点的表单。从我读过的,似乎我应该从forms.py文件中调用这个函数,但该函数需要用户id和联盟id作为参数传递,所以我宁愿在模型中做。有人可以解释一下,或者指出一个解释,说明如何将选择的领域选择从模型传递给表单?

I have a model called picks that allows users to select an nfl team (from a static list). Whenever they choose a team, they can no longer choose that team again, so there selection choices are reduced by any teams they have chosen.
I have a function that I call in my view that figures out what teams they have not selected yet, but I cannot figure out how to pass this information to the form. I've looked at many form examples online but have not really found one that shows how to accomplish this. From what I've read, it seems like I should be calling this function from the forms.py file, but the function needs the user id and league id passed in as parameters so I'd rather just do it in the model. Can someone explain, or point me to an explanation showing how to pass in select field choices from a model to a form?

我在Django和Python中都比较新所以请原谅我在这里做的任何明显的疏漏。

I'm relatively new in both Django and Python so please excuse any obvious oversights I'm making here.

谢谢!

strong>

EDIT

好的,我也许在这里给出了太多关于这个问题的非关键信息,我会尽量简化这个问题:

Ok, I think perhaps I gave too much non-crucial information for the issue here, I'll try to simplify the question here:

我有一个创建表单的视图。表单中有一个选择框。我根据当前用户和启动视图的URL中的变量计算视图中选择框中应该执行的选项。我想知道如何将选择选项传递到表单中,或者如果这不是应该如何实现的。

I have a view which creates a form. The form has a select box in it. I calculate the options that should go in the select box inside of the view, based on the current user and a variable in the URL that launched the view. I would like to know how to pass the select options into the form, or if that is not how this should be accomplished.

此时我没有在我面前的代码发布,但我真的不认为这与问题有关。我希望我已经足够通用了。

I don't have the code in front of me at this time to post, but I really don't think it's relevant to the problem. I hope I have made it generic enough.

推荐答案

您可以先定义您的表单而不使用动态字段。在您的视图中创建一个实例之后,您可以通过键入

You can first define your form without the dynamic field. AFTER creating an instance of it in your view, you can add the dynamic select field by typing

form_instance.fields['your_field'] = ChoiceField(choices=list_of_two_tuples)

或使用ModelChoiceField并输入类似于

or make use of the ModelChoiceField and type something like

form_instance.fields['your_field'] = ModelChoiceField(queryset=Teams.filter(...))

或者您可以使用类似的,但可能是清洁机制描述这里

Or you can use the similar, but probably cleaner mechanism described here.

这篇关于django - 表单中的动态选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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