Setting up a Django development environment

Now that you know what Django is for, we'll show you how to set up and test a Django development environment on Windows, Linux (Ubuntu), and macOS — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.

Prerequisites: Basic knowledge of using a terminal/command line and how to install software packages on your development computer's operating system.
Objective: To have a development environment for Django (3.*) running on your computer.

Django development environment overview

Django makes it very easy to set up your own computer so that you can start developing web applications. This section explains what you get with the development environment, and provides an overview of some of your setup and configuration options. The remainder of the article explains the recommended method of installing the Django development environment on Ubuntu, macOS, and Windows, and how you can test it.

What is the Django development environment?

The development environment is an installation of Django on your local computer that you can use for developing and testing Django apps prior to deploying them to a production environment.

The main tools that Django itself provides are a set of Python scripts for creating and working with Django projects, along with a simple development webserver that you can use to test local (i.e. on your computer, not on an external web server) Django web applications on your computer's web browser.

There are other peripheral tools, which form part of the development environment, that we won't be covering here. These include things like a text editor or IDE for editing code, and a source control management tool like Git for safely managing different versions of your code. We are assuming that you've already got a text editor installed.

What are the Django setup options?

Django is extremely flexible in terms of how and where it can be installed and configured. Django can be:

  • Installed on different operating systems.
  • Installed from source, from the Python Package Index (PyPi) and in many cases from the host computer's package manager application.
  • Configured to use one of several databases, which may also need to be separately installed and configured.
  • Run in the main system Python environment or within separate Python virtual environments.

Each of these options requires a slightly different configuration and setup. The following subsections explain some of your choices. For the rest of the article, we'll show you how to setup Django on a small number of operating systems, and that setup will be assumed throughout the rest of this module.

注意: Other possible installation options are covered in the official Django documentation. We link to the appropriate documents below .

What operating systems are supported?

Django web applications can be run on almost any machine that can run the Python 3 programming language: Windows, macOS, Linux/Unix, Solaris, to name just a few. Almost any computer should have the necessary performance to run Django during development.

In this article, we'll provide instructions for Windows, macOS, and Linux/Unix.

What version of Python should be used?

You can use any Python version supported by your target Django release. For Django 3.1.2 the allowed versions are Python 3.6 to 3.8 (see  FAQ:Installation ).

The Django project recommends (and "officially supports") using the newest available supported Python release.

注意: Python 2.7 cannot be used with the current releases of Django (The Django 1.11.x series is the last to support Python 2.7).

Where can we download Django?

There are three places to download Django:

  • The Python Package Repository (PyPi), using the pip tool. This is the best way to get the latest stable version of Django.
  • Use a version from your computer's package manager. Distributions of Django that are bundled with operating systems offer a familiar installation mechanism. Note however that the packaged version may be quite old, and can only be installed into the system Python environment (which may not be what you want).
  • Install from source. You can get and install the latest bleeding-edge version of Django from the source. This is not recommended for beginners but is needed when you're ready to start contributing back to Django itself.

This article shows how to install Django from PyPi, in order to get the latest stable version.

Which database?

Django officially supports the PostgreSQL, MariaDB, MySQL, Oracle, and SQLite databases, and there are community libraries that provide varying levels of support for other popular SQL and NoSQL databases. We recommend that you select the same database for both production and development (although Django abstracts many of the database differences using its Object-Relational Mapper (ORM), there are still potential issues that are better to avoid).

For this article (and most of this module) we will be using the SQLite database, which stores its data in a file. SQLite is intended for use as a lightweight database and can’t support a high level of concurrency. It is, however, an excellent choice for applications that are primarily read-only.

注意: Django is configured to use SQLite by default when you start your website project using the standard tools ( django-admin ). It's a great choice when you're getting started because it requires no additional configuration or setup.

Installing system-wide or in a Python virtual environment?

When you install Python3 you get a single global environment that is shared by all Python3 code. While you can install whatever Python packages you like in the environment, you can only install one particular version of each package at a time.

