Get the selected radio button in django template
Asked Answered
M

2

8

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"

Mouton answered 11/10, 2017 at 13:10 Comment(2)
is it a typo or you missed the closing </input> tag?Tedious
If I close it putting </input> at the end, I have a """warning""" that's say "closing tag is redundant". I think isn't necessary. However even if I put it, my problem isn't resolvedMouton
V
13

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>
Verduzco answered 11/10, 2017 at 13:41 Comment(0)
I
1

Signup.html django template

<div id="row type-select">
    {% for choice in form.option %}
        <div class="col s12 m4 l4 center-align">
          {{ choice.tag }}
           <label for="{{ choice.id_for_label  }}">{{ choice.choice_label }}</label>
        </div>
    {% endfor %}
</div>

forms.py

override SignUpForm from django-allauth

CHOICES=[('1','type 1'),
         ('2','type 2'),
         ('3','type 3')]

class SignupForm(forms.Form):
    option = forms.ChoiceField( widget=forms.RadioSelect,choices=CHOICES)
    first_name = forms.CharField(max_length=30, label='name')
    last_name = forms.CharField(max_length=30, label='last name')

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
Impatient answered 1/12, 2017 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.