0

Помогите преобразовать код. Мне необходимо, чтобы программа могла записывать в бд более 1 выбора пользователя. Т.е преобразовать radio в checkbox. Если просто заменить одно на другое, то все еще сохраняется только 1 ответ (причем последний выбранный)

html

<div class="container">
    <h1>Polls details page</h1>
    {% if messages %}
    <div class="messages">
        {% for message in messages %}
        <div {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        {% endfor %}
    </div>
    {% endif %}
    <hr>
    <h2 class="mt-3 mb-3">{{ poll }}</h2>
    <form action="{% url 'polls:vote' poll.id %}" method="POST">
        {% csrf_token %}
        {% for choice in poll.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" class="btn btn-primary mt-3">
        <a class="btn btn-warning mt-3" href="{% url 'polls:list' %}" role="button">Cancel</a>
    </form>

</div>

views

def poll_vote(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    choice_id = request.POST.get('choice')
    if not poll.user_can_vote(request.user):
        messages.error(
            request, "You already voted this poll", extra_tags='alert alert-warning alert-dismissible fade show')
        return redirect("polls:list")

    if choice_id:
        choice = Choice.objects.get(id=choice_id)
        vote = Vote(user=request.user, poll=poll, choice=choice)
        vote.save()
        print(vote)
        return render(request, 'polls/poll_result.html', {'poll': poll})
    else:
        messages.error(
            request, "No choice selected", extra_tags='alert alert-warning alert-dismissible fade show')
        return redirect("polls:detail", poll_id)
    return render(request, 'polls/poll_result.html', {'poll': poll})

1 ответ 1

0
    choice_id = request.POST.get('choice')

ты тут получаешь значение choice, если ты меняешь radio на checkbox, то тебе нужно получать данные с помощью request.POST.getlist('choice') и в дальнейшем обрабатывать именно список значений, а не одно значение.

def poll_vote(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    choice_ids = request.POST.getlist('choice')
    if not poll.user_can_vote(request.user):
        messages.error(
            request, "You already voted this poll", extra_tags='alert alert-warning alert-dismissible fade show')
        return redirect("polls:list")

    if choice_ids:
        for choice_id in choice_ids:
            choice = Choice.objects.get(id=int(choice_id))
            vote = Vote(user=request.user, poll=poll, choice=choice)
            vote.save()
            print(vote)
        return render(request, 'polls/poll_result.html', {'poll': poll})
    else:
        messages.error(
            request, "No choice selected", extra_tags='alert alert-warning alert-dismissible fade show')
        return redirect("polls:detail", poll_id)
    return render(request, 'polls/poll_result.html', {'poll': poll})

Но на мой взгляд, основная проблема, что ты пытаешься работать с django, но при этом формировать все формы html, обработку их вручную.

Зачем это делать? В django есть Form - для работы с вводом данных от пользователя (https://docs.djangoproject.com/en/3.1/topics/forms/#building-a-form-in-django)

ModelForm - развитие Form в сторону более автоматизированной работы моделями(https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#modelform)

4
  • Не поделитесь знаниями, как тогда работать с листом. Я вписала for. Теперь он просто сохраняет первое выбранное значение и ничего более. С формами, тут заморачиваться больше проблем (для меня)
    – user424798
    25 янв 2021 в 7:03
  • изменил ответ. Добавил обработку списка значений. 25 янв 2021 в 22:51
  • Андрей, можно ли получить вашу личную консультацию по своей работе? Вы, похоже, человек разбирающийся в коде, и мне бы очень помогла ваша помощь)
    – user424798
    26 янв 2021 в 7:45
  • Если возникают какие-то вопросы, задавайте на форуме, я стараюсь отвечать, когда есть свободное время. 26 янв 2021 в 19:33

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.