In this Django tutorial, we are going to learn about “Python Django get“. We will also cover some topics like- Python Django get post data, Python Django get_or_create, etc. Here is the complete list of topics that we will discuss in this tutorial.
- Python Django get
- Python Django get request parameters
- Python Django get_or_create
- Python Django get post data
- Python Django get URL parameters
- Python Django get settings variable
- Python Django get current URL
- Python Django get_user_model
- Python Django get_username
- Django Python get URL
- Python Django request.user.id
- Django Python get user
- Django Python get user id
Python Django get
In one of our previous tutorials, we discussed “Python Django filter“. In which, we discuss how to use different methods like filter(), exclude(), etc to fetch a subset from the complete QuerySet.
Now, these methods return a QuertSet of objects as result. Now, even if there is only one object in the QuerySet, they will return the QuerySet with one object.
So in this section, we will learn how to fetch a single object from the QuerySet, and for this implementation, we will use the get() method in Django.
The get() method in Django returns a single object that matches the given lookup parameter. While using the get(), we should always use the lookups which are unique like primary keys or fields in unique constraints.
Let’s take a simple example for its execution.
(InteractiveConsole)
>>>
>>> from myApp.models import Customer
>>>
>>> q = Customer.objects.get(pk=2)
>>>
>>> print(q)
- In the above example, we are using the Customer model and for the execution, we are using the Django shell.
- So, first, we have imported the Customer model from our application. After this, we are creating a QuerySet but this time we are using the get() method.
- And in the get() method, we are defined pk=2 as a lookup parameter. So this QuerySet will return an object whose primary key is defined as 2.
Now, if we use the print() statement to print the Queryset, it will return the object.
Now, we should always use the get() carefully as if the QuerySet doesn’t find any object then, it will return a Model.DoesNotExist exception. And if the QuerySet finds more than one object then, it will return the Model.MultipleObjectsReturned exception. Both the errors are shown in the example below.
Python Django get_or_create
Now, wherever we are working on a data-driven application using Django, we have to make sure that there are no duplicate records in our application model.
Generally, first, we need to write a logic to check the existence of an object and then, we need to save the object based upon its existence. But, Django simplifies this task by providing a method.
In Django, we can use the get_or_create() method to check the existence of an object and creates an object based upon its existence. This method has 2 parameters, first is “defaults” which are used to set default values for fields.
And second is “kwargs” which is used to define keyword arguments. And this method checks the object based upon the “kwargs” argument.
Now, this method returns a tuple (object, created), where the “object” is a created or retrieved object. And “created” is a boolean value based upon the fact of whether an object is created or not.
So, whenever a keyword argument is passed to the get_or_create() method (excepts for defaults). It will call the get() method to retrieve an object, and if the object is found then, the method will return the object name and False value in a tuple. Let’s have an example for this implementation.
(InteractiveConsole)
>>>
>>> from myApp.models import Customer
>>>
>>> q = Customer.objects.get_or_create(
... name='Cortney Davidsson',
... country='United Kingdom'
... )
>>>
>>> print(q)
In this example, we are using the get_or_create() method to create or retrieve an object, based upon the given name and country values. Now, if the object is already there in the database then, it will return a tuple as (object_name, False). Where object_name is the name of the object and False represents objects is not created.
When this method is unable to retrieve the object with given arguments then, it will create a new object with given values. And after creation, it will return the object name and True in the tuple. Let’s have an example of creating a new object using the get_or_create() method.
(InteractiveConsole)
>>>
>>> from myApp.models import Customer
>>>
>>> q = Customer.objects.get_or_create(
... name='Randy Briston',
... address='93 Coleman Street',
... country='United States',
... city='Houston'
... )
>>>
>>> print(q)
In this example, we have passed the values for a new object in the get_or_create() method. Now, as the method will be unable to fetch the object, it will create a new one with the given values. Here is the output of this example.
Python Django get_username
In this section, we are going to learn how to use the get_username() method in Django to fetch the username of a currently logged-in user.
So, the get_username() method is available for the User model class, and it returns the username of the user. And it is also recommended to use this method instead of using the username attribute directly.
Let’s understand how we can use this get_username() method with the help of an example. And in the example, we will demonstrate how to print the username in your Django template.
First, we will create a function-based view to get the username, and to fetch the username, we will use this method. Here is the code for the views.py file.
from django.shortcuts import render
def index(request):
current_user = request.user.get_username()
return render(request, 'index.html',{'user':current_user})
In the above code, we have defined a view with the name index. And in the view, we are using the request.user.get_username() method to store username value in the current_user variable. After this, we are sending the variable to the index.html page.
Next, we will add the following code to the index.html page.
<!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>Python Guides</title>
</head>
<style>
p{
text-align: center;
}
span{
font-weight: bolder;
font-size: larger;
}
</style>
<body>
<p><span>Username:</span> {{user}}</p>
</body>
</html>
On the index.html page, we will simply use the variable in the double curly braces to print the username. Here is the final result of this example.
Read How to setup Django project
Django Python get user
In this section, we will learn how to get user data in Django. And we will also understand how we can use the data to display in our template.
Django, by default, provides an authentication system, and we can easily extend this system to use it for our application. It also provides a default model to store data related to registered users. The name of the model is User, and some of its fields are as follows.
- username: stores the username of a user
- first_name: stores the first name of a user
- last_name: stores the last name of a user
- email: stores the email address of the user
- password: It is used to store the hash of the password, and metadata about the password.
- groups: It stores many-to-many relationships to the Group model.
- last_login: It stores a DateTime value related user’s last login.
- date_joined: It also stores a DateTime value representing the date and time when the user was created.
Next, we will understand how we can fetch these values in Django and also use them in our Django template. And, first, we need to create a view that fetches these values and returns them to the template.
Here is an example of the view.py file, where we fetching these values and send them to the index.html page.
from django.shortcuts import render
def index(request):
user = {
'fullname' : request.user.get_full_name(),
'firstname' : request.user.first_name,
'lastname' : request.user.last_name,
'email' : request.user.email,
'last_login': request.user.last_login,
'account_created': request.user.date_joined
}
return render(request, 'index.html',{'user':user})
In the above code, we have created a function-based view with the name “index“. And in this view, we have created a dictionary with multiple keys and values. Now, the data related to the current login user is in the request object.
So, we are using request.user to get the data related to the current login user. Here is the list of data that we are fetching.
- request.user.get_full_name() returns the full name of the user.
- request.user.first_name returns the first_name value from the User model.
- request.user.last_name returns the last_name field from the User model.
- request.user.email returns the email field from the User model.
- request.user.last_login returns the last_login field from the User model.
- request.user.date_joined returns the date_joined field from the User model.
In the end, we are returning the dictionary to the index.html page. And in the index.html page, we can use these values to display them. Here is the code for the index.html page.
<!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">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>Python Guides</title>
</head>
<body>
<br>
<div class="container w-50">
<div class="card bg-light text-dark">
<h5 class="card-header bg-dark text-light">User Info</h5>
<div class="card-body">
<div class="card-text"><b>Full Name:</b> {{user.fullname}}</div>
<div class="card-text"><b>First Name:</b> {{user.firstname}}</div>
<div class="card-text"><b>Last Name:</b> {{user.lastname}}</div>
<div class="card-text"><b>User Email:</b> {{user.email}}></div>
<div class="card-text"><b>Last Login:</b> {{user.last_login}}</div>
<div class="card-text"><b>Account Created On:</b> {{user.account_created}}</div>
</div>
</div>
</div>
</body>
</html>
In the template, we are using the Bootstrap classes to create an information card. And in the card, we are using dictionary values to get the required result. Now, if we move to the mapped URL, we will get the following result.
Read Python Django get admin password
Django Python get user id
For each entry in the User model, Django automatically assigns a primary key id for that entry. Now, in this section, we will learn how to get this primary key id for a user.
To fetch the user id, we will use the request.user object as it returns the information related current login user. To get the id, we will simply use request.user.id as it will return the user id for the current user. Here is the viewa.py file for this example.
from django.shortcuts import render
def index(request):
user_id = request.user.id
return render(request, 'index.html',{'user_id':user_id})
In the above code, we are using the request.user.id to store the value of user id in the user_id variable. After this, we are sending the variable to the index.html page where we use this to get the id.
Python Django get current URL
In this section, we will discuss how to get the current URL of a page in our Django template.
Now, the complete URL consists of 3 things, the first is the Domain, the second is the path, and the third is the querystring. And we will see how to fetch these parts of a URL in Django.
In Django, we can easily get the URL using some template tags. For this let’s take an example. And we have added the following code in the views.py file.
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def home(request):
return render(request, 'home.html')
In the above code, we have simply created 2 function-based views which refer to the HTML pages. Next, for the demonstration, we will use the home.html page with the following code.
Note: To show the difference between path and querystring, we have passed a querystring to the home page using URL.
<!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">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>Python Guides</title>
</head>
<body>
<br>
<div class="container w-50">
<div class="card bg-light text-dark">
<h5 class="card-header bg-dark text-light">Python Django get current URL</h5>
<div class="card-body">
<div class="card-text"><b>Current Page Path: </b>{{request.path}}</div>
<div class="card-text"><b>Current Page Path with Querystring: </b>{{request.get_full_path}}</div>
<div class="card-text"><b>Current Domain, Path and Querystring: </b>{{request.build_absolute_uri}}</div>
</div>
</div>
</div>
</body>
</html>
Now, in the home age, we have used 3 tags and the information related to these tags is as follows.
- {{ request.path }}: This will return the current page path.
- {{ request.get_full_path }}: This will return the current page path with querystring.
- {{ request.build_absolute_uri }}: This will return domain, page path and querystring together.
Now, if we open the home page, we will get the following result.
Read Difference between app and project in Django
Python Django get URL parameters
In the previous section, we discussed how to get different parts of a URL. Now, in this part, we will discuss how to fetch the URL parameters in Django. And we will also see how to display them in your template. But, before that, we should know about the GET method.
GET is an HTTP method in Django that encapsulates the data in a string and utilizes it to construct a URL. The URL includes the data keys and values as well as the address to which the data must be transmitted.
Python Django get request parameters
In Django, to get the URL parameters, we have to use the request.GET method. So, first, we will use this method to fetch and store the value of parameters in a variable. After this, we will return the variable to an HTML page. Let’s understand this with the help of an example.
For the example, first, we will use the index page which will have the link to the home page. And with the home page URL, it will also pass a message as a parameter.
Now, on the home page, we will print the parameter message. Here is the code for the views.py file.
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def home(request):
msg=request.GET.get('message')
return render(request, 'home.html',{'msg':msg })
For the view of the home page, we are using the request.GET.get(‘message’) method. And it will store the value of “message” in the “msg” variable. After this, we are just returning the “msg” to the home.html page.
Here is the code for the index.html page.
<!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">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>Python Guides</title>
</head>
<body>
<br>
<div class="container w-50">
<div class="card bg-light text-dark">
<h5 class="card-header bg-dark text-light">Index Page</h5>
<div class="card-body">
<div class="card-text"><a href="{% url 'home' %}?message=Hi Welcome to Python Guides">Link To Home Page</a></div>
</div>
</div>
</div>
</body>
</html>
On this page, we have a link to the home page and with the URL, we have passed a message.
Now, here is the code for the home.html page.
<!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">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>Python Guides</title>
</head>
<body>
<br>
<div class="container">
<div class="card bg-light text-dark">
<h5 class="card-header bg-dark text-light">Home Page</h5>
<div class="card-body">
<div class="card-text"><b>URL parameters: </b>{{msg}}</div>
</div>
</div>
</div>
</body>
</html>
On the home, we are simply using the “msg” variable to display the message value. In the end, we got the following result.
Python Django get post data
In this section, we will discuss how to fetch the POST data in Django. But before that, we should know what is POST and what is POST data in Django.
The POST is also an HTTP method that is used to deal with forms in Django. The POST method collects the form data, encrypts it for transmission, transmits it to the server, and then receives its response.
Now, for the implementation of this task, we will create a form to save some data in a model. The form will use the POST method, and we will try to fetch the form data on the server-side.
So, first, we will create a form on the home.html page, and here is the code for this implementation.
<!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">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>Python Guides</title>
</head>
<body>
<br>
<div class="container w-50">
<form action="success/" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" class="form-control" id="first_name" placeholder="Enter First Name">
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" class="form-control" id="last_name" placeholder="Enter Last Name">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="number" class="form-control" id="age" placeholder="Enter Your Age">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
On the above page, we have created a form with the POST method and there are 3 fields in the form. Also, we are using the Bootstrap framework and its classes to build this form.
Next, we will create a view for this home.html page, and here is the code for the views.py file.
from django.shortcuts import render
from myApp.models import Students
def home(request):
if request.method=='POST':
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
age = request.POST.get("age")
data = Students(first_name,last_name,age)
data.save()
return render(request, 'home.html')
def success(request):
return render(request, 'success.html')
- So, in the home view, we are using the request.POST.get() method to fetch the values of first_name, last_name, and age fields.
- And then, we are storing these values into the variable. After this, we are creating an object for Students model using these variables.
- In the end, we are using the save() method to store the data in the database.
Now, we have also created a success page, so if the data is stored successfully then, the success page will be opened.
Now, it’s time to run the development server, open the home page and submit a record.
Python Django get_user_model
In Django, we have a setting related to the User model with the name AUTH_USER_MODEL. This setting represents the model to be used for the User.
Now, if this AUTH_USER_MODEL setting is changed to some other user model then we cannot use the User model class directly.
So, instead of referring to the User model class, we can use the get_user_model() method. The get_user_model() method returns the currently active user model. Let’s take an example and understand how to use this get_user_model() method.
Again, for this execution, we will use the Django shell. Here is the execution example.
(InteractiveConsole)
>>>
>>> from django.contrib.auth import get_user_model
>>>
>>> get_user_model()
<class 'django.contrib.auth.models.User'>
>>>
>>> user = get_user_model()
>>> user.objects.all()
<QuerySet [<User: Ross>, <User: Margit>, <User: Misty>, <User: Mycah>, <User: Scotti>]>
In the example, we first, we have imported the get_user_model() method from django.contrib.auth. After this, we simply printed the method to show the model class which it was using.
As we didn’t change the AUTH_USER_MODEL setting, it is using the User model. Next, we are using this method to create a QuerySet of all objects. And in the end, we printed the QuerySet.
Here is the screenshot of this execution.
Read: Python Django group by
Python Django get settings variable
In Django, we have a settings.py file, this file contains all the configurations related to our Django installation. This settings.py file itself is a python module with module-level variables.
Now, in this section, we will learn how to fetch the values of these settings variables in Django.
For this task, first, we need to import the settings module, and then, we can access the variables using settings.VARIABLE. Where VARIABLE is the name of the settings variable, and it should always be in capital letters.
Let’s understand this implementation by implementing it and for implementation, we are using Django shell.
(InteractiveConsole)
>>>
>>> from django.conf import settings
>>>
>>> print('Time Zone: ',settings.TIME_ZONE)
Time Zone: UTC
>>>
>>> print('Language Code: ',settings.LANGUAGE_CODE)
Language Code: en-us
>>>
In this example, first, we have imported the settings module from the django.conf. After this, we are using the print() statement to print two settings variables. First is time zone using “settings.TIME_ZONE” and second is language code using “settings.LANGUAGE_CODE“.
Here is the screenshot of the above example.
Read: Django for loop
In this Django tutorial, we discussed “Python Django get“. We also covered some topics like- Python Django get post data, Python Django get_or_create, etc. Here is the complete list of topics that we have covered in this tutorial.
- Python Django get
- Python Django get request parameters
- Python Django get_or_create
- Python Django get post data
- Python Django get URL parameters
- Python Django get settings variable
- Python Django get current URL
- Python Django get_user_model
- Python Django get_username
- Django Python get URL
- Python Django request.user.id
- Django Python get user
- Django Python get user id
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.