我有文章模型,用户想要选择应将哪些文章导出到文件。
我想使用Django Form / ModelForm类来生成类似的东西:
<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>
<!-- ... -->
我该怎么做才能获得精选文章?
答案 0 :(得分:1)
Django的表格有ModelMultipleChoiceField
。默认小部件为<select>
,但您可以告诉它使用复选框(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,
)