如何将数据从ManyToManyField放入MultipleChoiceField中的选择 [英] How to put data from ManyToManyField to choices in MultipleChoiceField
问题描述
我有一个表格:
*# dialogues.forms*
class CreateConferenceForm(forms.Form):
...
participants = forms.MultipleChoiceField(choices=?)
...
我需要输入choices参数而不是?"该模型中来自朋友"字段的数据:
And I need to put in choices argument instead of "?" data from friends field in this model:
*# persons.models*
class Person(User):
...
friends = models.ManyToManyField(
'self',
related_name='+',
)
...
我该怎么办?
推荐答案
If you're creating an instance of a conference model with your form, you should consider using Django's ModelForm
, which is designed to be used in the creation and editing of model instances.
无论哪种情况,您都可以使用 ModelMultipleChoiceField
可以满足您的目的,这只是一个由查询集支持的MultipleChoiceField
用于其选择.您可以在标准Form
或ModelForm
中使用此字段.
In either case, you can use a ModelMultipleChoiceField
to serve your purpose, which is simply a MultipleChoiceField
backed by a queryset for its choices. You can use this field in either a standard Form
or a ModelForm
.
要根据请求自定义选择,可以在视图中设置查询集.
To customize the choices based on the request, you can set the queryset in your view.
例如:
forms.py
class CreateConferenceForm(forms.Form):
# An initial queryset is required, this is overwritten in the view
participants = forms.ModelMultipleChoiceField(Person.objects.all())
views.py
def new_conference(request):
data = request.POST if request.method == 'POST' else None
conference_form = CreateConferenceForm(data=data)
conference_form.fields['participants'].queryset = my_person.friends.all()
if data:
if conference_form.is_valid():
# etc
return render...
请注意,对您而言,在表单上调用is_valid
之前设置查询集非常重要,因为查询集用于验证,并且在将表单传递给模板之前(因为查询集用于生成)显示的选择.
Note that it is important for you to set the queryset prior to calling is_valid
on the form, since the queryset is used in validation, and prior to sending passing the form to a template, since the queryset is used to generate the choices shown.
这篇关于如何将数据从ManyToManyField放入MultipleChoiceField中的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!