gpt4 book ai didi

python - Django Form Error : Select a valid choice. ...不是可用选项之一

转载 作者:行者123 更新时间:2023-11-28 17:11:09 29 4
gpt4 key购买 nike

我正在尝试创建一个动态选择字段。我有一个创建元组列表的 View 。元组的第一个值是对象 ServiceWriter 的主键,而第二个值是 ServiceWriter 的名称。然后该列表被传递到表单类中。当我进行选择并提交页面时,表单被确定为无效,并且在 shell 中打印以下表单错误:“选择一个有效的选择。(元组的第一个值。即 1,2,3..)是不是可用的选择之一。”

forms.py

class CreateAdvancedRO(forms.Form):
service_writer = forms.ChoiceField()

def __init__(self, writer_choices, *args, **kwargs):
super(CreateAdvancedRO, self).__init__(*args, **kwargs)
self.fields['service_writer'].choices = writer_choices
self.helper = FormHelper()
self.helper.form_id = 'id-create-advanced-ro'
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', 'Open Repair Order'))

注意:我没有使用 ModelForm。

views.py
class CreateAdvancedRO(View):
form_class = CreateAdvancedRO
writer_form = CreateServiceWriter
add_line_form = AddJobLine

def post(self, request):
writer_choices = []
form = self.form_class(writer_choices, request.POST)
print(form.errors)
if form.is_valid():
'''Do something'''
else:
writer_choices = []
try:
writers = ServiceWriter.objects.filter(user=request.user)
for writer in writers:
writer_choices.append((str(writer.id), writer.name))
except ObjectDoesNotExist:
pass
form = self.form_class(writer_choices, request.POST)
writer_form = self.writer_form()
add_line_form = self.add_line_form()
return render(request, 'free/advanced_create.html', {'form': form, 'writer_form': wri
'add_line_form': add_line_form})

我在 View 中尝试了以下两种方法:

writer_choices.append((str(writer.id), writer.name)) and
writer_choices.append((writer.id, writer.name))

这里是 ServiceWriter 模型,以防万一。

class ServiceWriter(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=20, blank=False)

def __str__(self):
return str(self.name)

有什么想法吗?感谢您的帮助。

最佳答案

看起来您正在尝试根据一个空的选择列表来验证表单。在实例化或尝试验证表单之前,您是否尝试过填充 writer_choices?

关于python - Django Form Error : Select a valid choice. ...不是可用选项之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47333005/

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