Render a basic template in a Django app's views.py to a Django template


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

    urlpatterns = [
        path('admin/', admin.site.urls),
        path("app/", include("app.urls"))
    ]

  • Now go to app's urls.py file and paste this code.

    from django.urls import path
    from . import views

    urlpatterns = [
        path("home", views.handleHome, name="home")
    ]

  • Now go to app's views.py file and paste this code.

    from django.shortcuts import render

    def handleHome(request):
        return render(request, "index.html")

  • Now go to templates folder which is exist in root directory and create a file index.html inside templates folder and paste this code.

    <!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>Document</title>
    </head>

    <body>
        <h1>hello world</h1>
    </body>

    </html>

  • After all of these setups, your project's tree view will look like this in VS Code:
  • Now run this command in VS Code's terminal:

    python manage.py runserver

  • That's it.

No comments:

Post a Comment