注意: Python applications installed into the global environment can potentially conflict with each other (i.e. if they depend on different versions of the same package).

If you install Django into the default/global environment then you will only be able to target one version of Django on the computer. This can be a problem if you want to create new websites (using the latest version of Django) while still maintaining websites that rely on older versions.

As a result, experienced Python/Django developers typically run Python apps within independent  Python virtual environments . This enables multiple different Django environments on a single computer. The Django developer team itself recommends that you use Python virtual environments!

This module assumes that you've installed Django into a virtual environment, and we'll show you how below.

Installing Python 3

In order to use Django you will have to install Python on your operating system. If you're using   Python 3  then you will also need the PyPI (Python 包索引) tool — pip3 — which is used to manage (install, update, and remove) Python packages/libraries used by Django and your other Python apps.

This section briefly explains how you can check what versions of Python are present, and install new versions as needed, for Ubuntu Linux 20.04, macOS, and Windows 10.

注意: Depending on your platform, you may also be able to install Python/pip from the operating system's own package manager or via other mechanisms. For most platforms, you can download the required installation files from https://www.python.org/downloads/ and install them using the appropriate platform-specific method.

Ubuntu 20.04

Ubuntu Linux 20.04 LTS includes Python 3.8.5 by default. You can confirm this by running the following command in the bash terminal:

python3 -V
 Python 3.8.5

						

However, the Python Package Index tool ( pip3 ) you'll need to install packages for Python 3 (including Django) is not available by default. You can install pip3 in the bash terminal using:

sudo apt install python3-pip

						

macOS

macOS "El Capitan" and other more recent versions do not include Python 3. You can confirm this by running the following commands in the zsh or bash terminal:

$ python3 -V
  python3: command not found

						

You can easily install Python 3 (along with the pip3 tool) from python.org :

  1. Download the required installer:
    1. Go to  https://www.python.org/downloads/
    2. 选择 Download Python 3.8.6  button (the exact version number may differ).

      注意: The version offered may be different. Ensure that the version you download is supported by Django (if needed, links for getting older versions can be found on the same page).

  2. Locate the file using Finder , and double-click the package file. Following the installation prompts.

You can now confirm successful installation by checking for the Python 3 version as shown below:

python3 -V
 Python 3.9.0

					

You can similarly check that pip3 is installed by listing the available packages:

pip3 list

					

Windows 10

Windows doesn't include Python by default, but you can easily install it (along with the pip3 tool) from python.org :

  1. Download the required installer:
    1. Go to  https://www.python.org/downloads/
    2. 选择 Download Python 3.8.6  button (the exact version number may differ).

      注意: The version offered may be different. Ensure that the version you download is supported by Django  (if needed, links for getting older versions can be found on the same page).

  2. Install Python by double-clicking on the downloaded file and following the installation prompts
  3. Be sure to check the box labeled "Add Python to PATH"

You can then verify that Python 3 was installed by entering the following text into the command prompt:

py -3 -V
 Python 3.8.6

				

The Windows installer incorporates pip3 (the Python package manager) by default. You can list installed packages as shown:

pip3 list

				

注意: The installer should set up everything you need for the above command to work. If however you get a message that Python cannot be found, you may have forgotten to add it to your system path. You can do this by running the installer again, selecting "Modify", and checking the box labeled "Add Python to environment variables" on the second page.

Using Django inside a Python virtual environment

The libraries we'll use for creating our virtual environments are  virtualenvwrapper  (Linux and macOS) and  virtualenvwrapper-win  (Windows), which in turn both use the  virtualenv  tool. The wrapper tools creates a consistent interface for managing interfaces on all platforms.

Installing the virtual environment software

Ubuntu virtual environment setup

After installing Python and pip you can install  virtualenvwrapper  (which includes  virtualenv ). The official installation guide can be found here , or follow the instructions below.

Install the tool using  pip3 :

sudo pip3 install virtualenvwrapper

				

