Last active
December 12, 2015 06:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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