amr_aly

Search in database in Django

Jun 3rd, 2021 (edited)
273
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ############## in views.py
  2. from django.db.models import Q
  3.  
  4. def search_patient(request):
  5.     patient_search = request.GET.get('q') # represent the text input in our form
  6.     search_id = request.GET.get('pid')
  7.  
  8.     if patient_search == '' and search_id == '':
  9.         result_id = Patients.objects.all().order_by('-id')
  10.         table_search = PatientsTable(result_id)
  11.         table_search.paginate(page=request.GET.get("page", 1), per_page=page_no)
  12.  
  13.     elif search_id != None:   # ('pid' in request.GET) and request.GET['pid']:
  14.         result_id = Patients.objects.filter(Q(id=search_id)).all() # | Q(cardid__icontains=patient_search)
  15.         table_search = PatientsTable(result_id)
  16.  
  17.     elif ('q' in request.GET) and request.GET['q'].strip():
  18.         patient_search = request.GET.get('q')
  19.         result_id = Patients.objects.filter(Q(address__icontains=str(patient_search))).all()
  20.  
  21.         table_search = PatientsTable(result_id)
  22.         table_search.paginate(page=request.GET.get("page", 1), per_page=page_no)
  23.     else:
  24.         table_search = PatientsTable(Patients.objects.all().order_by('-id'))
  25.         table_search.paginate(page=request.GET.get("page", 1), per_page=page_no)
  26.          
  27.  
  28.     context = {
  29.         'patient_search': patient_search,
  30.         'table_patient_search':table_search,
  31.     }
  32.     return render(request, 'search/tables.html', context)
  33.  
  34. ######### in tables.html
  35.  
  36.             <form class="form-inline mt-2 mt-md-0 float-left" method="GET" action="{% url 'search:search_patient' %}">
  37.                 <input class="form-control mr-sm-2" type="text" name='q' placeholder="Search Name & Address..."
  38.                  value="{{request.GET.q}}" aria-label="Search">
  39.                 <button class="btn btn-secondary my-2 my-sm-0" type="submit" hidden>Search</button>
  40.             </form>
  41.  
  42.             <form class="form-inline mt-2 mt-md-0 float-left" method="GET" action="{% url 'search:search_patient' %}">
  43.                 <input class="form-control mr-sm-2" type="number" name='pid' placeholder="Search Patient ID..."
  44.                  value="{{request.GET.pid}}" aria-label="Search">
  45.                 <button class="btn btn-secondary my-2 my-sm-0" type="submit" hidden>Search</button>
  46.             </form>
  47.  
  48.  
  49.  
RAW Paste Data