I have model with ManyToManyField. Now I need form but don’t need select field in template.
class Foo(models.Model):
name = models.CharField(max_length=50)
short_description = models.CharField(max_length=100)
price = models.IntegerField()
def __unicode__(self):
return self.name
class Bar(models.Model):
foo = models.ManyToManyField(Foo, blank=True, null=True, related_name='foos')
def __unicode__(self):
return unicode(self.id)
What I really need is to display all data from the Foo model with checkboxes in template, instead of select field which I have if use model.Form and {{ form }} call in template.
class BarForm(forms.ModelForm):
class Meta:
model = Bar
view.py
def show_form(request, id):
foo = get_object_or_404(Foo, id=id)
form = BarForm()
...
To show a
ManyToManyFieldas checkboxes instead of a select field, you need to set the widget in theMetaclass of the appropriateModelFormsubclass. Then to show a custom label on each checkbox, create your own form field class derived fromModelMultipleChoiceField, and overridelabel_from_instance. You may also add HTML tags to the string returned bylabel_from_instanceto make it look as pretty as you want, but remember to wrap the returned string with mark_safe.