loader image

21CS62 Program 3

3. Develop a Django app that displays current date and time in server.

Step-01: Create new folder:-
⦿ In the same project folder whatever we made earlier create again one new app name called as datetime_app using below command.

python manage.py startapp datetime_app
VS Code

Step-02: Add the datetime_app to the installed_apps list:-
⦿ locate the settings.py file (usually located in the project directory) and open it.
⦿After then add your app name in install_apps list as per below image.

VS Code

Step-03: Inside views.py file create a function:-
⦿ Open the views.py file in your Django project directory (datetime_app/views.py).
⦿ Import the required modules at the top of the file.
⦿ Create a new view function that will handle the request and render the date and time.

from django.shortcuts import render

import datetime

def datetime_app(request):
 now = datetime.datetime.now ()
 context = {'datetime_app': now}
 return render (request, 'datetime_app.html', context)
VS Code

Step-04: Create a template:-
⦿ Right click on datetime_app folder, create a new folder named templates.
⦿ Inside the templates folder, create a new file named datetime_app.html.
⦿ Open datetime_app.html and add the below code to display the current date and time.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vtucode | Current Date and Time</title>
<style>
    .container{
        flex-direction: column;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>
</head>
<body style="text-align:center;">
    <div class="container">
    <h1>Current Date and Time on the Server:</h1>
    <p>{{ datetime_app }}</p>
    </div>
</body>
</html>
VS Code

Step-05: Include the datetime_app URLs in the project’s URL patterns:-
⦿ Open the urls.py file in your Django project directory (project/urls.py).
⦿ Import the view function at the top of the file.
⦿ Add a new URL pattern to the urlpatterns list.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', datetime_app, name='datetime_app'),
]
Screenshot 182

Step-6: Run Your Project:-
⦿ Now setup is completed you can run your project using below command.
⦿ The terminal will display the URL where the development server is running, typically http://127.0.0.1:8000/.
⦿ Copy the URL from the terminal and paste it into your web browser’s address bar to see the output web page.

python manage.py runserver
VS Code
OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *