Django Views and Templates

In this tutorial, you will learn how to create views and templates to render dynamic content in your Django applications.

Step 1: Creating a View

Views are defined in the `views.py` file of your app. Here is an example of a simple view:

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

Step 2: Creating a Template

Templates are HTML files that are rendered by views. Create a `home.html` file in your app's `templates` directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>
    <h1>Welcome to Django Projects</h1>
</body>
</html>

Step 3: Configuring URLs

To map the view to a URL, add an entry to your app's `urls.py` file:

from django.urls import path
from . import views

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

Now, when you navigate to the root URL of your project, the `home.html` template will be rendered by the `home` view.

Step 4: Using Template Variables

You can pass data from your view to the template using context variables:

from django.shortcuts import render

def home(request):
    context = {'message': 'Welcome to Django Projects'}
    return render(request, 'home.html', context)

In your `home.html` template, you can access the context variable like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>
    <h1>{{ message }}</h1>
</body>
</html>

Follow the Django documentation to learn more about creating views and templates.