我有一个我在django处理的表单。它正在正确处理表单,但在处理完成后,它会抛出一个无法发生的http响应错误......
这是表格:
# create a new expense form - group
class CreateExpenseForm(forms.ModelForm):
split_choices = (('1', 'even'),
('2', 'individual'))
split = forms.TypedChoiceField(
choices=split_choices
)
class Meta:
model = Expense
fields = ['location', 'description', 'amount', 'split']
这是视图: 我将打破错误发生的地方:
if request.method == 'POST':
form = CreateExpenseForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
location = cd['location']
description = cd['description']
amount = cd['amount']
split = cd['split']
reference = generate_number()
for member in members:
if member.user.username in request.POST:
new_expense = Expense.objects.create(
user = member.user,
group = group,
location = location,
description = description,
amount = amount,
reference = reference,
created_by = user,
)
print('all exepense accounted for')
所有费用占'在终端打印然后它抛出错误
现在使用表单,只有两个选项可以分为1和2
我正在选择选项1(偶数),因此拆分应为1,但没有打印消息显示...
if split == 1:
print('even split')
print(groupid)
print(groupname)
return redirect('even_expense', groupid = groupid, groupname = groupname)
if split == 2:
print('individual splut')
return redirect('test')
它不会打印任何错误,因此必须在上面的部分中发生http响应错误。
else:
print(form.errors)
return redirect('test')
else:
form = CreateExpenseForm()
parameters = {
'form':form,
'members':members,
}
return render(request, 'groups/create_expense.html', parameters)
答案 0 :(得分:1)
请试试这个:
field = forms.TypedChoiceField(choices=CHOICES, coerce=int)
添加 coerce = int 会将值转换为您想要的类型,此处类型为 int 。