Django (Python)

Table of contents

Child pages


Tutorials

The official Django tutorial

Summary

Part 1

  • Install Django: run pip install Django from within a venv.
  • Creating a project
    • Create a new Django project: django-admin startproject mysite
    • About the default files:
      • manage.pyA command-line utility that lets you interact with this Django project in various ways.
      • mysite/settings.pySettings/configuration for the Django project.
      • mysite/urls.pyThe URL declarations for this Django project.
        • This is a similar concept to Web.py
      • mysite/wsgi.pyAn entry-point for WSGI-compatible web servers to serve your project.
        • This should be a familiar concept to anyone who has used PythonAnywhere to serve a Python web app.
  • The development server
    • Run the dev server: python manage.py runserver
    • The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.
  • Creating the Polls app
    • Projects vs. apps - What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.
    • Note that a Django "project" is different from a PyCharm project / git repo.  Your Django project will have a "container" folder within your PyCharm project folder / git repo folder, and within that Django project container folder will be a Python package folder that's unique to your project.
    • Apps don't live within the Django project's inner package directory.  You can keep apps anywhere that a module can be imported from, but if it's tightly tied to your project you'd have it within the Django project's container directory, at the same level as the manage.py file and the project's Python package directory:
      • pycharm_project_folder/
        • django_project_container_folder/
          • django_project_python_package_folder/
          • app_1_folder/
          • manage.py
          • etc.
    • Create an app: python manage.py startapp app_name
    • Apps have the following initial structure:
      • app_name/ 
        •  __init__.py
        • admin.py
        • apps.py
        • migrations/
          • __init__.py
        • models.py
        • tests.py
        • urls.py
        • views.py
    • Questions I have:
      • Why doesn't the mysite/ folder have a views.py, tests.py, etc. by default?
  • Write your first view
    • Hello World (/app_name/views.py):
      • from django.http import HttpResponse
        def index(request): return HttpResponse("Hello, world. You're at the polls index.")
    • Create a URL configuration by filling out /app_name/urls.py
      • from django.urls import path
        
        from . import views
        
        urlpatterns = [
            path('', views.index, name='index'),
        ]
      • The Django term for this entry is apparently "a URLconf".
    • Register the new URLconf with the root URLconf in mysite/urls.py
      • from django.contrib import admin
        from django.urls import include, path
        
        urlpatterns = [
            path('polls/', include('polls.urls')),
            path('admin/', admin.site.urls),
        ]
    • Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

    • The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.
    • path() arguments
      • route
        • A string that contains a URL pattern
        • Django starts looking for matches at the first pattern in urlpatterns and makes its way down the list.
      • view
        • A function defined in views.py.
        • Django calls the function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments.
      • kwargs - Arbitrary keyword arguments can be passed in a dictionary to the target view.
      • name - Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.

Part 2

  • Summary: We’ll set up the database, create your first model, and get a quick introduction to Django’s automatically-generated admin site.
  • Database setup
  • Creating models
  • Activating models
  • Playing with the API
  • Introducing the Django Admin
    • Creating an admin user
    • Start the development server
    • Enter the admin site
    • Make the poll app modifiable in the admin
    • Explore the free admin functionality

Part 3

  • Summary: We’re continuing the Web-poll application and will focus on creating the public interface – “views.”
  • Overview
  • Writing more views
  • Write views that actually do something
    • A shortcut: render()
  • Raising a 404 error
    • A shortcut: get_object_or_404()
  • Use the template system
  • Removing hardcoded URLs in templates
  • Namespacing URL names

Part 4

  • Summary: We’re continuing the Web-poll application and will focus on simple form processing and cutting down our code.
  • Write a simple form
  • Use generic views: Less code is better
    • Amend URLconf
    • Amend views

Part 5

  • Summary: We’ll now create some automated tests for the application.
  • Introducing automated testing
    • What are automated tests?
    • Why you need to create tests
      • Tests will save you time
      • Tests don’t just identify problems, they prevent them
      • Tests make your code more attractive
      • Tests help teams work together
  • Basic testing strategies
  • Writing our first test
    • We identify a bug
    • Create a test to expose the bug
    • Running tests
    • Fixing the bug
    • More comprehensive tests
  • Test a view
    • A test for a view
    • The Django test client
    • Improving our view
    • Testing our new view
    • Testing the DetailView
    • Ideas for more tests
  • When testing, more is better
  • Further testing

