Autocomplete with jQuery and Django

Asked

Viewed 354 times

1

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

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

Valueerror at /consultorio/agenda/ Cannot assign "'Francisco André Filho'": "Agenda.paciente" must be a "Paciente" instance.

py views.

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

ajax view

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 point is to basically inform the patient schedule field the patient’s id, but I can’t do that, I’ve tried several things.

Thank you for your time. Thank you.

1 answer

1

Error happens because you are getting one CharField instead of receiving an instance of Patient.

Remove the paciente from your Forms.py:

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

And manually insert the field into your template paciente.

html template.:

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

I don’t know how jQuery autocomplete works, but it solves the problem being generated.

  • 1

    Hello, thanks for the answer, I made some changes to Forms.py and the patient field I used a modelchoicefield, the previous error is gone, now I have another error: "Make a valid choice... PS: I will test your hint yet.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.