Praveen
Praveen

Reputation: 374

Django-Select2 Heavy Widget

I was trying to implement Django-select2 for the first time.... I referred their documentation and some of the stack overflow solutions to implement it.... I managed to get ajax functionality work properly, also i am able to select multiple choices... however when I submit and validate the form, I am getting error like -> "Select a valid choice. 123456 is not one of the available choices."

I am not understanding what I am doing wrong....

here is my form.

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'})

and customer_ajax view calls below function...

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'})

when I checked in debug mode. I found that choices are empty... screenshot of debug

I appreciate for the quick help... if possible, please provide one complete example which explains how form defined and view used for Ajax function...

Upvotes: 4

Views: 1807

Answers (2)

Deepak Tripathi
Deepak Tripathi

Reputation: 3243

Solution is to write custom clean methods so this way you are defining your own validations for a field thus overriding django form validation for the choice field.

def clean_initial_customer(self):
  choices = self.cleaned_data["initial_customer"]
  # write your custom logics and remove any errors

let me know if you find some issue in implementing the same.

Upvotes: 0

Jhon Frederick
Jhon Frederick

Reputation: 15

That happens because when you send your form there aren't initial choices so the chosen option don't pass the validation. When you send your form, the class MyCustReqForm is initialized and in that moment you must do a requets to get choices of your form field. That choices must containt your chosen option. For example:

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

When the request is 'GET' there isn't problem, but in the request 'POST' is necessary to have some basic options.

PD: Sorry for my english

Upvotes: 1

Related Questions