簡體   English   中英

如何獲得Django選擇領域的價值?

[英]How to get value Django choice field?

我無法從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,但我確實提交了。

if form.is_valid():
                recipe_vote = form.data.get('vote')

用它來閱讀投票

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM