Open In App

Generate random numbers and background colour in Django

Last Updated : 04 Dec, 2022
Like Article

In this article, we will learn how to generate random numbers and background colors in Python Django. And we will also see different steps related to a random number in Django. These are the following steps that we are going to discuss in this tutorial:

  • What is the Django?
  • Functions to generate a random number
  • Functions to generate random background color
  • Django random number in template

What is Django?

A Python-based web framework called Django enables you to easily build effective online apps. Because Django has built-in features for everything, including the Django Admin Interface and the default database, SQLlite3, it is often known as a batteries-included framework.

File Structure

This is the final file structure when we did our all stuff.


Stepwise Implementation

Step 1: Create a Virtual Environment, You can skip this step if you want.

Step 2: Step up Django Installation.

Open Command Prompt or Terminal and Install Django

pip install Django

Step 3: Start a project by the following command, and Change the directory to Test 

django-admin startproject Test
cd Test

Step 4:  Create an app in Django

Note:  ‘GenerateRandom’ is the name of the app you can change it accordingly.

python startapp GenerateRandom

Step 5: Add resources to your Django app. Create a templates directory to hold HTML pages. Open any code editor and add both directories to the path. For your reference, you can see the file structure given above. 

Step 6: Edit Test/

Add the following code to the end of the file. 

Note:  Remember to Import the os module into the code.



Step 7: Now find Templates and add the following code to DIRS.



Step 8: Add GenerateRandom/index.html files to the template directory. Here, the script is the name that is defined in the  for the corresponding view, now edit the of the app and add a new path to it.


<!DOCTYPE html>
<html lang="en">
    <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>Generate Random Number</title>
        body {
            background-color: rgb(249, 255, 195);
        button {
            margin-bottom: 15px;
            border-radius: 15px;
            background-color: rgb(164, 211, 252);
            padding: 5px;
            padding-left: 10px;
            padding-right: 10px;
            font-size: 15px;
            font-family: 'Courier New', Courier, monospace;
        h1 {
            font-family:'Courier New', Courier, monospace
        <h1>Generate Random Number</h1>
        <button onclick="location.href='{% url 'script' %}'">Generate</button>
    {% if number %}
    <center>Random Number is: {{number}}</center>
    <script> "#{{number}}"</script>
    {% endif %} 

Step 9: Configure the Test/ file.


from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('', include('GenerateRandom.urls'))

Step 10: Open the newly created GenerateRandom/ in the app and add the following code it.


from django.contrib import admin
from django.urls import path, include
from GenerateRandom import views
urlpatterns = [
    path('', views.index),
    path('output', views.output, name='script')

Step 11: Open GenerateRandom/ in the app.

  • Create an index function to render index.html.file
  • The generate function generates a random number through Python and displays the number and changes the background color randomly, so creating a generate function that generates a random number and color.
  • Create a new output function and then call the previously created generate() function in it.


from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
    return render(request, 'index.html')
def generate():
    from random import randrange
    num = randrange(100000, 1000000)
    return num
def output(request):
    context = {
        'number': generate()
    return render(request, 'index.html', context)

Step 12: Deploy the Project.

Now Everything is set let’s run the server and preview our application. To run the server enter the following command:

python runserver



For source code checkout this GitHub Repository.

Similar Reads

wxPython - Change Background colour of Button
In this article we are going to learn about how can we change background colour of a button present in a frame. We use SetBackgroundColour() function to set background colour of the button to some different colour. It takes a wx.Colour class object as an argument. Syntax: wx.Button.SetBackgroundColour(self, colour) Parameters: Parameter Input Type
1 min read
wxPython - Change Background Colour of Radio Button
In this article we are going to learn about how can we change background colour of a Radio Button. We will use SetBackgroundColour() function sets the background colour of the window. Notice that as with SetForegroundColour, setting the background colour of a native control may not affect the entire control and could be not supported at all dependi
1 min read
wxPython - Get background colour of Toolbar
In this article we will know how can we get the colour of the background of wx.ToolBar. In order to do this we will use GetBackgroundColour() function of wxPython. GetBackgroundColour() function simply returns the background colour of the window. Syntax: wx.ToolBar.GetBackgroundColour(self) Parameters: No parameters are required in this method. Ret
1 min read
wxPython - Change background colour of RadioBox
In this article we are going to learn how can we change the background colour of Radio Box present in the frame. In order to do that we are going to use SetBackgroundColour() method. SetBackgroundColour() function takes wx.Colour argument which will be used as background colour for Radio Box. Syntax: wx.RadioBox.SetBackgroundColour(self, colour)Par
1 min read
Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
Generate five random numbers from the normal distribution using NumPy
In Numpy we are provided with the module called random module that allows us to work with random numbers. The random module provides different methods for data distribution. In this article, we have to create an array of specified shape and fill it random numbers or values such that these values are part of a normal distribution or Gaussian distrib
2 min read
How to generate random numbers from a log-normal distribution in Python ?
A continuous probability distribution of a random variable whose logarithm is usually distributed is known as a log-normal (or lognormal) distribution in probability theory. A variable x is said to follow a log-normal distribution if and only if the log(x) follows a normal distribution. The PDF is defined as follows. [caption width="800"]Probabilit
3 min read
Generate Random Numbers From The Uniform Distribution using NumPy
Random numbers are the numbers that cannot be predicted logically and in Numpy we are provided with the module called random module that allows us to work with random numbers. To generate random numbers from the Uniform distribution we will use random.uniform() method of random module. Syntax: numpy.random.uniform(low = 0.0, high = 1.0, size = None
1 min read
Discrete Colour Scale in Plotly Python
In the Cartesian plane for X and Y coordinates, colors can be used to represent data on the graph to make it more understandable. This color label can be used to display continuous or discrete data both. Python Plotly can be used to display both the color representation i.e. continuous(moments in time) and discrete(categorical). In this article, we
2 min read
wxPython - Change Font colour of Radio Button
In this article we are going to learn that how can we change the foreground or font color of the radio button. In order to change the foreground colour of Radio Button we will use SetForegroundColour() function. SetForegroundColour() function sets the foreground colour of the window. The meaning of foreground colour varies according to the window c
2 min read
Practice Tags :