Skip to content
Justice Tech School

Django Tutorial

The Python web framework for building secure sites and APIs quickly.

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