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
|
Step 9: Configure the Test/urls.py file.
Python3
|
Step 10: Open the newly created GenerateRandom/urls.py in the app and add the following code it.
Python3
|
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
|
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.