Search code examples
djangoradio-button

Get the selected radio button in django template


In my template I have for loop. As you can see the id for each radiobutton is represented by {{stud.id}} .

{{stud.nameAndSurname}} shows the name and the surname of the student(in browser I can see name and surname of the corresponding student).

<form method="POST" class="post-form">
        {% csrf_token %}
        {% for stud in students %}
            <input type="radio" id="{{ stud.id }}" name="student">{{ stud.nameAndSurname  }}
        {% endfor %}
    <button type="submit" class="save btn btn-default">GO!</button>
</form>

In my view.py I have:

 class MyClass(View):
     def get(...):
         ...

     def post(self,request, pk):
         myVar = request.POST.get("student")
         return HttpResponse(myVar)

If I click submit button i want to go to another page that shows me name and surname of the selected student. Now the issue is that instead of the student's name and surname it's showing me simply written "on"


Solution

  • Radio buttons need to have a value. (Note that the part after the end of the input is the label, and should be enclosed in a label element.)

    <input type="radio" id="student_{{ stud.id }}" name="student" value="{{ stud.id }}">
    <label for="student_{{ stud.id }}">{{ student.nameAndSurname }}</label>