Home > Software design >  Django how to automatically render name of patient if exact value matched?
Django how to automatically render name of patient if exact value matched?

Time:02-19

I have an forms for set appointment. see the picture enter image description here

If any patient fill the mobile number and he already exist in my database then I want to automatically render his name in my patient name fields. Suppose I have an patient name Jhone and his mobile number 123456. If Jhone input his mobile number then I want his name will be automatically render in my patient name fields. How to that in djago? here is my code:

models.py

class Patient(models.Model):
       patient_name = models.CharField(max_length=150)
       patient_number = models.CharField(max_length=50, blank=True, null=True) 

class Appointment(models.Model):
       patient = models.ForeignKey(
       Patient, on_delete=models.CASCADE, blank=True, null=True)
       patient_name = models.CharField(max_length=100, blank=True, null=True)
       patient_number = models.CharField(max_length=50, blank=True, null=True)

views.py:

 if form.is_valid():
     form.save()
     messages.add_message(request, messages.INFO,f'Appoinment added sucessfully for 
       {form.instance.patient_name}')
     return redirect('hospital:add-appointment')
 else:
    form = AppointmentForms()

CodePudding user response:

Method 1: Any Data Size

  1. Use JavaScript(JS) onchange to detect when the user inputs and leaves the Mobile Number input.
  2. Use an Ajax request in the JS to send that to the server (the views.py in your Django)
  3. The view function then tries to find the Patient based on the Mobile number and returns a JsonResponse back with the Patient info
  4. The JS receives that, and targets the Patient Name input via it's id, changing the value of the input to the patient's name.

Method 2: Small Data
If you don't have too many patient records, this method avoids Ajax altogether.

  1. Send a dictionary of ALL patient's names and matching Mobile numbers when the page is rendered.
  2. Use JavaScript(JS) onchange to detect when the user inputs and leaves the Mobile Number input.
  3. Use the JS to grab the number, match it to the mobile number and targets the Patient Name input via it's id, changing the value of the input to the patient's name.

Bottom Line
Django is server-side, and what you're asking must be done done on the client side, meaning JavaScript.

  • Related