gpt4 book ai didi

python - django ModelMultipleChoiceField(默认值)

转载 作者:行者123 更新时间:2023-12-05 05:29:03 26 4
gpt4 key购买 nike

在过去的几个小时里,我一直在搜索并试图让它工作,但我做不到

我有一个从数据库中获取的技能列表:

forms.ModelMultipleChoiceField(
skills.objects.all(),
required=True,
widget=forms.CheckboxSelectMultiple(),
label='Check your skills.',
initial=skill_list.objects.filter(user='void'),
)

但这并没有像我期望的那样工作。我基本上想显示技能列表(所有技能)以及用户已经检查过的技能……pff 我什至无法解释正确。

在用户选中复选框并在另一个页面中点击提交后,我想显示所有技能以及用户选中的技能。

假设我有 a b c 并且用户检查 b 并在 w/中点击提交我要显示的页面 a unchecked b checked c unchecked.

PS:如果我使用 skills.objects.all(),我会进入 HTML value 1 以及如何制作它像这样:

skills = (
('a', 'a'),
('b', 'b'),
)

代替 ('1', 'a'), ('2', 'b')

最佳答案

你的问题有点不清楚,我还是会尽力的。

首先,

I wanna display all skills and the one the user checked to be checked ...

该表单无权访问用户,因此您需要将其传递给用户。您可以像这样通过重载 __init__ 方法来做到这一点:

    def __init__(self, **kwargs):
current_user = kwargs.pop ('user')
super(FormName, self).__init__(attrs)

然后设置初始选择的值,

self.fields['skills'].initial = skill_list.objects.filter(user='void')

请记住,您必须在调用基类的构造函数之后执行此操作。

最后,

PS: if i use skills.objects.all() I get in the html value 1 and a how can I make this as

skills = ( ('a', 'a'), ('b', 'b'), )

instead of ('1', 'a'), ('2', 'b')

你为什么要这样做?这些数字是“技能”表中行的主键。 Django 使用它来设置适当的关系。

关于python - django ModelMultipleChoiceField(默认值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4010878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com