Autocomplete with jQuery and Django

0

Hello, I did a search on the site, but I did not find it, if anyone knows a link that already deals with this subject, please post.

Next, I did an autocomplete in a Django form with jQuery and jQueryUI, in that form I have a foreignkey and I used a text input widget to be able to do the autocomplete that is even working, the problem is when I try to persist this form, see the output with the error.

ValueError at / office / schedule / Can not assign "'Francisco André Filho'": "Agenda.paciente" must be a "Patient" instance.

views.py

def add_agenda(request):
if request.method == 'POST':
    form_agenda = AgendaForm(request.POST)
    if form_agenda.is_valid():
        form_agenda.save()
        return redirect(reverse('paciente:listaagenda'))
    else:
        print(form_agenda.errors)
else:
    form_agenda = AgendaForm()
return render(request, 'paciente/add_agenda.html', {'form_agenda': form_agenda})

view ajax

def get_pacientes(request):
if request.GET:
    q = request.GET.get('term', '')
    pacientes = Paciente.objects.filter(nome__icontains = q)[:20]
    results = []
    for paciente in pacientes:
        paciente_json = {}
        # paciente_json['id'] = paciente.id
        # paciente_json['label'] = paciente.nome
        paciente_json['value'] = paciente.nome
        results.append(paciente_json)
    data = json.dumps(results)
else:
    data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

forms.py

class AgendaForm(forms.ModelForm):
paciente = forms.CharField(widget=forms.TextInput())
class Meta:
    model = Agenda
    fields = ('paciente', 'medico', 'data_consulta', 'horario', 'observacoes')

The question is basically to inform the Patient Agenda field of the patient id, but I can not do this, I have already tried several things.

I thank you for your willingness. Thank you.

    
asked by anonymous 24.08.2015 / 16:18

1 answer

0

The error happens because you are receiving CharField instead of receiving a Patient instance.

Remove paciente from your forms.py:

class AgendaForm(forms.ModelForm):
    # linha removida
    class Meta:
        model = Agenda
        fields = ('paciente', 'medico', 'data_consulta', 'horario', 'observacoes')

And enter the paciente field in your template manually.

template.html:

<input type='text' id='id_paciente' name='paciente' />

I do not know how the jQuery autocomplete works, but this solves the problem that is being generated.

    
30.08.2015 / 20:51