【发布时间】:2019-09-29 22:57:43
【问题描述】:
我无法从 Django 表单选择字段中读取数据。表单中的数据不会转到views.py 或forms.py 中的表单。错误列表 = 选择一个有效的选项。费率不是可用的选择之一。如何解决?
#views.py
def recipe_detail(request, recipe_name):
recipe = Recipe.objects.get(recipe_name=recipe_name)
form = VoteSubmissionForm()
if request.method == 'POST':
recipe = Recipe.objects.get(recipe_name=recipe_name)
if 'Like' in request.POST:
recipe_like = recipe.recipe_like
recipe_like = int(recipe_like) + 1
recipe = Recipe.objects.filter(recipe_name=recipe_name).update(recipe_like=recipe_like)
recipe = Recipe.objects.get(recipe_name=recipe_name)
return render(request, 'detail.html', {
'recipe': recipe,
'form': form,
})
elif 'vote' in request.POST:
form = VoteSubmissionForm(request.POST) #forma veri gelmiyor ?
if form.is_valid():
recipe_vote = recipe.recipe_vote
recipe_vote_count = recipe.recipe_vote_count
recipe_vote = (int(recipe_vote) * int(recipe_vote_count) + form.cleaned_data['vote']) / (int(recipe_vote_count) + 1)
recipe_vote_count = int(recipe_vote_count) + 1
recipe = Recipe.objects.filter(recipe_name=recipe_name).update(recipe_vote=recipe_vote, recipe_vote_count=recipe_vote_count)
recipe = Recipe.objects.get(recipe_name=recipe_name)
return render(request, 'detail.html', {
'recipe': recipe,
'form': form,
})
else:
return redirect('index')
return render(request, 'detail.html', {
'recipe': recipe,
'form': form,
})
#forms.py
VOTE_CHOICES = (
('0', '0'),
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
('6', '6'),
('7', '7'),
('8', '8'),
('9', '9'),
('10', '10')
)
class VoteSubmissionForm(forms.Form):
vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.Select, label='Vote')
<form method="POST">
{% csrf_token %}
{{ form }}
<input class="btn btn-primary" type="submit" name="vote" value="Rate">
</form>
表单不是 is_valid,但我确实提交了。
【问题讨论】:
-
请添加您看到输出的确切错误消息
-
'VoteSubmissionForm' 对象没有属性 'cleaned_data'
-
您的
submit按钮的名称也是vote。将其更改为其他内容。
标签: python django django-forms