3

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?

1
  • Can you show code you tried? Commented Mar 19, 2018 at 14:03

1 Answer 1

3

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,
    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.