Reputation: 100
I have Article model and user wants to select which articles should be exported to file.
I want to use Django Form / ModelForm class to generate something like:
<input type="checkbox" name="articles[0]">Article #0</input>
<input type="checkbox" name="articles[1]">Article #1</input>
<input type="checkbox" name="articles[2]">Article #2</input>
<!-- ... -->
How can I do that and then get selected articles?
Upvotes: 3
Views: 2567
Reputation: 3234
Django's forms have a ModelMultipleChoiceField
for that. The default widget is <select>
, but you can tell it to use checkboxes instead (CheckboxSelectMultiple
):
from django import forms
from <yourapp>.models import Article
class ExportForm(forms.Form):
…
articles = forms.ModelMultipleChoiceField(
queryset = Article.objects.all(), # or .filter(…) if you want only some articles to show up
widget = forms.CheckboxSelectMultiple,
)
Upvotes: 3