Django is one of the most popular frameworks for web development in Python, chosen by many developers for its speed and advanced capabilities. One of the first tasks done when creating a Django project is to create the main index page. This page serves as the main display for your site and usually includes links and introductory information about your site.
To add a main page in Django, you first need to create a view. A view is actually a function that returns an HttpResponse. Typically, this response includes an HTML template that shows the content of the page.
The next step is to create a URL pattern that connects the main page to a specific URL address. This is done using the urls.py file. You can specify exactly which address directs the user to the main page.
Afterward, you will need to create your own template. Templates allow you to effectively present content along with dynamic data. This is done using a Django templating language similar to HTML.
Now, let’s take a look at one of these steps and examine the code that needs to be written:
# views.py
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
# index.html
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
</head>
<body>
<h1>Welcome to my site</h1>
<p>This is the first page of the site.</p>
</body>
</html>
Step-by-Step Explanation of the Code
def index(request):
This view function is used to manage requests related to the main page.
return render(request, 'index.html')
This line renders the template related to index.html and returns it as a response to the user.
path('', views.index, name='index')
This section in urls.py indicates that the root URL of the site (for example, www.example.com) is associated with the view related to the main page.
The HTML referenced in index.html
is a simple template containing text and a heading.