Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django checkbox form for ModelMultipleChoiceField label for each input

I have the following form:

from models import MyModel

class MultProgresemosReferenciasForm(forms.Form):
    selected = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                    queryset=MyModel.objects.filter(active=True))                   

Which I in turn use in the following template:

  <form action="" method="post">                                                                                             
      {% for field in form %}                                                                                                
        {{ field }}
      {% endfor %}                                                                                                           
      {% csrf_token %}                                                                                                       
      <input type="submit" value="Submit Selected" />
  </form>                                                                                                                    

Which renders the following html:

  <form action="" method="post">
    <ul>
<li><label for="id_selected_1"><input type="checkbox" name="selected" value="9" id="id_selected_8" /> prog 1420000930 - pp 0.0078125</label></li>
<li><label for="id_selected_2"><input type="checkbox" name="selected" value="10" id="id_selected_9" /> prog 1420001041 - pp 0.00390625</label></li>
    </ul>
      <div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='csrf_token_hash_string...' /></div>
      <input type="submit" value="Submit Selected" />
  </form>

As you can see, the template gets some label for each checkbox (from the model, which has two string fields with the values you can see there).

The question is, how can I get into this labels for the checkboxes and customize them? I'm trying to use those same model's names but with some tweaks. Is there an easy way to achieve this in django?

I've tried to use field.label but all I get is the 'Selected' label for the entire ChoiceField. That's not what I want, I need to get into the labels for each generated checkbox...

like image 748
Javier Novoa C. Avatar asked Apr 26 '12 19:04

Javier Novoa C.


1 Answers

I think you want to override in your form label_from_instance

The unicode method of the model will be called to generate string representations of the objects for use in the field's choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it. For example:

def label_from_instance(self, obj):
    #custom logic here...
    return smart_unicode(obj)
like image 99
Nix Avatar answered Nov 20 '22 07:11

Nix