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?
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,
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With