【发布时间】:2019-01-10 06:31:53
【问题描述】:
我正在开发一个儿童电子邮件程序,该程序将在单击“全部回复”后使用适当的邮件收件人填充复选框。当我为回复电子邮件创建模板时,我需要动态生成选项以及预先选中的框。一切正常,只是没有选中这些框。我在这里阅读了很多相关的问题,但没有一个是直接从查询集中填充的。我不明白如何/在哪里设置“初始”。为了确保我的过滤器没有导致问题,我将查询集和初始值都设置为相同的值,希望所有框都被选中,但没有一个。感谢您的帮助。
forms.py:
class EmailForm(forms.Form):
recipients = forms.ModelMultipleChoiceField(queryset=None,
widget=forms.CheckboxSelectMultiple)
email_views.py:
def email_compose_show(request, reply_type, email_id):
if reply_type == 'reply-all':
msg = Mail.objects.get(id=email_id)
qs = CustomUser.objects.filter(id__in=get_users(request.user.id)).exclude(id=request.user.id)
form = EmailForm(initial={'message': msg.message, 'subject': msg.subject})
recipients = forms.ModelMultipleChoiceField(
label="Recipients",
widget=forms.widgets.CheckboxSelectMultiple,
queryset=qs,
initial=qs
)
form.fields['recipients'] = recipients
template:
{% for x,y in form.fields.recipients.choices %}
<label for="id_recipients_{{forloop.counter0}}">
<input type="checkbox" name="recipients"
id="id_recipients_{{forloop.counter0}}" value="{{ x }}"> {{ y }}
</label>
{% endfor %}
【问题讨论】: