I have an forms for set appointment. see the picture
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
- Use JavaScript(JS) onchange to detect when the user inputs and leaves the Mobile Number input.
- Use an Ajax request in the JS to send that to the server (the views.py in your Django)
- The view function then tries to find the Patient based on the Mobile number and returns a JsonResponse back with the Patient info
- 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.
- Send a dictionary of ALL patient's names and matching Mobile numbers when the page is rendered.
- Use JavaScript(JS) onchange to detect when the user inputs and leaves the Mobile Number input.
- 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.