Why isn’t working here? The select works fine, but when i try to sent the form, shows that form is invalid.
View.py:
class EntradaAutocomplete(View):
def get(self, request, *args, **kwargs):
term = request.GET.get('term', '')
queryset = Entrada.objects.filter(id__icontains=term)[:50] # Filtra e limita os resultados
results = []
for entrada in queryset:
results.append({
'id': entrada.id,
'text': entrada.id})
return JsonResponse({'results': results}, safe=False)
form.py:
class LocalizacaoProntuarioMultiplosCreateForm(forms.Form):
data_cadastro = forms.DateTimeField(
widget=forms.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}),
initial=(timezone.now() - timedelta(hours=3)).strftime('%Y-%m-%dT%H:%M'),
label="Data",
required=True
)
entradas = forms.ModelMultipleChoiceField(
queryset=Entrada.objects.all()[:10],
widget=forms.SelectMultiple(attrs={'class': 'form-control select2'}),
label="Entradas",
required=True
)
def __init__(self, *args, **kwargs):
super(LocalizacaoProntuarioMultiplosCreateForm, self).__init__(*args, **kwargs)
html/script:
<script type="text/javascript">
$(document).ready(function() {
// Inicializa o Select2 com AJAX
$('.select2').select2({
ajax: {
url: "{% url 'entrada_autocomplete' %}",
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term // Termo de busca
};
},
processResults: function (data) {
return {
results: data.results
};
},
cache: true
},
minimumInputLength: 0,
placeholder: 'Digite para pesquisar',
multiple: true,
allowClear: true
});
});
</script>