# views.py import requests from django.http import Http404 from django.shortcuts import get_object_or_404 from patients.models import PatientProfile class PatientContextMixin: """ Resolve the patient automatically from: 1) URL kwarg `patient_id` 2) Query param `?patient=` 3) Logged-in user's linked PatientProfile """ patient_kwarg_name = "patient_id" patient_query_param = "patient" def get_patient(self): tenant = getattr(self.request, 'tenant', None) # 1) URL kwarg patient_id = self.kwargs.get(self.patient_kwarg_name) if patient_id: patient = get_object_or_404( PatientProfile, pk=patient_id ) print(patient) return patient # 2) Query param patient_qp = self.request.GET.get(self.patient_query_param) if patient_qp: patient = get_object_or_404( PatientProfile, pk=patient_qp ) print(patient) return patient # 3) Current user's patient profile (self-service) # Adjust attribute access if your relation is named differently. # if hasattr(self.request.user, 'patientprofile'): # pp = self.request.user.patientprofile # if pp and pp.tenant == tenant and pp.is_active: # return pp # If still not found, raise a clear 404 (or you can redirect with a message) # raise Http404("Patient not found or not accessible.")