I’ve often found myself needing to generate random numbers in Django applications. Python’s built-in random module makes this task simple, and integrating it within Django views or models is simple once you understand the basics.
In this article, I’ll walk you through different ways to generate random numbers in Django, sharing practical examples that you can use right away.
Let’s get in!
Methods to Generate Random Numbers in Django
In real-world applications, random numbers serve many purposes. For example, in an e-commerce website based in the USA, you might want to assign a random discount code to customers or generate a random verification number for two-factor authentication.
Understanding how to generate random numbers properly ensures your application behaves reliably and securely. Let’s dive into some methods I use regularly.
Read Create a Card with a Button in Django
1: Use Python’s random.randint() in Django Views
The simplest way to generate a random integer within a specific range is by using the randint() function from Python’s random module.
Here’s a quick example of how I generate a random 6-digit number in a Django view, which could be used as a one-time password (OTP) for user verification:
# views.py
import random
from django.http import HttpResponse
def generate_otp(request):
otp = random.randint(100000, 999999) # Generates a 6-digit random number
return HttpResponse(f"Your OTP is: {otp}")You can refer to the screenshot below to see the output:

In this example, when a user visits the URL mapped to generate_otp they receive a random 6-digit number displayed on the page. This method is quick and effective for generating integer-based random numbers.
Check out Create a User Profile Using Django
2: Generate Random Floating-Point Numbers with random.uniform()
Sometimes you need a random decimal number, such as generating random prices or ratings.
Here’s how I generate a random float between 1.0 and 5.0, which could simulate a product rating in an online store:
# views.py
import random
from django.http import HttpResponse
def random_rating(request):
rating = round(random.uniform(1.0, 5.0), 2) # Random float with 2 decimals
return HttpResponse(f"Random product rating: {rating}")You can refer to the screenshot below to see the output:

This method uses random.uniform() to generate a floating-point number within the given range and round it to two decimal places for better readability.
Read Create an API in Python Django
3: Use Django Template to Display Random Numbers
If you want to generate and display random numbers directly in your Django templates without modifying views, you can create a custom template tag.
Here’s a simple example:
- Create a new directory
templatetagsinside your app folder with an__init__.pyfile. - Add a Python file
random_tags.pywith the following code:
# random_tags.py
import random
from django import template
register = template.Library()
@register.simple_tag
def random_int(min_value=0, max_value=100):
return random.randint(min_value, max_value)- Load and use this tag in your template:
{% load random_tags %}
<p>Random number: {% random_int 1000 9999 %}</p>You can refer to the screenshot below to see the output:

This approach is handy when you want to keep your views clean and generate random numbers directly in the front-end.
Check out JWT Authentication Using Django Rest Framework
4: Generate Random Numbers for Model Fields
Sometimes you might want to assign a random number automatically when saving a model instance. For example, generating a random order number.
Here’s how I do it using Django’s model save() method:
# models.py
import random
from django.db import models
class Order(models.Model):
order_number = models.CharField(max_length=10, unique=True, blank=True)
customer_name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
if not self.order_number:
self.order_number = str(random.randint(1000000000, 9999999999)) # 10-digit number
super().save(*args, **kwargs)This ensures every new order gets a unique 10-digit random number as its order number. Remember to handle the rare case of duplicates if your application scales.
Tips for Using Random Numbers in Django
- Always import Python’s built-in
randommodule for generating random numbers. - For cryptographic or security-sensitive applications (like tokens), prefer
secretsmodule overrandom. - When generating random numbers for database fields, consider uniqueness and collision handling.
- Use rounding for floating-point numbers to improve user readability.
Generating random numbers in Django is easy once you know the right functions and where to place the code. Whether it’s in views, templates, or models, you can easily add randomness to your application to meet various business needs.
I hope this guide helps you implement random number generation effectively in your Django projects.
You may like to read:
- How to Deploy an AI Model with Django
- Build a Chat App in Django
- Compare Two Integers in Python Django

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.