Installing and Creating a Django Project
Install Django with pip and use django-admin to scaffold a project.
Python
# Install Django
# pip install django
# Create a new project
# django-admin startproject mysite
# cd mysite
# Create an app within the project
# python manage.py startapp blog
# Project structure:
# mysite/
# manage.py β CLI tool
# mysite/
# settings.py β Configuration
# urls.py β URL routing
# wsgi.py β WSGI server entry
# blog/
# models.py β Database models
# views.py β View functions
# urls.py β App URL patternsModels β Database Tables as Python Classes
Django models map directly to database tables. Django generates and runs SQL migrations automatically.
Python
# blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey("auth.User", on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
published = models.BooleanField(default=False)
class Meta:
ordering = ["-created_at"]
def __str__(self):
return self.title
# Run migrations:
# python manage.py makemigrations
# python manage.py migrateViews β Handling HTTP Requests
Views receive HTTP requests and return responses.
Python
# blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.filter(published=True)
return render(request, "blog/post_list.html", {"posts": posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk, published=True)
return render(request, "blog/post_detail.html", {"post": post})Ad β 336Γ280
URL Routing
Map URLs to view functions using URLconf.
Python
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.post_list, name="post-list"),
path("posts//", views.post_detail, name="post-detail"),
]
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("blog/", include("blog.urls")),
] The Django Admin Panel
Register models to get a fully-featured CRUD admin UI automatically.
Python
# blog/admin.py
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ["title", "author", "published", "created_at"]
list_filter = ["published", "created_at"]
search_fields = ["title", "content"]
# Create superuser:
# python manage.py createsuperuser
# Visit http://127.0.0.1:8000/admin/Tip
Django's admin is one of its killer features. You get a full CRUD interface for all your models with zero additional code.