kdubs
kdubs

Reputation: 946

Associate radio buttons with table rows in Django

I am making a website using django. I have a pandas dataframe that I've converted to an html table in my views.py using pandas DataFrame.to_html(). I want to be able to add a radio button to each row of the table so that the user can select which row of the dataframe they want to use for further processing. I have a radio button form in django but am not sure how to apply it to the table.

form looks like this:

class RadioSelectForm(forms.Form):
  def __init__(self,*args,**kwargs):
    arg_list = kwargs.pop('arg_list')
    section_label = kwargs.pop('section_label')
    required_val = kwargs.pop('required_val')

    super(RadioSelectForm,self).__init__(*args,**kwargs)
    self.fields['choice'].choices = arg_list
    self.fields['choice'].label = section_label
    self.fields['choice'].required = required_val

  choice = forms.ChoiceField(widget=forms.RadioSelect())

html template looks like this:

<div class="panel panel-body">
  <div class="panel-title text-center">
    <div class="table-responsive">
      {{ table1 | safe }}
    </div>
  </div>
</div>

views.py table generation looks like this (would like to add radio buttons to each row in this table):

dumy_df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))  #just a placeholder dataframe for this question
html_df = dumy_df.to_html(classes="table table-hover")
template_dict = {'table1':html_df}

return render(request,'DjangoTemplateName.html',template_dict)

Does anyone know if you can associate radio buttons with rows in a table in Django?

Upvotes: 1

Views: 1773

Answers (1)

onyeka
onyeka

Reputation: 1537

Pandas has an insert function you can use to add a column to the generated table. I don't know what you're using to id your individual rows, but let's say we use the values in column A, you can run through the rows.

radio = [] # empty array to push the rows of input tags 
for val in dumy_df.['A']:
    radio.append('<input type="radio" value="{}">'.format(val))

So you could try dumy_df.insert(0, 'E', radio , allow_duplicates=True)

0, being the location, radio being html for the radio button like

Then you could wrap the whole table in a form tag.

<form action="/some_link/" method="post">
  <div class="table-responsive">
     {{ table1 | safe }}
   </div>
</form>

I haven't tried this in entirety, but something along these lines might work.

Edit2: Okay, see above.

Upvotes: 2

Related Questions