Hi all,
I have a list of patients and doctors. For each patient I set which doctor can see patient data
until now I have this example:
@login_required(login_url='adminlogin')
@user_passes_test(is_admin_or_doctor)
def update_patient_data_view(request,pk):
patient=models.Patient.objects.get(id=pk)
user=models.User.objects.get(id=patient.user_id)
....
....
render(request,'hospital/admin2patient/admin_update_patient_data.html',context=mydict)
where
def is_admin_or_doctor(user):
return user.groups.filter(name='ADMIN').exists() or user.groups.filter(name='DOCTOR').exists()
the patient model have this parameter:
assignedDoctorId = models.ManyToManyField(Doctor,default=None)
I would like check if id of doctor logged is in the “assignedDoctorId” list before let show patient data to him
many thanks in advance
best regards
What is the relationship between Doctor
and User
?
Doctor is a user which belong to a group
for example when I add new doctor I have this model:
from django.contrib.auth.models import User
class Doctor(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
...
and in view:
def doctor_signup_view(request):
userForm=forms.DoctorUserForm()
doctorForm=forms.DoctorForm()
mydict={'userForm':userForm,'doctorForm':doctorForm}
if request.method=='POST':
userForm=forms.DoctorUserForm(request.POST,prefix=userForm)
doctorForm=forms.DoctorForm(request.POST,request.FILES,prefix=doctorForm)
if userForm.is_valid() and doctorForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
doctor=doctorForm.save(commit=False)
doctor.user=user
doctor=doctor.save()
my_doctor_group = Group.objects.get_or_create(name='DOCTOR')
my_doctor_group[0].user_set.add(user)
return HttpResponseRedirect('doctorlogin')
return render(request,'hospital/doctorsignup.html',context=mydict)
Ok, so Doctor
is a profile model attached to User
This makes the basic query something like:
patient.assignedDoctorId.filter(user=user).exists()
This query will return True
or False
depending upon whether the currently-logged-in user is a member of the Patient.assignedDoctorId
relationship. (I suggest you experiment with this in the Django shell to become comfortable with what it’s doing.)
You have a couple different ways to use this, depending upon how sophisticated you want to get.
-
Test this in your view after the queries for patient
and user
. (The user_passes_test
decorator does not accept additional parameters.)
-
Create a custom decorator to replace user_passes_test
that can accept additional parameters such as request
or pk
.