Django Tutorial
The Python web framework for building secure sites and APIs quickly.
Getting started11 lessons
- 1Python You Need: ClassesDjango models, views and forms are classes.
- 2Python You Need: DecoratorsA decorator wraps a function.
- 3Django IntroductionDjango is a Python web framework that includes an ORM, an admin site, forms, authenticatio.
- 4Install DjangoCreate a virtual environment so each project has its own packages, then install Django wit.
- 5Create a Projectdjango-admin startproject creates the project folder with manage.py and a settings package.
- 6Project StructureA project holds settings.py (configuration), urls.py (routes), wsgi.py and asgi.py (server.
- 7Create an Appstartapp creates an app folder.
- 8Your First ViewA view is a Python function that takes a request and returns a response.
- 9URL Routingurls.py maps paths to views.
- 10URL ParametersAngle brackets capture parts of the URL.
- 11Named URLs and reverseGive each route a name and use reverse() or the url template tag instead of hard coding pa.
Templates18 lessons
- 12TemplatesTemplates are HTML files with Django template language.
- 13VariablesDouble braces print a value.
- 14Tags: if and forTags use {% %}.
- 15FiltersFilters change a value with a pipe.
- 16Template InheritanceA base template defines blocks.
- 17Static FilesCSS, JavaScript and images are static files.
- 18Include and Commentsinclude inserts another template and can pass values.
- 19Rendering Templatesrender fills a template with context.
- 20Template VariablesDouble braces print values.
- 21Template TagsTags use percent braces for logic.
- 22Template FiltersFilters change values.
- 23Template InheritanceBase templates define blocks.
- 24The include TagReuse snippets.
- 25The url TagLink with names.
- 26Static FilesLoad static assets with the static tag.
- 27CSRF ProtectionEvery POST form needs a token.
- 28Auto EscapingDjango escapes HTML by default.
- 29Template SettingsTEMPLATES controls where templates live.
Models10 lessons
- 30ModelsA model is a Python class that describes a database table.
- 31Field TypesCommon fields: CharField, TextField, IntegerField, FloatField, BooleanField, DateField, Da.
- 32Migrationsmakemigrations writes migration files from model changes and migrate applies them to the d.
- 33The ORM in the ShellThe shell lets you try the ORM.
- 34QuerySetsA QuerySet represents a database query.
- 35Field LookupsDouble underscores add conditions: contains, icontains, startswith, gt, gte, lt, lte, in, .
- 36Update and DeleteChange attributes then save, or use update() for many rows at once.
- 37Relationships: ForeignKeyA ForeignKey links many rows to one row, such as many comments for one post.
- 38Many to Many and One to OneManyToManyField links many rows to many rows, such as posts and tags.
- 39__str__ and Meta__str__ controls how an object prints, which helps in the admin.
Admin2 lessons
Forms4 lessons
Views6 lessons
- 46Shortcuts: get_object_or_404 and redirectget_object_or_404 returns an object or a 404 page.
- 47JsonResponse and HTTP MethodsJsonResponse returns JSON.
- 48Class Based ViewsA class based view organises code by HTTP method.
- 49ListView and DetailViewGeneric views remove repeated code.
- 50The Messages FrameworkMessages show one time notices such as Saved successfully.
- 51Sessions and Cookiesrequest.session is a dictionary stored on the server and linked to a cookie.
Advanced DjangoPremium20 lessons
- 52CreateView, UpdateView and DeleteViewGeneric edit views handle forms and saving.
- 53Authentication: Login and Logoutdjango.contrib.auth provides users, login and logout views.
- 54User RegistrationUserCreationForm validates and hashes passwords.
- 55Permissions and GroupsEvery model gets add, change, delete and view permissions.
- 56Custom User ModelStart every real project with a custom user model, even an empty one.
- 57MiddlewareMiddleware wraps every request and response, for logging, authentication or headers.
- 58SignalsSignals let code react to events such as post_save without editing the sender.
- 59select_related and prefetch_relatedThe N plus 1 problem runs one query per row.
- 60Aggregation and Annotationaggregate returns one summary and annotate adds a computed value to each object.
- 61Q and F ObjectsQ builds OR and NOT conditions.
- 62Custom Managers and QuerySetsA manager adds reusable queries.
- 63Database Transactionsatomic groups queries so they all succeed or none do.
- 64CachingCaching stores expensive results.
- 65File UploadsUse FileField or ImageField, set MEDIA_ROOT and MEDIA_URL and put enctype multipart on the.
- 66Django REST Framework BasicsDRF turns models into JSON APIs.
- 67API Authentication and PaginationDRF supports token, session and JWT authentication through packages.
- 68TestingDjango tests use unittest style classes with a test database and a test client.
- 69Async ViewsDjango can run async def views under ASGI servers such as uvicorn.
- 70Custom Template Tags and FiltersCreate a templatetags package with a Library, register filters and tags, then load it in t.
- 71Custom Management CommandsCommands under management/commands run with manage.py, ideal for cron jobs and data import.
Django in practicePremium10 lessons
- 72Settings and Environment VariablesNever commit SECRET_KEY or passwords.
- 73Security ChecklistDjango protects against XSS, CSRF, SQL injection and clickjacking by default.
- 74Using PostgreSQLSQLite is fine for learning.
- 75Deployment with Gunicornrunserver is only for development.
- 76Static Files in Productioncollectstatic gathers all static files into STATIC_ROOT.
- 77Background Tasks with CelerySlow jobs such as emails and reports should run outside the request.
- 78Logging and MonitoringConfigure LOGGING to write errors to stdout or files, and use Sentry for alerts.
- 79Docker for DjangoDocker makes the environment repeatable.
- 80Django Best PracticesKeep fat models and thin views, use class based views where they help, write tests, pin re.
- 81Next StepsBuild a blog, a todo app and an API.
Django setup7 lessons
- 82Virtual EnvironmentsIsolate packages per project.
- 83Starting a Projectdjango-admin creates the project skeleton.
- 84Creating an AppAn app is a feature module.
- 85Project StructureKnow the main files.
- 86Settingssettings.py configures the project.
- 87The Dev Serverrunserver auto reloads on code changes.
- 88The MVT PatternDjango uses Model, View and Template.
Views and URLs12 lessons
- 89Your First ViewA view takes a request and returns a response.
- 90URL Configurationpath maps a URL to a view.
- 91include for App URLsinclude delegates URLs to an app.
- 92URL ParametersConverters capture parts of the URL.
- 93Named URLs and reverseUse names instead of hard coded paths.
- 94GET and POSTrequest.method tells how the page was requested.
- 95Query Stringsrequest.GET reads values after the question mark.
- 96Redirectsredirect sends the browser elsewhere.
- 97JSON ResponsesJsonResponse returns JSON.
- 98Handling 404Raise Http404 or use get_object_or_404.
- 99Class Based ViewsView classes handle methods separately.
- 100Generic ViewsListView and DetailView reduce code.
Models and database17 lessons
- 101Defining a ModelA model is a Python class for a table.
- 102Field TypesCommon fields include CharField, IntegerField, BooleanField and DateField.
- 103Migrationsmakemigrations records changes and migrate applies them.
- 104Creating ObjectsCreate with the constructor or objects.create.
- 105Reading Objectsall, get and filter read data.
- 106Field LookupsDouble underscores add conditions.
- 107Updating and DeletingChange fields and save, or delete.
- 108Ordering and Slicingorder_by sorts and slices limit.
- 109exclude and Q ObjectsQ combines conditions with OR.
- 110Aggregationaggregate and annotate compute values.
- 111ForeignKeyForeignKey makes one to many links.
- 112Reverse Relationscomment_set reads the other side.
- 113ManyToManyLink many to many.
- 114Model MethodsAdd methods and __str__.
- 115Model Meta OptionsMeta sets ordering and names.
- 116The Django ShellTry queries interactively.
- 117DatabasesSQLite is the default.
Admin and forms9 lessons
- 118Admin and SuperuserCreate an admin user and log in.
- 119Registering Modelsadmin.site.register adds a model to the admin.
- 120Customising ModelAdminControl list columns, search and filters.
- 121Django FormsForm classes render and validate input.
- 122Using a Form in a ViewCheck is_valid then read cleaned_data.
- 123ModelFormCreate forms from models.
- 124Rendering FormsRender with as_p or by field.
- 125Custom Validationclean_<field> checks one field.
- 126Messages FrameworkFlash one time messages.
Auth and project work13 lessons
- 127Login and LogoutUse the built in auth views.
- 128Protecting Viewslogin_required blocks anonymous users.
- 129request.userAccess the current user.
- 130User RegistrationUserCreationForm builds a sign up form.
- 131Sessionsrequest.session stores per visitor data.
- 132MiddlewareMiddleware wraps every request.
- 133Signals BasicsRun code when models save.
- 134TestingTestCase runs tests with a temporary database.
- 135Deployment BasicsTurn off debug, set hosts and collect static files.
- 136Secrets and EnvironmentKeep SECRET_KEY out of the code.
- 137Project: BlogModels, views and templates together.
- 138Project: Todo AppCRUD with ModelForm.
- 139Django Best PracticesKeep apps small, use fat models, thin views and tests.