to retrieve values of multiple radio buttons and form fields in views.py django

3.3k views Asked by At

i want to receive the radio button values for the table generated within the form multiple times in views.py in django.

My templates file is something like :

<form action = "/appName/accept" method = "POST"
    {% for l in list %}
        <table>
        <tr>
        <td>{{l.value}}</td> 
        </>tr
        </table>  
        <input type = "radio" name = "acceptance" value ="accept">Accept</input>
        <input type = "radio" name = "acceptance" value ="reject">Reject</input>
     {% endfor %}
     <input type ="submit" name = "submit">SUBMIT</input>
</form>

that means rendered page will look like :

value 1

  • Accept

  • Reject

value 2

  • Accept
  • Reject

and so on SUBMIT BUTTON

as soon as user clicks the submit button, I want to collect the values of all the radio buttons for each value as well as the table rows but how to do that in views.py? I know that if we give common name to radio input like here "acceptance", so only of one of them will be selected at a time. Please Help. I am new to this concept and django.

1

There are 1 answers

0
Amr Abdelaziz On

you should better use django formsets https://docs.djangoproject.com/en/1.8/topics/forms/formsets/

As mentioned in documentation :

from django.forms.formsets import formset_factory
from django.shortcuts import render_to_response
from myapp.forms import ArticleForm

def manage_articles(request):
    ArticleFormSet = formset_factory(ArticleForm)
    if request.method == 'POST':
        formset = ArticleFormSet(request.POST, request.FILES)
        if formset.is_valid():
            for form in formset:
                form.cleaned_data...
                # here you can access each radio button


    else:
        formset = ArticleFormSet()
    return render_to_response('manage_articles.html', {'formset': formset})

The manage_articles.html template might look like this:

<form method="post" action="">
    {{ formset.management_form }}
    <table>
        {% for form in formset %}
        {{ form }}
        {% endfor %}
    </table>
</form>