1

How can I combine radio-button inside a dropdown select form. I'll be grateful for your help.

My codes: index.html

<div class="card-header">
                <div class="container">
                  <div class="row">
                      <form class="col-md-4">
                          <select class="form-control select2" >
                            <option>Select Major Head</option>
                            {% for major in majors %}
                              <option>{{ major.pk }}: {{ major.description }}</option> 
                            {% endfor %} 
                          </select>
                          <button type="button">Display!</button>
                      </form>
                   </div>
                </div>
              </div>
jas
  • 57
  • 1
  • 6
  • Do you just want to show the choices from the database or you want to collect data from the select form? Or both? – crimsonpython24 Nov 30 '20 at 08:39
  • @crimsonpython24 I want to select multiple options from the dropdown option form so that I can pass it on to the view.py file. – jas Nov 30 '20 at 08:44
  • you cant put radio in select options... unless you make your own dropdown with divs+css+js – BeryCZ Nov 30 '20 at 08:45

1 Answers1

1

This might not be the best approach, but you can try something like this:

<form class="col-md-4" action="{{ your_url_here }}" method="post">
  {% csrf_token %}
  <select class="form-control select2" >
    <option>Select Major Head</option>
    {% for major in majors %}
      <option value="{{ major.pk }}">{{ major.pk }}: {{ major.description }}</option> 
    {% endfor %} 
  </select>
  <input type="submit" value="Select">
</form>

Yes, you need to write a Django form to process the data. You can read more about forms here. The value="{{ major.pk }}" part gives Django views an attribute to recognize, which you are going to use later.

After having filled out the form, you can get the data in your views as such:

def page_objects(request):
  if request.method == 'POST':
    form = YourForm(request.POST)

    if form.is_valid():
      answer = form.cleaned_data['value']

Forms are not the easiest thing to do as you need to create your own views and forms, both backend and frontend. You may also try out other form helper libraries like django crispy forms, but that really depends on how much you want to rely on bootstrap and other UI libraries.

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27