Generate random numbers and background colour in Django

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 manage.py 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/settings.py.

Add the following code to the end of the file. 

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

STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static")
]

 

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

os.path.join(BASE_DIR,"templates")

 

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

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>Generate Random Number</title>

    <style>

        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

        }

    </style>

</head>

<body>

    <center>

        <h1>Generate Random Number</h1>

        <button onclick="location.href='{% url 'script' %}'">Generate</button>

    </center>

    {% if number %}

    <center>Random Number is: {{number}}</center>

    <script>document.body.style.backgroundColor= "#{{number}}"</script>

    {% endif %} 

</body>

</html>

Step 9: Configure the Test/urls.py file.

Python3

from django.contrib import admin

from django.urls import path, include

  

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('GenerateRandom.urls'))

]

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

Python3

from django.contrib import admin

from django.urls import path, include

from GenerateRandom import views

  

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', views.index),

    path('output', views.output, name='script')

]

Step 11: Open GenerateRandom/view.py 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.

Python3

from django.shortcuts import render, HttpResponse

  

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 manage.py runserver

Output:

 

For source code checkout this GitHub Repository.