TheCodingRecruiter
TheCodingRecruiter

Reputation: 71

Why can't I get radio buttons when using RadioSelect form in Django?

I am working to build a page where the user can select a month via the use of radio buttons. I also need to collect other information with this such as first name, last name, email, phone number, and company. In doing this, I figured using Django forms should get the job done. I began and implemented everything and got to the part for the radio buttons. I found out I needed to do this using the ChoiceField and that RadioSelect is a widget of it. All of my choices are showing up, but I can't click on any of them to select them. Also, this is going to be a required question, and I am not sure how to make this a required form, as it can be left blank and I see it still will POST with no issues.

I googled everything under the sun. I tried to set an initial selection for it, hoping that it would display at least one radio button, but that didn't do it. I tried just doing widget=forms.Select() instead of RadioSelect() and still the months display, but I can't select any of them. Not sure what to do. This is utilizing Django 2.1 if that helps.

index.html --- Please note that while I do have a place for month radio buttons here, I am trying to not have them in the template and would prefer them in the form.py file {% extends 'landingpage/layout.html' %}

{% block content %}
<div class="h1 col s3 left-align grey lighten-4" style="font-family: 'Exo', sans-serif;">Welcome to FaithGuard</div>
<div class="div">
        <br>
        <br>
        <br>
        <br>
</div>

<div class="row" style="font-family: 'Exo', sans-serif;">


        <form method='POST' class="col s6"> {% csrf_token %}
{{ form }}

<div class="h1 col s6 grey lighten-4 radioRequired">Date of renewal/expiration</div>
<br>
<br>

<div class="div" id ="Exiration Month Div">
                <p>
                  <label>
                    <input name="month" value ="January" type="radio" />
                    <span>January</span>
                  </label>
         <label>
           <input name="month" value ="February" type="radio" />
          <span>February</span>
        </label>

         <label>
         <input name="month" value="March" type="radio"  />
         <span>March</span>
         </label>
         <label>
          <input name="month" value="April" type="radio" />
           <span>April</span>
        </label>
                </p>


                <p>
                  <label>
                    <input name="month" value="May" type="radio" />
                    <span>May</span>
                  </label>
                                    <label>
                    <input name="month" value="June" type="radio" />
                    <span>June</span>
                  </label>
                                    <label>
                    <input name="month" value="July" type="radio" checked/>
                    <span>July</span>
                  </label>
                                    <label>
                    <input name="month" value="August" type="radio" />
                    <span>August</span>
                  </label>
                </p>
                <p>
                  <label>
                    <input name="month" value="September" type="radio"  />
                    <span>September</span>
                  </label>
                                    <label>
                    <input name="month" value="October" type="radio" />
                    <span>October</span>
                  </label>
                                    <label>
                    <input name="month" value="November" type="radio" />
                    <span>November</span>
                  </label>
                                    <label>
                    <input name="month" Value="December" type="radio" />
                    <span>December</span>
                  </label>
                </p>
<div class="div right-align">
<button class="btn waves-effect waves-light" type="submit" name="action">Submit</button>
</div>

</div>
              </form>

      </div>

{% endblock %}

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .forms import ContactForm

# Create your views here.

def index(request):

    contact_form = ContactForm(request.POST or None)

    context = {
        'form' : contact_form

    }
    if contact_form.is_valid():
        print(contact_form.cleaned_data)

    if request.method == "POST":
        print(request.POST)
    #     print(request.POST.get('email'))



    return render(request, 'landingpage/index.html', context)

forms.py

from django import forms

class ContactForm(forms.Form):

firstname = forms.CharField(
    label="First Name", widget=forms.TextInput(
        attrs={
            "class": "form-control", 
            "placeholder": "First Name"
            }
            )
            )
lastname = forms.CharField(
    label="Last Name", widget=forms.TextInput(
        attrs={
            "class": "form-control", 
            "placeholder": "Last Name"
            }
            )
            )
npo = forms.CharField(
    label="Nonprofit Organization", widget=forms.TextInput(
        attrs={
            "class": "form-control", 
            "placeholder": "Nonprofit Organization",
            }
            )
            )
email = forms.EmailField()
phone = forms.IntegerField(min_value=999999)
month = forms.ChoiceField(label='Month of Renwal/Expiration', choices=[('1', 'January'), ('2', 'February'),('3', 'March'),('4','April'),('5','May'),('6','June'),('7','July'),('8','August'),('9','September'),('10','October'),('11','November'), ('12', 'December')], initial='1',
widget=forms.RadioSelect())


# EXAMPLE FROM ANOTHER STACKOVERFLOW RADIOSELECT ISSUE
# do_a = forms.ChoiceField(label='Do A',choices=[('1', 'Yes'), ('2', 'No'), ('3', 'Maybe')], initial='Maybe', widget = forms.RadioSelect())

What I am expecting from this is for the months to display with radio buttons the user can select from

This is what I see after removing the hardcoded inputs from the template

Upvotes: 0

Views: 1964

Answers (2)

Luiz
Luiz

Reputation: 2055

it's a lot of questions here but to clarify a little bit, that are having the same isue, the django radio select display something like this in most of cases

<label>
    {{ radio.choice_label }}
    <span>{{ radio.tag }}</span>
</label>

which produce this, and that's why the radio doesn't show properly

<label>
    <span>name_of_choice
       <input />
    </span>
</label>

we need to do something like this to work

{% for radio in form.clientes %}
    <label>
        {{ radio.tag }}
        <span>{{ radio.choice_label }}</span>
    </label>
{% endfor %}

I suggest to you pass parameters from views.py for forms.py to get i clean template and correct values, if you have a doubt on that, let me know.

Upvotes: 0

frnhr
frnhr

Reputation: 12903

Unless you really have to do it yourself, you should let Django render the input tags for you.

You can let it render the whole form with {{ form }} or {{ form.as_p }}or similar. Or you can render individual fields like: {{ form.month }} (and also {{ form.month.errors }} to show any validation errors). Relevant docs: https://docs.djangoproject.com/en/2.2/topics/forms/#rendering-fields-manually

I think your immediate problem is that you have duplicate inputs in a single <form> element, i.e. input with the same name attribute. One set of inputs (radio buttons) comes from the {{ form }} template tag and the other is hardcoded in the template. Try removing the hardcoded inputs and see if the forms starts to behave as expected.

Upvotes: 1

Related Questions