Here’s a step-by-step guide to help you create a simple home page.
If you have already created a Django project and you want to create a home page for your Django web app, then you need to do the following things.
1. Create a separate app for the main pages
Create a new app (let's call it pages):
python manage.py startapp pages
2. Add the app details in the Settings.py file
INSTALLED_APPS = [ ... 'pages', ]
3. Create a templates folder in your main pages app. Create a home.html file with the home page code.
Create a folder named 'templates" inside your pages app. Then create a file named "home" inside the templates folder.
add the following code to your home.html file
<!-- pages/templates/home.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home Page</title> </head> <body> <h1>Welcome to My Django Home Page!</h1> <p>This is the home page of my Django application.</p> </body> </html>
Then save the file.
4. Configure your main project home page redirect to pages app urls.py
Add the following code to your main project urls.py file
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), # Include pages app URLs ]
5. Create a view for the home page in your main pages app.
add the following code to your pages app views.py file.
from django.shortcuts import render def home_view(request): return render(request, 'home.html')
Save the file.
6. Include the home page in the main pages urls.py file.
Create a urls.py file in your pages app directory and add the following code.
from django.urls import path from .views import home_view urlpatterns = [ path('', home_view, name='home'), ]
Run the server
python manage.py runserver
That's all.
Method 2: Create a home page without HTML Template (for test purposes)
You can also create a home page using the HttpResponse method.
Just add the following code in your app views,py file.
from django.http import HttpResponse def home_view(request): return HttpResponse("<h1>Welcome to My Django Home Page!</h1><p>This is the home page of my Django application.</p>")
Then add it to app urls.py file
from django.urls import path from .views import home_view urlpatterns = [ path('', home_view, name='home'), ]
You can also pass the values when you create a home view.
Ex:-
from django.shortcuts import render def home_view(request): context = { 'title': 'Home Page', 'message': 'Welcome to My Django Home Page!' } return render(request, 'home.html', context)
Use those values in the HTML template.
<!-- pages/templates/home.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ title }}</title> </head> <body> <h1>{{ message }}</h1> </body> </html>
That's all.
© 2024 Webapptiv. All rights reserved.