How to create a list of Django Forms -- with different HTML names so we can retrieve them easily?

Viewed 37

In a table, each row contains an ID number and a dropdown. I want the user to choose a value in each row's dropdown, and then submit all that and display it on the next page. On the next page I call request.POST.get() so each dropdown needs to have a unique HTML name.

Currently I have the following which works for displaying the info:

class Dropdown(forms.Form):
    def __init__(self, mylistTuples):
        super(Dropdown,self).__init__()
        self.fields['dropdown'] = forms.CharField(label="", widget=forms.Select(choices=mylistTuples))
    dropdown = forms.CharField()

The HTML output of that is:

<tbody >
  <tr class="even">
    <td >item1</td>
    <td ><p> <select name="dropdown" id="id_dropdown">
      <option value="option1">option1</option>
      <option value="option2">option2</option>
    </select></p></td>
  </tr>
  <tr class="odd">
    <td >item2</td>
    <td ><p> <select name="dropdown" id="id_dropdown">
      <option value="option1">option1</option>
      <option value="option2">option2</option>
    </select></p></td>
  </tr>
</tbody>

which doesn't allow me to retrieve the different dropdowns. request.POST.get("dropdown") only retrieves the last one!

I think I want something like the following, but I don't quite understand how the self.fields['name'] relates to the variable name.

class Dropdown(forms.Form):
    def __init__(self, mylistTuples, my_id):
        super(Dropdown,self).__init__()
        self.fields['dropdown_'+my_id] = forms.CharField(label="", widget=forms.Select(choices=mylistTuples))
    dropdown?? = forms.CharField()

I also tried the following without success (self is not defined outside the __init__ function apparently):

class Dropdown(forms.Form):
    def __init__(self, mylistTuples, my_id):
        super(Dropdown,self).__init__()
        self.fields['dropdown_'+my_id] = forms.CharField(label="", widget=forms.Select(choices=mylistTuples))
        self.my_id = my_id
    globals()['dropdown_'+self.my_id] = forms.CharField()

In the next page's view, request.POST.items() will allow me to loop through my results.

1 Answers

Found a way to make it work, but I don't know if that's the most elegant way.
In my form definition, I store the name of the dropdown in a global variable (dd_id):

class Dropdown(forms.Form):
    def __init__(self, mylistTuples, my_id):
        super(Dropdown,self).__init__()
        global dd_id
        dd_id = 'dropdown_' + my_id
        self.fields[dd_id] = forms.CharField(label="", widget=forms.Select(choices=mylistTuples))
    globals()['dd_id'] = forms.CharField()

That creates the HTML output I was looking for, with personalized name and id fields.

Related