Python Django random number

In this Django tutorial, we will learn about Python Django random numbers. And we will also see different examples related to a random number in Django. These are the following topics that we are going to discuss in this tutorial:

  • What is the random number
  • Functions to generate random number
  • Django random number in view
  • Django random number in template

What is the random number

In this section, we’ll learn what a random number is and how to use the random concept in Django.

A random number is a number selected at random from a collection of limited or unlimited numbers with no clear pattern that can be predicted. Almost all of the numbers in the pool are unrelated to one another. The collection of numbers, on the other hand, may follow a specified distribution.

For example, the weight distribution of kids at a school tends to follow a normal distribution around the median weight. If a student’s weight is chosen at random, it has a better chance of being close to the median weight than being classified as overweight or underweight.

The random number generators assume that the generated numbers are independent of one another and that they will be evenly distributed across the entire wide range of possible values.

Random numbers are used in a variety of Django applications, including cryptography, password generation, lottery number generation, random generation of stories, statistical sampling, entirely randomized design, computer simulation, and any other application where unpredictable random numbers are desired.

Read: Convert HTML page to PDF using Django

Functions to generate random number

In this section, we’ll go through some of the most often used Python functions for generating random numbers. The random module in Python defines a set of functions for generating and manipulating random integers.

  • choice() function: The Python programming language has an inbuilt method called choose() that returns a random item from a list, tuple, or string.
  • randrange(start, end, step): The random module has a function called randrange that may produce random integers from a specific range while also allowing a specific space range.
  • random(): This function generates a float random integer that is less than 1 and bigger than or equal to 0.
  • uniform(lower-limit, upper-limit): This function generates a floating-point random number between the values specified in the inputs. It takes two arguments: a lower limit which is included in the generation and an upper limit which is not included in the generation.
  • randint(start, stop): This method returns an integer number selected element from the specified range. It includes both start and stop number.

Read: Get URL parameters in Django

Django random number in view

In this section, we’ll learn to generate random numbers using the view in Django. So, we clarify our concepts by using various examples.

I’ll show you the project’s urls.py file before I start the demonstration. As it remains the same in all of the examples.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home.urls'))
]

This means that when you open your project in the browser, it will take you to your home.urls.

Now, see the home’s urls.py file:

from django.urls import path, include
from home import views

urlpatterns = [
    path('', views.home, name='home')
]

It moves to the views.py file of the home app.

Example #1

The views.py file:

from django.http import HttpResponse
import random

# Create your views here.
def home(request):
    my_list = [1, 2, 3, 4, 5, 6]
    rand_num = random.choice(my_list)
    html = "<html><body><b>Random Number:</b> %s</body></html>" % rand_num
    return HttpResponse(html)
  • In the above example, we have imported the random method. Next, we have created a view with the name home.
  • In this view, we are using the random.choice() method to get the random number from the list and store the value in a rand_num variable. And then, we are using the variable to return the random number value as an HTTP response.

Now, if we run the development server, we will get the following output. Each time we’ll refresh the browser page we’ll get a different number.

django random number in view
Random Number
python django random number in view
Random Number

Example #2

The views.py file:

from django.http import HttpResponse
import random

# Create your views here.
def home(request):
    rand_num = random.randrange(1, 100)
    html = "<html><body><b>Random Number:</b> %s</body></html>" % rand_num
    return HttpResponse(html)
  • In this example, we have imported the random method. Next, we have created a view with the name home.
  • In this view, we are using the randrange() method to get the random number from the specified range and store the value in a variable. And then, we are using the variable to return the random number value as an HTTP response.

The output is as follow:

random number in view using django
Random Number

Example #3

The views.py file:

from django.http import HttpResponse
import random

# Create your views here.
def home(request):
    rand_num = random.random()
    html = "<html><body><b>Random Number:</b> %s</body></html>" % rand_num
    return HttpResponse(html)

In this view, we are using the random() method to get the random number and store the value in a variable. And then, we are using the variable to return the random number value as an HTTP response.

The output is as follow:

random number using view in django
Random Number

Read: How to get data from get request in Django

Django random number in template

In this section, we’ll learn to generate random numbers using the template in Django. We can generate random numbers using template tags in two ways:

  • Using built-in template filter
  • Using custom tag

Using built-in template filter

In Django, we have a built-in filter reference random, which returns a random item from the given series. It works the same as a python choice() method.

Template filter random:

{{ value | random }}

So, we use diverse examples to clarify our concepts.