Part 6

  • Summary: We’ll now add a stylesheet and an image to our application.
  • Customize your app’s look and feel
  • Adding a background-image

Part 7

  • Summary: We'll now focus on customizing Django’s automatically-generated admin site.
  • Customize the admin form
  • Adding related objects
  • Customize the admin change list
  • Customize the admin look and feel
    • Customizing your project’s templates
    • Customizing your application’s templates
  • Customize the admin index page

Advanced tutorial: How to write reusable apps

  • Summary: We’ll be turning our Web-poll into a standalone Python package you can reuse in new projects and share with other people.
  • Reusability matters
  • Your project and your reusable app
  • Installing some prerequisites
  • Packaging your app
  • Using your own package
  • Publishing your app
  • Installing Python packages with virtualenv

Misc tutorials



Praise for Django

Criticisms of Django

  • 2005.12.06 - Aaron Schwartz - Rewriting Reddit
    • He criticizes Django
    • Summary
      • While Django claims that it’s “loosely coupled”, using it pretty much requires fitting your code into Django’s worldview.
      • Django’s philosophy says “Explicit is better than implicit”, but Django has all sorts of magic.
      • Another Django goal is “less code”, at least for you. But Django is simply full of code.
      • Django’s most important problem is that its developers seem incapable of designing a decent API.
        • Their APIs are ugly and regularly missing key features.

Misc articles

  • 2017.06.14 - @dizballanze - Django project optimization guide (part 1)
  • Amazon - Two Scoops of Django: Best Practices For Django 1.6 - (Intermediate-Level Resource)
  • Quora - What is the one thing that you wish you knew about Django framework early?
    • Upvoted by Parker Conrad
    • Joseph Misiti
      • Start off with the right directory structure
      • Use Celery for asynchronous tasks AND cron jobs (no need to use unix crontab)
      • Use Gunicorn instead of Apache for your webserver
      • Don’t be afraid of using MongoDB as your primary data store
      • Use named URLs, reverse, and the url template tag
      • Get your settings.py file right
      • Use supervisor for process monitoring
      • Pick the right AJAX/JSON mechanism
      • Use Redis - because it will eventually be your best friend
      • Use munin and statds for process monitoring
      • Use jammit for static asset compression
    • Tommaso Barbugli
      • Don't use Django's Template language; use Jinja2 instead.
      • Read Forms' documentation.
      • Don't do too many smart things in your settings!  Have test/dev/production/staging settings but otherwise try to keep it as simple as possible.
      • Use Django Debug Toolbar to find performance mistakes / inspect context / cache calls etc.
    • Nguyen Thanh Luan
      • Use cookie cutter Django
      • Use virtualenv
      • Change the setting structure for different environments
      • Custom user model
      • Use Sentry for monitoring
      • And some apps to use (djang-extensions, djang-debug-toolbar, django_builder)
    • Sudip Kafle
      • Django has built-in system to send email to the site administrators in case a 500 server error occurs in your application; to use it define the ADMINS tuple in the settings file with the name and email address of the admins.
    • Clay McClure
      • A Django "project" is just a settings module, and a Django "app" is just a package containing a models module. There's no magic, and you can lay these things out however you'd like.
    • Jagadesh Babu
      • the authentication and registration system like, login, password reset, can be re-utilized from the admin site for our projects
    • Andrew Choi
      • Middleware!
        • I was having a problem in an app where I needed to pass a specific header when the incoming request was coming from IE, and before I knew about middleware I wrote an "examine_request_source()" function that would set a flag, which would be read by a custom render() method and dealt with appropriately. The equivalent code in middleware was about 5 lines, and didn't muddy up any of the rest of the code.
    • Johan Uys
      • I wish I knew that the importance of monitoring the number of db queries and using select related and prefetch related to keep the number low
    • Anurag Kumar
      • render()
      • render_to_Response()
      • csrf_token
      • the User Model. And that it has predefined fields such as username, email and password. And that we can extend it with our custom fields.
  • 2009.12.04 - StackOverflow - How should I organize Python source code?