Then add the following lines to the end of your shell startup file (this is a hidden file name  .bashrc  in your home directory). These set the location where the virtual environments should live, the location of your development project directories, and the location of the script installed with this package:

export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 '
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

				

注意: VIRTUALENVWRAPPER_PYTHON and VIRTUALENVWRAPPER_VIRTUALENV_ARGS variables point to the normal installation location for Python3, and source /usr/local/bin/virtualenvwrapper.sh points to the normal location of the virtualenvwrapper.sh script. If the virtualenv doesn't work when you test it, one thing to check is that Python and the script are in the expected location (and then change the startup file appropriately).

You can find the correct locations for your system using the commands  which virtualenvwrapper.sh  and  which python3 .

Then reload the startup file by running the following command in the terminal:

source ~/.bashrc

				

At this point you should see a bunch of scripts being run as shown below:

virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/premkproject
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postmkproject
...
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/preactivate
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postactivate
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/get_env_details

				

Now you can create a new virtual environment with the  mkvirtualenv  command.

macOS virtual environment setup

Setting up virtualenvwrapper on macOS is almost exactly the same as on Ubuntu (again, you can follow the instructions from either the official installation guide  or below).

Install  virtualenvwrapper  (and bundling  virtualenv ) using  pip  as shown.

sudo pip3 install virtualenvwrapper

				

Then add the following lines to the end of your shell startup file (these are the same lines as for Ubuntu). If you're using the zsh shell then the startup file will be a hidden file named .zshrc  in your home directory. If you're using the bash shell then it will be a hidden file named .bash_profile . You may need to create the file if it does not yet exist.

export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

				

注意: The  VIRTUALENVWRAPPER_PYTHON  variable points to the normal installation location for Python3, and source /usr/local/bin/virtualenvwrapper.sh points to the normal location of the  virtualenvwrapper.sh script. If the virtualenv doesn't work when you test it, one thing to check is that Python and the script are in the expected location (and then change the startup file appropriately).

For example, one installation test on macOS ended up with the following lines being necessary in the startup file:

export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
export PROJECT_HOME=$HOME/Devel
source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh

				

You can find the correct locations for your system using the commands which virtualenvwrapper.sh and which python3 .

Then reload the startup file by making the following call in the terminal:

source ~/.bash_profile

				

At this point, you may see a bunch of scripts being run (the same scripts as for the Ubuntu installation). You should now be able to create a new virtual environment with the  mkvirtualenv  command.

注意: If you can't find the startup file to edit in the finder, you can also open this in the terminal using nano.

Assuming you're using bash, the commands look something like this:

cd ~  # Navigate to my home directory
ls -la #List the content of the directory. YOu should see .bash_profile
nano .bash_profile # Open the file in the nano text editor, within the terminal
# Scroll to the end of the file, and copy in the lines above
# Use Ctrl+X to exit nano, choose Y to save the file.

				

Windows 10 virtual environment setup

Installing  virtualenvwrapper-win  is even simpler than setting up  virtualenvwrapper  because you don't need to configure where the tool stores virtual environment information (there is a default value). All you need to do is run the following command in the command prompt:

pip3 install virtualenvwrapper-win

				

Now you can create a new virtual environment with the  mkvirtualenv  command

创建虚拟环境

Once you've installed  virtualenvwrapper  or  virtualenvwrapper-win  then working with virtual environments is very similar on all platforms.

Now you can create a new virtual environment with the  mkvirtualenv  command. As this command runs you'll see the environment being set up (what you see is slightly platform-specific). When the command completes the new virtual environment will be active — you can see this because the start of the prompt will be the name of the environment in brackets (below we show this for Ubuntu, but the final line is similar for Windows/macOS).

$ mkvirtualenv my_django_environment
Running virtualenv with interpreter /usr/bin/python3
...
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/t_env7/bin/get_env_details
(my_django_environment) ubuntu@ubuntu:~$

				

Now you're inside the virtual environment you can install Django and start developing.

