Python Django Framework
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the "batteries-included" philosophy, providing everything you need to build a robust web application out of the box.
Installation
pip install django
Creating a Project
To start a new Django project:
django-admin startproject myproject
cd myproject
Running the Server
python manage.py runserver
Creating an App
A project can contain multiple apps. To create one:
python manage.py startapp myapp
Important: You must add 'myapp' to the INSTALLED_APPS list in myproject/settings.py.
Views and URLs
View (myapp/views.py)
A view function takes a web request and returns a web response.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world!")
URL Configuration (myapp/urls.py)
Create a urls.py file in your app directory to map URLs to views.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Project URLs (myproject/urls.py)
Include the app's URLs in the main project configuration.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
]
Templates
Django has a powerful template engine to separate design from Python code.
- Create a
templatesdirectory in your app folder. - Inside that, create a folder with your app name (e.g.,
myapp/templates/myapp/). - Create
index.html.
<h1>Hello, {{ name }}!</h1>
Update the view to render the template:
from django.shortcuts import render
def index(request):
context = {'name': 'Django'}
return render(request, 'myapp/index.html', context)
Models (Database)
Define your data structure in myapp/models.py. Django uses an ORM (Object-Relational Mapper).
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
Migrations
Apply changes to the database schema.
# Create migration files based on model changes
python manage.py makemigrations
# Apply migrations to the database
python manage.py migrate
Admin Interface
Django provides a built-in admin interface to manage data.
- Create a superuser:
python manage.py createsuperuser - Register your models in
myapp/admin.py:
from django.contrib import admin
from .models import Question
admin.site.register(Question)
- Visit
http://127.0.0.1:8000/admin/and log in.