我不知道如何动态更新AutoModelSelect2Field的查询集。我得到的结果很奇怪。例如,有时select2框将返回正确的过滤结果,有时当我输入相同的字符时它将不返回任何结果。
我的代码:
#views.py
form = MyForm()
#forms.py
class MyField(AutoModelSelect2Field):
search_fields = ['name__icontains']
max_results = 10
class MyForm(forms.Form):
my_field = MyField(
queryset=project.objects.none(),
required=True,
widget=AutoHeavySelect2Widget(
select2_options={
'width': '100%',
}
)
)
def __init__(self, *args, **kwargs):
qs = kwargs.pop('queryset')
self.base_fields['my_field'].queryset = qs
super(MyForm, self).__init__(*args, **kwargs)
#self.fields['my_field'].queryset = qs
#self.base_fields['my_field'].queryset = qs我试过的几件事-
意见中的最新情况:
#views.py
form = MyForm()
form.base_fields['my_field'].queryset = new_qs以及:
form = MyForm()
form.fields['my_field'].queryset = new_qs将qs传递给表单:
#views.py
form = MyForm(queryset=Project.objects.filter(project_type=pt))
# see above code for forms.py我还尝试将初始qs设置为所有对象:
class MyForm(forms.Form):
my_field = MyField(
queryset=project.objects,
...但我也遇到了同样的问题,90%的时间我得到了初始查询集的结果,而不是基于新qs的过滤对象。
发布于 2014-04-23 14:47:51
我们找到了一种非常简单的方法,可以通过额外的字段来筛选下拉选项(即。首先选择国家,然后使州下拉菜单仅显示来自选定国家的州)
它受到了来自这里的一个建议的启发(我们也在这里发布了这个解决方案):https://github.com/applegrew/django-select2/issues/22
在forms.py中:
class StateChoices(AutoModelSelect2Field):
queryset = State.objects
def get_results(self, request, term, page, context):
country = request.GET.get('country', '')
states = State.objects.filter(country=country, name__istartswith=term)
s2_results = [(s.id, s.name, {}) for s in states]
return ('nil', False, s2_results)表单字段:
# only include this when you would have a screen where the country
# is preset and would not change, but you want to use it as a search context
country = forms.ModelChoiceField(queryset=Country.objects.all(),
widget=forms.HiddenInput())
state = StateChoices(widget = AutoHeavySelect2Widget(
select2_options = {
'minimumInputLength': 1,
'ajax': {
'dataType': 'json',
'quietMillis': 100,
'data': JSFunctionInContext('s2_state_param_gen'),
'results': JSFunctionInContext('django_select2.process_results'),
}
}))在我们的javascript中:
function s2_state_param_gen(term, page) {
var proxFunc = $.proxy(django_select2.get_url_params, this);
results = proxFunc(term, page, 's2_condition_param_gen');
results.country = $('#id_country').val();
return results;
}https://stackoverflow.com/questions/20586690
复制相似问题