gpt4 book ai didi

Django:如何将参数传递给表单

转载 作者:行者123 更新时间:2023-12-03 09:21:19 27 4
gpt4 key购买 nike

我有一个使用 bootstrap3 呈现的 Django 表单。我希望能够将参数传递到我的表单中以使其更加通用。我的表单如下所示:

class SpacecraftID(forms.Form):
def __init__(self,*args,**kwargs):
choices = kwargs.pop('choices')
#self.choices = kwargs.pop('choices') produces same error
super(SpacecraftID,self).__init__(*args,**kwargs)

scID = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=choices)

我的观点如下:

def schedule_search(request):
choices = (
('1','SAT1'),
('2','SAT2'),
('3','SAT3'),
)

if request.method == 'POST':
form_ID = SpacecraftID(request.POST,choices=choices)
if form.is_valid():
scID = form_ID.cleaned_data['scID']

else:
form_ID = SpacecraftID(choices=choices)

return render(request, 'InterfaceApp/schedule_search.html', {'form3': form_ID})

当我运行此代码时,出现错误:

名称错误位于/InterfaceApp/schedule_search/,名称“选择”未定义

最佳答案

问题在于,当您定义表单字段时,choices变量不可用,即当Python解析forms.py文件时,它仅在以下情况下可用:表单在 __init__ 内实例化。然后,您需要更新 __init__ 内的字段。

class SpacecraftID(forms.Form):
def __init__(self,*args,**kwargs):
choices = kwargs.pop('choices')

super(SpacecraftID,self).__init__(*args,**kwargs)

# Set choices from argument.
self.fields['scId'].choices = choices

# Set choices to an empty list as it is a required argument.
scID = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=[])

关于Django:如何将参数传递给表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29974105/

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