Django Get User by Username Example

Published On: 03/08/2022 | Category: Django


Hi Dev,

In this tute, we will discuss django get user by username example. step by step explain python django get_username. you can understand a concept of how to get user username in django. I explained simply step by step how can i get the username of the logged-in user in django.

So, we are going to learn how to use the get_username() method in Django to fetch the username of a currently logged-in user.

let's see below simple example with output:

Example views.py
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    current_user = request.user.get_username()
    return render(request, 'index.html',{'user':current_user})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tuts-Station.com</title>
</head>
<style>
    p{
        text-align: center;
        margin-top: 100px;
    }
    span{
        font-weight: bolder;
        font-size: larger;
    }
</style>
<body>
   <p><span>Username:</span> {{user}}</p> 
</body>
</html>
Output

I Hope It will help you....