unable to show particular patient's details page

I have a patient list and each patient has a detail page with their information. I want to scan the patient’s face and if the face matches the existing patient’s picture, I went to render to open the details HTML page for that patient. However, I am unsure of what to call to open the details page. After I scan the face i get this error TypeError: join() argument must be str, bytes, or os.PathLike object, not ‘dict’. I have a rough idea that I need to fix in my views.py and utilities.py but just unsure of how.

utilities.py

def is_a_ajax(request):
  return request.headers.get('x-requested-with') == 'XMLHttpRequest'


def get_all_encoded_faces():
    # This function loads all user profile images and encodes their faces
    # Retrieve all patient profiles from the database
    ps = Patient.objects.all()

    # Create a dictionary to hold the encoded face for each user
    encoded = {}

    for p in ps:
        # Initialize the encoding variable with None so like default is none
        encoding = None

        # Load the user's profile image
        face = fr.load_image_file(p.picture.path)

        # Encode the face (if detected)
        face_encodings = fr.face_encodings(face)
        if len(face_encodings) > 0:
            encoding = face_encodings[0]
        else:
            print("No face found in the image")

        # Add the user's encoded face to the dictionary if encoding is not None
        if encoding is not None:
            encoded[p.id] = encoding #i believe this p. should be something else from my models 

    # Return the dictionary of encoded faces
    return encoded

def match_face(img):
    # This function takes an image as input and returns the name of the face it contains
    # Load all the known faces and their encodings
    faces = get_all_encoded_faces()
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())

    # Load the input image
    img = fr.load_image_file(img)
 
    try:
        # Find the locations of all faces in the input image
        face_locations = fr.face_locations(img)

        # Encode the faces in the input image
        unknown_face_encodings = fr.face_encodings(img, face_locations)

        # Identify the faces in the input image
        face_names = []
        for face_encoding in unknown_face_encodings:
            # Compare the encoding of the current face to the encodings of all known faces
            matches = fr.compare_faces(faces_encoded, face_encoding)

            # Find the known face with the closest encoding to the current face
            face_distances = fr.face_distance(faces_encoded, face_encoding)
            best_match_index = np.argmin(face_distances)

            # If the closest known face is a match for the current face, label the face with the known name
            if matches[best_match_index]:
                name = known_face_names[best_match_index]
            else:
                name = "Patient not in system"

            face_names.append(name)

        # Return the name of the first face in the input image
        return face_names[0]
    except:
        # If no faces are found in the input image or an error occurs, return False
        return False

views.py

@login_required
def find_patient(request):
    if is_a_ajax(request):
        picture = request.POST.get('picture')
        _, str_img = picture.split(';base64')
        #decode base 64 into binary format
        decoded_file = base64.b64decode(str_img)

        y = LogPatient()
        y.picture.save('uploadpatient.png', ContentFile(decoded_file))
        y.save()

        result = match_face(y.picture.path)
        patient_exists = Patient.objects.filter(id=result).exists()
        if patient_exists:
            data = Patient.objects.get(id = result)
            y.patient = data
            y.save()

            return render('details.html',{'x': data})
    
        else:
            messages.success(request, ("Face not in database! Please register."))
            return JsonResponse({'success': False})

Side note: When posting code here, you want to enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then the code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of editing your original post for this.)

Can you clarify what you mean by this?

If you want to retrieve the details page, you want to identify the primary key of the patient and use that for the query, which is what it’s looking like you’re trying to do.

Side notes: You’ve got a couple of syntax errors in your views.py.

First, you’re showing your if is_a_ajax condition at the same level of the def find_patient statment - it needs to be indented. (Actually, you’ve got a couple places in your code with apparently improper indentation. I’m surprised you’re not getting errors thrown by your code if this is an actual copy/paste of what you’re trying to run.)

Second, your y.save statement is missing the parens.

