Getting Started with Django
Django is a high-level Python web framework that enables rapid development of secure and maintainable websites.
Installation
Prerequisites
- Python 3.8 or higher
- pip package manager
- Virtual environment (recommended)
Setting up Django
- Create a virtual environment:
python -m venv django_env
source django_env/bin/activate # On Windows: django_env\Scripts\activate
- Install Django:
pip install django
- Verify installation:
python -m django --version
Creating Your First Project
Start a new project:
django-admin startproject mysite
cd mysite
Project structure:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
Run the development server:
python manage.py runserver
Visit http://127.0.0.1:8000/ to see the Django welcome page.
Creating an Application
Django projects contain multiple applications:
python manage.py startapp polls
This creates:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
Basic Configuration
Add your app to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls', # Add your app here
]
Create your first view in polls/views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
Configure URLs in polls/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Include app URLs in main urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
Database Setup
Apply initial migrations:
python manage.py migrate
Create a superuser:
python manage.py createsuperuser