Skip to content

Instantly share code, notes, and snippets.

@simonbowen
Last active December 12, 2015 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonbowen/4727718 to your computer and use it in GitHub Desktop.
Save simonbowen/4727718 to your computer and use it in GitHub Desktop.
How to customise output of the CheckboxSelectMultiple in Django. I was being a pleb and didn't quite get it at first
### Form, I was originally using a ModelForm, so that's what I shall demonstrate here
class Author(models.Model):
books = models.ManyToManyField(Book)
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
def __init__(self, *args, **kwargs):
super(LovelyForm, self).__init__(*args, **kwargs)
# Overloaded the form widget type here, since this is the only
# way I could work out how
self.fields['books'].widget = CheckboxSelectMultiple()
self.fields['books'].queryset = Books.objects.all()
### HTML for form
{% for value, text in form.books.field.choices %}
<label><input type="checkbox" value="{{ value }}" name="{{ form.books.name }}" {% if value in form.books.value %}checked{% endif %}/>{{ text }}</label>
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment