S
S
Sama Samsonov2016-12-28 10:13:20
Django
Sama Samsonov, 2016-12-28 10:13:20

How to check the radiobutton is selected or not selected?

there is a function

def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.answer_set.get(pk=request.POST['choice'])
    except (KeyError, Question.DoesNotExist):
        # Redisplay the poll voting form.
        return render_to_response('polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        }, <b>context_instance=RequestContext(request))</b>
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return redirect('/polls/%s/results' % p.id)

this exception does not work here how to fix , context_instance=RequestContext(request))
or want to rewrite
selected_choice = p.answer_set.get(pk=request.POST['choice'])
if selected_choice == 'what to write here'
How to check the radiobutton is selected or not selected?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2016-12-28
@ATNC

If the value attribute is not assigned to the radio button, then "on" will come by default. If there are several radio buttons, and you need to distinguish which one is selected, you need to set the value attribute for each radio (also do not forget to set the name attribute). For example:

<input type="radio" name="choice" value="choice1">
<input type="radio" name="choice" value="choice2">
<input type="radio" name="choice" value="choice3">

When submitting the form, the server will receive the value from value. For example, if the first button is selected, the request will receive choice1. Example:
choice = request.POST['choice']
print(choice)
>>> choice1

I also recommend taking a value from a dict using get. This way you can avoid mistakes. For example:
choice = request.POST.get('choice', None)
if choice:
    делать ваш код
else:
    вы не выбрали батон

UPD: If the radiobutton is not selected, its value will not be sent to the server

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question