【问题标题】:Django-Select2 Heavy WidgetDjango-Select2 重型小部件
【发布时间】:2020-08-07 06:08:45
【问题描述】:

我第一次尝试实现 Django-select2....我参考了他们的 documentation 和一些堆栈溢出解决方案来实现它....我设法让 ajax 功能正常工作,我也是能够选择多个选项...但是,当我提交并验证表单时,我收到类似错误 ->“选择一个有效的选择。123456 不是可用的选择之一。

我不明白我做错了什么......

这是我的表格。

class MyCustReqForm(forms.ModelForm):
    initial_customer = forms.MultipleChoiceField(
            widget=HeavySelect2MultipleWidget(data_view='customer_ajax',
                                              attrs={'data-minimum-input-length': 4, 'delay':200},
                                              model=Customer),

    )
    end_customer = forms.MultipleChoiceField(
            widget=HeavySelect2MultipleWidget(data_view='customer_ajax',
                                              attrs={'data-minimum-input-length': 4, 'delay':200},
                                              model=Customer),

    )

    class Meta:
        model = Workflow_Customer
        fields = [ 'initial_customer', 'end_customer' ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['initial_customer'].widget.attrs.update({'style': 'width:100%', 'data-placeholder': 'Select Customer'})
        self.fields['end_customer'].widget.attrs.update({'style':'width:100%', 'data-placeholder':'Select end customer'})

和 customer_ajax 视图调用下面的函数...

def customer_select2(request):
    term = request.GET.get("term", None)
    if term:
        res = list(Customer.objects.filter(Q(customer_number__contains=term) | Q(customer_name__contains=term)).values('id', 'customer_number', 'customer_name'))[:10]
    if res:
        result = [{'id': value['id'], 'text': value['customer_number'] + ' ' + value['customer_name'] } for index, value in enumerate(res)]

        return JsonResponse({'err': 'nil', 'results': result}, safe=False)

return JsonResponse(data={'success': False, 'errors': 'No mathing items found'})

当我在调试模式下检查时。我发现选择是空的...

感谢您的快速帮助...如果可能,请提供一个完整的示例来解释如何定义表单和用于 Ajax 功能的视图...

【问题讨论】:

    标签: python django jquery-select2 django-select2


    【解决方案1】:

    发生这种情况是因为当您发送表单时没有初始选项,因此所选选项未通过验证。当您发送表单时,类 MyCustReqForm 被初始化,此时您必须执行请求以获取表单字段的选择。该选项必须包含您选择的选项。例如:

    self.fields['customer'].choices = call_to_end_point()

    请求'GET'时没有问题,但请求中'POST'需要有一些基本选项。

    PD:对不起我的英语

    【讨论】:

      猜你喜欢
      • 2016-11-11
      • 2023-04-10
      • 2022-08-09
      • 2021-12-31
      • 2021-09-06
      • 2017-12-30
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      相关资源
      最近更新 更多