Access a json object form views django

i have tired a number of suggestions but need help.

in my views.py

def findnamesurname(request):
    username = request.POST['username']
    obj = Users.objects.all().values("first_name")
    return HttpResponse(obj)

in my json

 $.ajax({
            url: "/findnamesurname",
            method: "POST",
            data: {
                'csrfmiddlewaretoken': '{{csrf_token}}',
                "username": data,
            },

            success: function (data) {
            
            alert(JSON.stringify(data))

      }
        })
    }

I want to get first name please in a viable I get the following when i alert: {'first_name': 'Daniel'}

How to access this object please.

Not sure I got your question right. But if you want to retrieve the first and last name of a user by its username, you first need to filter/search that user in the database. Then you can send the response by using JsonResponse.

from django.http import JsonResponse
from django.http import Http404


def findnamesurname(request):
    username = request.POST["username"]
    try:
        user = YourUserModel.objects.get(username=username).values(
            "first_name", "last_name"
        )
    except YourUserModel.DoesNotExists:
        raise Http404

    return JsonResponse(user)
Back to Top