Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkboxes to select objects in Django

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?

like image 964
Simeon Borko Avatar asked Mar 18 '26 02:03

Simeon Borko


1 Answers

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,
    )
like image 131
helb Avatar answered Mar 20 '26 19:03

helb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!