Пример #1
0
def vote(request, question_id):
    # question = get_object_or_404(Question, pk=question_id)
    # try:
    #     selected_choice = question.choice_set.get(pk=request.POST['choice'])
    # except (KeyError, Choice.DoesNotExist):
    #     # Redisplay the question voting form.
    #     return render(request, 'polls/detail.html', {
    #         'question': question,
    #         'error_message': "You didn't select a choice.",
    #     })
    # else:
    #     selected_choice.votes += 1
    #     selected_choice.save()
    #     # Always return an HttpResponseRedirect after successfully dealing
    #     # with POST data. This prevents data from being posted twice if a
    #     # user hits the Back button.
    #     return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

    # <h1>{{ question.question_text }}</h1>
    #
    # {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
    #
    # <form action="{% url 'polls:vote' question.id %}" method="post">
    # {% csrf_token %}
    # {% for choice in question.choice_set.all %}
    #     <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    #     <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
    # {% endfor %}
    # <input type="submit" value="Vote">
    # </form>

    question = get_object_or_404(Question, pk=question_id)

    def post_handler(form, **_):
        if form.is_valid():
            choice = form.fields.choice.value
            choice.votes += 1
            choice.save()
            return HttpResponseRedirect(
                reverse('polls:results', args=(question.id, )))

    return Form(
        title=str(question),
        fields__choice=Field.choice_queryset(question.choice_set.all()),
        actions__submit__post_handler=post_handler,
    )
Пример #2
0
 class TrackForm(Form):
     artist = Field.choice_queryset(choices=Track.objects.all())