我有几个相当复杂的表单,它们依赖于模型层次结构来分配ForeignKey
价值观。我需要根据其父字段的值限制子字段可用的选择。问题是父字段的值可能来自初始数据(GET 请求)or来自绑定数据(POST 请求)。因此,我最终多次复制了这种模式:
class MyForm(forms.Form):
parent = forms.ModelChoiceField(queryset=Parent.objects.all())
child = forms.ModelChoiceField(queryset=Child.objects.all())
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
# Limit 'child' choices based on current value of 'parent'
if self.is_bound and self.data.get('parent'):
self.fields['child'].queryset = Child.objects.filter(parent__pk=self.data['parent'])
elif self.initial.get('parent'):
self.fields['child'].queryset = Child.objects.filter(parent=self.initial['parent'])
else:
self.fields['child'].choices = []
我感觉有一种更有效的方法可以实现这一目标。我缺少什么?
你很幸运。Django 智能选择 https://github.com/digi604/django-smart-selects让这变得非常简单!您必须使用 ModelForm(如下)或使用ChainedForeignKey
字段类型(如文档中所示)。
请注意 - 这不是确切的代码。提供的参数与您的模型定义和结构相关。然而,第一个选项看起来像这样:
from smart_selects.form_fields import ChainedModelChoiceField
class MyForm(forms.ModelForm):
parent = forms.ModelChoiceField(queryset=Parent.objects.all())
child = ChainedModelChoiceField('your_app','ModelName','parent','parent')
class Meta:
model = YourModel
您必须在呈现的页面中包含 JQuery 才能使用智能选择。呈现表单字段时,智能选择将包含适用的 JQuery 代码,以便在以下情况下发出 Ajax 请求:parent
被选择,限制children
与所选内容相关的选项parent
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)