hi thank you for formatting it, i will keep in mind to use ``` next time !!!

my syntax is fine on vscode, when I copy pasted it the first line moves and i just spaced it till i got the blockquote view, the y.save() also changed i am not sure why it did that…

I am not sure of how to identify the pk actually, I have tried both id and first_name but i got errors for both and have been stuck for a while

Please fix your post then, so we can see what you’re actually trying to do.

You also need to be more detailed here with your explanation. Please provide more context around what you’re trying to ask. It’s not clear what or where in the code you’re having an issue - it would help if you focused in on where the problem exists rather than just posting everything.

hi i have fixed my post, is it better now? I am new to django and posting on forum so apologies for the mistakes

Yes, the code looks a lot better now. (Don’t worry about the mistakes, we’re here to help.)

So, what specific part of this code are you unsure about? It would really help if you could narrow down what we would need to focus on here.

I am unsure of this part from views.py.

And what are you unsure about?

What are you trying to do here?

How is this not working as you expect?

when i click “view more”, this second page shows up. I want this implemented but with face recognition.

so when I click scan, I want it to bring me the details page

this is what I tried to do in the above code I quoted, but it is not working and I don’t know how to make it work…

Ok, how does your “View more” button work?

this is how my view more button works
html

<td><a href="{%url 'details' x.id %}" class= "btn btn-outline-primary btn-sm">View more</a></td>

views.py

@login_required
def patients_detail(request, id):
    data = get_object_or_404(Patient, pk=id)
    return render(request, 'details.html',{'x':data})

urls.py

urlpatterns = [
    path('patient_details_<int:id>/', views.patients_detail, name='details'),
]

Good - your view is executing a query, then supplying that object in the context for the render.

You’ve got basically the same thing in the code you’ve posted, except you’ve got a couple extra lines:

Why are those lines here?

Other than that, what isn’t working in that code?

these lines are to save the picture from the video element to a log model with the patient’s name. A video I watched on face recognition login mentioned if the place has many similar-looking people, it is good to have a class log because, with this class, we will be able to measure the accuracy of face recognition.

I think the return render line is not working as well because after it scans the face, I get a TypeError: join() argument must be str, bytes, or os.PathLike object, not ‘dict’. I am assuming this is because data is a dict.

Post the complete traceback of the error you’re receiving. (Surrounded between lines of ```, just like you would do with any other code.)

the entire error

Internal Server Error: /match/
Traceback (most recent call last):
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view
    return view_func(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\Desktop\MediMiles_Ver2\MediMiles\mysite\mysite\views.py", line 93, in find_patient
    return render('details.html',{'x': data})
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loader.py", line 15, in get_template
    return engine.get_template(template_name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\backends\django.py", line 33, in get_template
    return Template(self.engine.get_template(template_name), self)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\engine.py", line 175, in get_template
    template, origin = self.find_template(template_name)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\engine.py", line 157, in find_template
    template = loader.get_template(name, skip=skip)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loaders\cached.py", line 57, in get_template
    template = super().get_template(template_name, skip)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loaders\base.py", line 17, in get_template
    for origin in self.get_template_sources(template_name):
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loaders\cached.py", line 70, in get_template_sources
    yield from loader.get_template_sources(template_name)
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loaders\filesystem.py", line 35, in get_template_sources
    name = safe_join(template_dir, template_name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fahir\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\_os.py", line 17, in safe_join
    final_path = abspath(join(base, *paths))
                         ^^^^^^^^^^^^^^^^^^
  File "<frozen ntpath>", line 149, in join
  File "<frozen genericpath>", line 164, in _check_arg_types
TypeError: join() argument must be str, bytes, or os.PathLike object, not 'dict'

Compare your render call to the render call that is working in your “View more” view. How are they different?

oh i dont have a request… i did not realise I removed it

i just added it in and tried it but it still does not bring me the details page, instead brings me to the page that opens when I log in

What is the JavaScript doing with the response being returned?

the below code is done on success…

success: (resp) => {
                            console.log(resp)
                            window.location.href = window.location.origin //reload the page
                        },

Your view is rendering a page - what is your JavaScript doing with that response?