注意: From now on in this article (and indeed the module) please assume that any commands are run within a Python virtual environment like the one we set up above.

Using a virtual environment

There are just a few other useful commands that you should know (there are more in the tool documentation, but these are the ones you'll use regularly):

  • deactivate  — Exit out of the current Python virtual environment
  • workon  — List available virtual environments
  • workon name_of_environment  — Activate the specified Python virtual environment
  • rmvirtualenv name_of_environment  — Remove the specified environment.

Installing Django

Once you've created a virtual environment, and called  workon  to enter it, you can use  pip3 to install Django.

pip3 install django~=3.1

				

You can test that Django is installed by running the following command (this just tests that Python can find the Django module):

# Linux/macOS
python3 -m django --version
 3.1.2
# Windows
py -3 -m django --version
 3.1.2

				

注意: If the above Windows command does not show a django module present, try:

py -m django --version

				

In Windows Python 3 scripts are launched by prefixing the command with py -3 , although this can vary depending on your specific installation. Try omitting the -3 modifier if you encounter any problems with commands. In Linux/macOS, the command is python3.

警告: The rest of this 模块 使用 Linux command for invoking Python 3 ( python3 ) . If you're working on Windows replace this prefix with:  py -3

Testing your installation

The above test works, but it isn't very much fun. A more interesting test is to create a skeleton project and see it working. To do this, first navigate in your command prompt/terminal to where you want to store your Django apps. Create a folder for your test site and navigate into it.

mkdir django_test
cd django_test

				

You can then create a new skeleton site called " mytestsite " using the django-admin tool as shown. After creating the site you can navigate into the folder where you will find the main script for managing projects, called manage.py .

django-admin startproject mytestsite
cd mytestsite

				

We can run the development web server from within this folder using manage.py runserver command, as shown.

$ python3 manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 27, 2020 - 03:00:01
Django version 3.1.2, using settings 'mytestsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

				

注意: The above command shows the Linux/macOS command. You can ignore the warnings about  "18 unapplied migration(s)" at this point!

Once the server is running you can view the site by navigating to the following URL on your local web browser: http://127.0.0.1:8000/ . You should see a site that looks like this:

The home page of the skeleton Django app.

摘要

You now have a Django development environment up and running on your computer.

In the testing section you also briefly saw how we can create a new Django website using  django-admin startproject , and run it in your browser using the development web server ( python3 manage.py runserver ). In the next article, we expand on this process, building a simple but complete web application.

另请参阅

In this module

发现此页面有问题吗?

最后修改: , 由 MDN 贡献者

  1. Complete beginners start here!
  2. Web 快速入门
    1. Getting started with the Web overview
    2. 安装基本软件
    3. What will your website look like?
    4. 处理文件
    5. HTML 基础
    6. CSS 基础
    7. JavaScript 基础
    8. 发布您的网站
    9. How the Web works
  3. HTML — Structuring the Web
  4. HTML 介绍
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. 多媒体和嵌入
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML 表格
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. CSS 第一步
    1. CSS first steps overview
    2. What is CSS?
    3. Getting started with CSS
    4. How CSS is structured
    5. How CSS works
    6. Using your new knowledge
  9. CSS 构建块
    1. CSS building blocks overview
    2. Cascade and inheritance
    3. CSS 选择器
    4. The box model
    5. Backgrounds and borders
    6. Handling different text directions
    7. Overflowing content
    8. Values and units
    9. Sizing items in CSS
    10. Images, media, and form elements
    11. Styling tables
    12. Debugging CSS
    13. Organizing your CSS
  10. 样式化文本
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  11. CSS 布局
    1. CSS layout overview
    2. Introduction to CSS layout
    3. Normal Flow
    4. Flexbox
    5. Grids
    6. Floats
    7. 位置
    8. Multiple-column Layout
    9. Responsive design
    10. Beginner's guide to media queries
    11. Legacy Layout Methods
    12. Supporting Older Browsers
    13. Fundamental Layout Comprehension
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript 第一步
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic math in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. 数组
    10. Assessment: Silly story generator
  14. JavaScript 构建块
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. 事件介绍
    8. Assessment: Image gallery
  15. 引入 JavaScript 对象
    1. Introducing JavaScript objects overview
    2. Object basics
    3. 对象原型
    4. Object-oriented programming concepts
    5. Classes in JavaScript
    6. Working with JSON data
    7. Object building practice
    8. Assessment: Adding features to our bouncing balls demo
  16. 异步 JavaScript
    1. Asynchronous JavaScript overview
    2. General asynchronous programming concepts
    3. Introducing asynchronous JavaScript
    4. Cooperative asynchronous Java​Script: Timeouts and intervals
    5. Graceful asynchronous programming with Promises
    6. Making asynchronous programming easier with async and await
    7. Choosing the right approach
  17. 客户端侧 Web API
    1. 客户端侧 Web API
    2. Introduction to web APIs
    3. Manipulating documents
    4. Fetching data from the server
    5. Third party APIs
    6. Drawing graphics
    7. Video and audio APIs
    8. Client-side storage
  18. Web forms — Working with user data
  19. Core forms learning pathway
    1. Web forms overview
    2. Your first form
    3. How to structure a web form
    4. Basic native form controls
    5. The HTML5 input types
    6. Other form controls
    7. Styling web forms
    8. Advanced form styling
    9. UI pseudo-classes
    10. Client-side form validation
    11. Sending form data
  20. Advanced forms articles
    1. How to build custom form controls
    2. Sending forms through JavaScript
    3. CSS property compatibility table for form controls
  21. Accessibility — Make the web usable by everyone
  22. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  23. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  24. Tools and testing
  25. Client-side web development tools
    1. Client-side web development tools index
    2. Client-side tooling overview
    3. Command line crash course
    4. Package management basics
    5. Introducing a complete toolchain
    6. Deploying our app
  26. Introduction to client-side frameworks
    1. Client-side frameworks overview
    2. Framework main features
  27. React
    1. Getting started with React
    2. Beginning our React todo list
    3. Componentizing our React app
    4. React interactivity: Events and state
    5. React interactivity: Editing, filtering, conditional rendering
    6. Accessibility in React
    7. React resources
  28. Ember
    1. Getting started with Ember
    2. Ember app structure and componentization
    3. Ember interactivity: Events, classes and state
    4. Ember Interactivity: Footer functionality, conditional rendering
    5. Routing in Ember
    6. Ember resources and troubleshooting
  29. Vue
    1. Getting started with Vue
    2. Creating our first Vue component
    3. Rendering a list of Vue components
    4. Adding a new todo form: Vue events, methods, and models
    5. Styling Vue components with CSS
    6. Using Vue computed properties
    7. Vue conditional rendering: editing existing todos
    8. Focus management with Vue refs
    9. Vue resources
  30. Svelte
    1. Getting started with Svelte
    2. Starting our Svelte Todo list app
    3. Dynamic behavior in Svelte: working with variables and props
    4. Componentizing our Svelte app
    5. Advanced Svelte: Reactivity, lifecycle, accessibility
    6. Working with Svelte stores
    7. TypeScript support in Svelte
    8. Deployment and next steps
  31. Angular
    1. Getting started with Angular
    2. Beginning our Angular todo list app
    3. Styling our Angular app
    4. Creating an item component
    5. Filtering our to-do items
    6. Building Angular applications and further resources
  32. Git and GitHub
    1. Git and GitHub overview
    2. Hello World
    3. Git Handbook
    4. Forking Projects
    5. About pull requests
    6. Mastering Issues
  33. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  34. Server-side website programming
  35. 第一步
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  36. Django Web 框架 (Python)
    1. Django web framework (Python) overview
    2. 介绍
    3. 设置开发环境
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  37. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  38. Further resources
  39. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. Web mechanics
    5. Tools and setup
    6. Design and accessibility