To begin building a Django web application, first ensure Python is installed and configured on your system. Then install Django using pip:
pip install Django
Verify the installation by checking the version:
python -m django --version
Creating a Django Project
It’s critical to initialize the project from the correct directory. Avoid creating the project within an IDE-generated structure (e.g., PyCharm’s project template), as this may cause path and module resolution issues.
Navigate to your desired workspace directory (e.g., Django-workspace) and run:
django-admin startproject test_platform
This generates a project root folder containing essential files like manage.py and settings.py. Open this folder in your IDE (e.g., PyCharm), then conifgure the enterpreter to use a virtual environment. If you previously created a project in the IDE, delete it and re-open the newly created folder—PyCharm will auto-detect the correct Python environment.
Creating a Django App
Inside the project directory, generate a new app using the manage.py script:
python manage.py startapp webtest
This creates a new app folder with standard Django components: models.py, views.py, apps.py, and more.
Registering the App
Open test_platform/settings.py and add your app to the INSTALLED_APPS list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webtest', # Add this line
]
Failure to register the app will result in runtime errrors when referencing its views or models.
Building a View
Edit webtest/views.py to define a simple HTTP response:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, Django!")
Rendering a Template
To serve dynamic HTML content, create a template directory structure. Inside the webtest folder, create a folder named templates, and within it, create another folder named webtest (matching the app name):
webtest/
├── templates/
│ └── webtest/
│ └── index.html
└── views.py
Now create webtest/templates/webtest/index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Template</title>
</head>
<body>
<h1>Welcome to My Django App</h1>
<p>This page is rendered using a template.</p>
</body>
</html>
Update the view to render this template instead of returning plain text:
from django.shortcuts import render
def index(request):
return render(request, 'webtest/index.html')
Now you’re ready to run the development server:
python manage.py runserver
Visit http://127.0.0.1:8000/ in your browser to see your page.