Django how to automatically render name of patient if exact value matched?

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 do 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()

You’d need to copy those denormalized fields over manually. One way to do it would be:

# ...
 if form.is_valid():
     form.instance.patient_name = form.instance.patient.name
     form.instance.patient_number = form.instance.patient.patient_number
     form.save()
# ...
1 Like