Before I start the demonstration, I’ll show you the project’s urls.py and app’s urls.py files. As it remains the same in all of the examples.

The project’s urls.py file:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls'))
]

This means that when you open your project in the browser, it will take you to your myapp.urls.

Now, see myapp urls.py file:

from django.urls import path, include
from myapp import views

urlpatterns = [
    path('', views.myapp, name='myapp')

It moves to the views.py file of the myapp app.

Example #1

The views.py file:

from django.shortcuts import render


# Create your views here.

my_list = ['abc','def','ghi','abcd','as$25l6']

def myapp(request):    
    return render(request, 'home.html', {'my_list':my_list})

Firstly, we will create a view that will redirect to an HTML page. In the views.py file, we define the list and redirect the list value to the home.html page.

The home.html file:

<!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>PythonGuides</title>
</head>
<body>
    <p>
        <b> Random Generator : </b> {{my_list|random}}    
    </p> 
</body>
</html>

Next, we will add the “random” filter to the home.html file to get the result.

python django random number in template
Random Generator
django random number in template
Random Generator

Example #2

The views.py file:

from django.shortcuts import render

# Create your views here.

my_series = ['124dsvb@#','def%^569$#','ghi496o)%@5','897563214','as$25l6']

def myapp(request):    
    return render(request, 'home.html', {'my_series':my_series})

Firstly, we will create a view that will redirect to an HTML page. In the views.py file, we define the list and redirect the list value to the home.html page.

The home.html file:

<!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>PythonGuides</title>
</head>
<body>
    <p>
        <b> Random Generator : </b> {{my_series|random}}    
    </p> 
</body>
</html>

Next, we will add the “random” filter to the home.html file to get the result.

random number using template in django
Random Number

Read Compare two integers in Python Django

Using Custom tag

Now, we’ll learn to generate a random number using the custom tag. So firstly we have to create a custom tag. So, let’s learn the concept from different examples.

Example #1

Here I create a custom_tag.py file under templatetags directory under the app’s directory.

The custom_tag.py file:

import random
from django import template

register = template.Library()

@register.simple_tag
def random_int(start, stop):
    return random.randint(start, stop)

Here I create a tag with the name random_number. And after this, random.randint() method is used to generate a random number between the start and stop.

The views.py file:

from django.shortcuts import render

# Create your views here.

def myapp(request):    
    return render(request, 'home.html')

Firstly, we will create a view that will redirect to an HTML page. In the views.py file, we’ll define a code to redirect to the home.html page.

The home.html file:

<!Load Custom Tag>

{%load custom_tag%}

<!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>PythonGuides</title>
</head>
<body>
    <p>
        <b> Random Generator : </b> {% random_number 100 1000%}    
    </p> 
</body>
</html>

Now, at the home.html file, I’ll first load the tag name as custom_tag.

Command to load tag:

{% load <tag_name> %}

Next, I use the random_number tag which I created earlier. Here I pass 100 and 1000 as a start and stop value.

Now, if we run the development server, we will get the following output.

django random number using custom tag
Random Number
python django random number using custom tag
Random Number

Example #2

Here I create a random_tag.py file under templatetags directory under the app’s directory.

The random_tag.py file:

import random
from django import template

register = template.Library()

@register.simple_tag
def rand_num(lower_limit, upper_limit):
    return random.uniform(lower_limit, upper_limit)

Here I create a tag with the name rand_num. And after this, random.uniform() method is used to generate a random number between the lower and upper limits.

The views.py file:

from django.shortcuts import render

# Create your views here.

def myapp(request):    
    return render(request, 'random.html')

Firstly, we will create a view that will redirect to an HTML page. In the views.py file, we’ll define a code to redirect to the random.html page.

The random.html file:

<!Load Custom Tag>

{%load random_tag%}

<!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>PythonGuides</title>
</head>
<body>
    <p>
        <b> Random Generator : </b> {% rand_num 10 20%}    
    </p> 
</body>
</html>

Now, at the random.html file, I’ll first load the tag name as random_tag. Next, I use the rand_num tag which I created earlier. Here I pass 10 and 20 as a lower and upper limit.

Now, if we run the development server, we will get the following output.

django python random number generator in templates
Random Number

You may also like to read the following Django tutorials.

In this Django tutorial, we discussed Python Django random numbers. Also, we discussed the following lists of topics:

  • What is the random number
  • Functions to generate random number
  • Django random number in view
  • Django random number in template