Max Chen
Max Chen

Reputation: 23

django ModelMultipleChoiceField display in template

class AddRoleForm(forms.Form):
     roles=forms.ModelMultipleChoiceField(queryset=Role.objects.all(),widget=forms.CheckboxSelectMultiple())

in the template :

{{ form.roles }}

the result is like this:

 <ul>
    <li><label for="id_roles_0"><input type="checkbox" value="1" name="roles" id="id_roles_0"> User object</label></li>
    <li><label for="id_roles_1"><input type="checkbox" value="2" name="roles" id="id_roles_1"> User object</label></li>
    </ul>

I want to show the role's name in each line and get the role's id in the chebox like:

<ul>
    <li><label for="id_roles_0"><input type="checkbox" value="100" name="roles" id="id_roles_0">boss</label></li>
    <li><label for="id_roles_1"><input type="checkbox" value="101" name="roles" id="id_roles_1">employee</label></li>
    </ul>

What should i do?

Upvotes: 2

Views: 6367

Answers (3)

Jhonny From China
Jhonny From China

Reputation: 31

check your model 'Role'

you need add

def __unicode__(self):
    return self.name

Upvotes: 3

awesoon
awesoon

Reputation: 33661

  • To change value parameter you have to do those steps:

    1. Write your own CheckboxInput and overload render function. You have to change

      final_attrs['value'] = force_text(value)
      

      to something like that:

      final_attrs['value'] = force_text(str(int(value) + 99))
      

      Other parts can be copied without changes.

    2. Write your own CheckboxSelectMultiplue and overload render function. You have to change

      cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
      

      to your implementation of CheckboxInput.

    3. Use your new widget instead of built-in.

    NOTE: Parts of code may differs, because they can depends of Django version

  • About issue with User object: I'm not sure, but try to check your __unicode__ function.

Upvotes: 0

Below the Radar
Below the Radar

Reputation: 7635

I think you this post can possibly help you.

Have a look at: Django - Render CheckboxSelectMultiple() widget individually in template (manually)

Upvotes: 0

Related Questions