This is a first for me since under normal circumstances we run all our Django applications on Linux with Nginx, but we’re in the process of developing an application for another department and due to the requirements around this project, we’ll be handing the code off to them to deploy. They don’t have any experience with Linux or web servers other than IIS, so I recently took up the challenge of figuring out how to run Django applications on Windows Server 2012 with IIS.
Based on the dated or complete lack of information around this I’m assuming it’s not something that’s very common in the wild, so I thought I’d share what I came up with in case others need to do this.
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Assumptions and Caveats
- The operating system is Windows Server 2012 R2, 64-bit. If another variant of the operating system is being used, these instructions may not work properly.
- All of the software versions referenced in this document are current as of the date of this blog post.
- All actions are performed as the Administrator user, or another user with Administrator rights.
- Depending on the audience, some of these steps may seem unnecessarily pedantic. They were originally written to be as foolproof as possible and to make these steps as thorough and complete as they can be. I decided not to simplify or abbreviate anything for this blog post.
- The version of Django that is current as of the time of this writing is 1.9.8. If any of the Django-related configuration settings change in the future, the settings outlined in this document may no longer be valid. For example, the details of the call to the Django WSGI handler are specific to this version of Django. They have been different in prior versions of Django, and may need to be updated in the future to reflect changes in Django.
- We’ll be creating a sample application called foo directly on the server. In real-world circumstances you’ll be deploying a completed application to the server, but I thought this was a good way to illustrate the steps and how all the pieces fit together.
- If you install things in different locations than outlined here, or put your application in a different location than outlined here, obviously you’ll have to adjust paths in configuration settings accordingly.
Prerequisites for Running Django Applications on IIS
If you want to target Windows Server and IIS as the production environment for your Django application, there aren’t really any issues of concern other than including the wfastcgi Python package (https://pypi.python.org/pypi/wfastcgi) in your application.
wfastcgi is maintained by Microsoft as part of Python Tools for Visual Studio (https://www.visualstudio.com/en-us/features/python-vs.aspx), and provides a file that serves as the entry point of the IIS handler for WSGI applications in Python. It’s similar in purpose to a tool like Gunicorn (http://gunicorn.org), with the end result being that requests that come into IIS are handed off to the Python application for processing.
wfastcgi can be installed with pip:
pip install wfastcgi
pip install wfastcgi
You’ll also want to add wfastcgi to your Django application’s requirements.txt file to make sure it gets installed as part of the deployment of your application.
After installing wfastcgi the file wfastcgi.py will be in your Python environment’s site-packages directory. We’ll point to this file later when we’re configuring the IIS handler for Django.
- Download the latest Windows x86-64 executable installer from https://python.org
- Double-click the Python installer. If you get a security warning at this point, click “Run” to continue.
- In the Python Setup dialog that appears, click “Customize Installation”
- On the Optional Features step, leave the default settings and click “Next”
- On the Advanced Options step, make the following changes:
- Check the “Install for all users” box (note that this will also check the “Precompile standard library” box)
- Check “Add Python to environment variables”
- In the input box below “Customize install location” change the value to the following:
- Click “Install”
- When the installation is complete, click “Close”
Confirm the Python Installation
- Open a new Command Prompt. Note that if you already had a command prompt open you will need to close and reopen it, as the Python installation process added new environment variables and any open command prompts will not have the new environment variables available.
- Type python and press Enter. This should open a Python interpreter:
- If instead of seeing the Python interpreter you see the error “‘python’ is not recognized as an internal or external command …” this likely means the “Add Python to environment variables” box was not checked on the Advanced Options step of the installation process. If this occurs you can uninstall and reinstall Python and make sure to check the “Add Python to environment variables” checkbox, or add the following to the System environment “Path” variable:
- Exit the Python interpreter by typing exit() and pressing Enter.
- Close the Command Prompt
Even if you already have IIS installed, you may need to go through these steps to install the CGI feature if it wasn’t installed as part of the original IIS installation.
- Open the Control Panel
- In the search box in the top right, type “windows features” (without the quotes)
- In the search results under “Programs and Features” click “Turn Windows features on or off.” This launches the Add Roles and Features Wizard.
- On the “Before you begin” step, click “Next”
- On the “Select installation type” leave the “Role-based or feature-based installation” radio button selected and click “Next”
- On the “Select destination server” step, leave the current server highlighted and click “Next”
- On the “Select server roles” step, scroll to the bottom of the list and check “Web Server (IIS)”
- In the “Add features that are required for Web Server (IIS)?” dialog that appears, leave the “Include management tools (if applicable)” checkbox checked and click “Add Features”
- On the “Select server roles” step, now that “Web Server (IIS)” is checked, click “Next”
- On the “Select features” step, leave the defaults and click “Next”
- On the “Web Server Role (IIS)” step, click “Next”
- On the “Select role services” step, scroll down to “Application Development,” expand that section, and check the “CGI” box. This will also check the “Application Development” checkbox. With “CGI” checked, click “Next.”
- On the “Confirmation” step, click “Install”
- Once the installation completes, click “Close”
- Close Server Manager
- Close Control Panel
Verify the IIS Installation
- Open a web browser on the server
- Enter http://localhost in the address bar and press Enter. You should see the default IIS page.
- If you don’t see the default IIS page:
- Open Control Panel
- Type “services” in the search box
- Under “Administrative Tools” click “View local services”
- Scroll to the bottom of the list and ensure you see “World Wide Web Publishing Service” listed, and that the status is “Running”
Create and Configure a Python Virtual Environment for Your Application
Python virtual environments are used to isolate application-specific Python environments from the system-wide Python environment. Even if you will only be running one application on a server, it’s good practice to create a virtual environment for your application to keep the virtual environment free from any unanticipated side effects of system updates.
- Open a Command Prompt
- Navigate to the root of the C: drive:
cd C: [then press Enter]
- Create a new directory in which to store your virtual environments:
mkdir virtualenvs [then press Enter]
- Navigate to the newly created virtualenvs directory:
cd virtualenvs [then press Enter]
- Create a new virtual environment. We’ll use the name foo for the purposes of illustration. Note that if you change this, you’ll have to adjust the rest of the steps in this post accordingly.
python -m venv foo [then press Enter]
Activate the Virtual Environment and Upgrade pip
With the virtual environment created, the next steps are to activate the virtual environment and update pip, Python’s package installer.
First, we’ll activate the virtual environment:
- Open a Command Prompt
- Navigate to the virtual environment’s directory:
cd C:virtualenvsfoo [then press Enter]
- Activate the virtual environment:
Scriptsactivate.bat [then press Enter]
- At this point you will see (foo) at the beginning of the command prompt, indicating the virtual environment is active:
- Once a virtual environment is active, all Python-related commands such as python, pip, etc. will be executed against the active virtual environment. For example, with the virtual environment active if a package is installed with pip, that package will only be available in the virtual environment, not in the system’s global Python environment.
Next, to ensure we don’t run into installation or security issues with pip, let’s upgrade it:
- In the same Command Prompt you opened above, with the virtual environment activated, run the following command:
python -m pip install –upgrade pip [then press Enter]
- If an update for pip is available, it will be downloaded and installed
Install Django and Create a Sample Django Application
Typically, you’ll be installing requirements from a requirements.txt file that is part of the codebase for your application, but for the purposes of this installation guide we’ll install Django in our virtual environment, both to illustrate the steps involved as well as to ensure the virtual environment is working properly. Then we’ll create a sample Django application that we’ll use later to configure with IIS.
- In the same Command Prompt you opened above, with the virtual environment activated, install Django:
pip install django [then press Enter]
- As outlined in the prerequisites section at the beginning of this document, you’ll also need to install wfastcgi in order for IIS to be able to pass requests off to Django:
pip install wfastcgi [then press Enter]
- Navigate to the root of the C: drive:
cd C: [then press Enter]
- Create a new directory in which we’ll put our application:
mkdir apps [then press Enter]
- Navigate to the newly created apps directory:
cd apps [then press Enter]
- Create a new Django project called foo:
django-admin.py startproject foo [then press Enter]
- Navigate to the newly created foo project directory:
cd foo [then press Enter]
- Start the Django development server:
python manage.py runserver [then press Enter]
- In a browser on the server, go to http://localhost:8000
You should see the following:
- Go back to the Command Prompt and press Ctrl-C to stop the Django development server.
Configure IIS to Serve Django Applications
Thus far we’ve accomplished the following:
- Installed Python
- Installed IIS with CGI
- Created and activated a Python virtual environment
- Installed Django and wfastcgi in a Python virtual environment
- Created a new Django project
- Ran the Django project using the Django development server
With all the underlying infrastructure in place, the last step is to configure IIS to serve Django applications. The Django development server is not designed for production use, so using a production-quality web server such as IIS is mandatory for production applications.
As with previous steps you’ll need to adjust accordingly for the actual application you want to deploy, but for the purposes of this documentation we’ll configure IIS to serve the test Django application we created in the previous steps.
Configure FastCGI in IIS
- Open the IIS Manager by clicking the Windows button, clicking on Administrative Tools, and double-clicking Internet Information Services (IIS) Manager
- Click on the name of the server in the list on the left. If you see the following dialog box, check the box “Do not show this message” and click “No.” (You can always get to this later if necessary by clicking “Get New Web Platform Components” under “Actions” on the right-hand side of IIS Manager.)
- Double-click the “FastCGI Settings” icon
- Under “Actions” on the right-hand side click “Add application …”
- In the Add FastCGI Application dialog, in the “Full Path” box, type the path to the Python executable for the application’s virtual environment:
- In the Arguments input box, type the path to the wfastcgi.py file in the application’s virtual environment:
- At this point your settings in the Add FastCGI Application dialog should look like this:
- With the Add FastCGI Application dialog box still open, under the “General” section, click on the “Environment Variables” line, then click the gray “…” button that appears next to (Collection) on the right-hand side of the line. This opens the EnvironmentVariables Collection Editor dialog.
- In the EnvironmentVariables Collection Editor dialog, click “Add”
- In the “Name properties” section on the right, click the input box to the right of “Name,” remove the “Name” text that is already in the input box, and enter DJANGO_SETTINGS_MODULE (note that this MUST be entered in ALL CAPS)
- Click the input box to the right of “Value” and enter foo.settings
- Click “Add” again and enter the following:
- Click “Add” again and enter the following:
- At this point you will have three environment variables:
- NOTE: All of these settings are CASE-SENSITIVE. They must be entered with exactly the case indicated here in order to work.
- Click “OK” to close the EnviromentVariables Collection Editor
- Click “OK” to close the Add FastCGI Application dialog
Create and Configure a New IIS Web Site
Next we need to create a new web site in IIS for the Django application, and add a Handler Mapping to the newly created web site so that requests coming to the IIS web site are passed off to the Django application for processing.
- Open IIS Manager
- On the left-hand side under Connections, expand the tree under the server name by clicking on the arrow to the left of the server name
- Right-click on the Sites folder and click “Add Website …”
- For the site name enter foo
- For the physical path, type the following:
- For the purposes of this example configuration, change the Port to 81, since the Default site is running on port 80. For a real-world application you’ll likely want to use name-based virtual hosting by adding bindings and run the site on port 80.
- You may leave the “Host name” blank. At this point the Add Website dialog should look like this:
- Click “OK”
Next, we’ll add a FastCGI handler mapping to this site so the requests coming into the site will be processed by the Django application.
- In IIS Manager, expand the Sites folder on the left-hand side and click on the foo site
- On the right, double-click “Handler Mappings”
- On the right, under “Actions,” click “Add Module Mapping”
- In the “Request path” box enter an asterisk: *
- Click the arrow on the right-hand side of the “Module” box and select “FastCgi Module”
- NOTE: Make sure to select FastCgi Module, NOT CgiModule
- In the “Executable” box, enter the following:
- Note that the character after python.exe is a pipe (|), which is entered by pressing Shift- on your keyboard
- In the “Name” box, enter Django Handler (you can call this whatever you want; it’s merely a friendly name for the module mapping)
- The Add Module Mapping dialog should now look like this:
- Click the “Request Restrictions” button and uncheck the “Invoke handler only if request is mapped to:” checkbox
- Click “OK” to close the Request Restrictions dialog
- Click “OK” to close the Add Module Mapping dialog
- When prompted “Do you want to create a FastCGI application for this executable?” click “No” since we created the application earlier.
- Note that you CAN have it create the FastCGI application for you from the module mapping, but the settings seem to be different and the end result isn’t fully editable. I also detailed how to create the FastCGI application to be as thorough as possible with all the various pieces involved.
- You will now see the Django Handler listed in the Handler Mappings for the foo website:
At this point everything should be working, so verify by loading the application in a browser.
This is the same result as when we ran the Django test server earlier, but now the requests are being handled by IIS.
Configure Django and IIS to Serve Static Files
Now we have things more or less working but we aren’t quite done. If you browse to the Django admin page (http://localhost:81/admin), you’ll see something like this:
The reason things look a little strange is because IIS doesn’t know where things like the CSS and image files for the Django application are located. In the Django world these assets are referred to as “static files,” and we need to perform a couple of additional steps for IIS to be able to serve these files. This isn’t an issue during development since Django has a static file server built into it, but in production we’ll want IIS to handle serving these files.
How Django handles static files is a bit of a topic in and of itself, so for further information please consult the Django documentation (https://docs.djangoproject.com/en/1.9/howto/static-files/). In this guide we’ll focus on a specific set of steps to get things working without getting into too many of the behind-the-scenes technical details, the different philosophies on where static files can or should be placed, or the various and sundry ways in which this aspect of Django applications can be addressed.
Add a STATIC_ROOT Setting to the Django Settings File
First, your Django application’s settings file needs to include a STATIC_ROOT setting, and this setting is not in Django applications by default. The STATIC_ROOT setting is used when Django’s collectstatic management command is run to determine where to place the collected static files.
In our sample foo application, we’ll tell Django to collect the static files in a static directory located in the same directory as the settings.py file. (You can ultimately put your static directory wherever you wish, but this is where we’ll be putting it for the purposes of this example.)
To accomplish this, do the following:
- Using a plain text editor such as Notepad, or Idle if that was installed when you installed Python, open the file C:appsfoofoosettings.py
- Scroll to the bottom of the file, or use the find feature of your text editor, and find the STATIC_URL setting
- Above the STATIC_URL setting, add the following setting:
STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, ‘foo’, ‘static’))
- The placement of the STATIC_ROOT setting in the settings.py file doesn’t matter, but putting it right next to the STATIC_URL setting is typical and keeps all the settings related to static files in one place.
- The STATIC_ROOT setting we’re using as our example will put the static files in C:appsfoofoostatic
- Save the settings.py file
Run the collectstatic Management Command
Now that Django knows where to put the static files, we can run the collectstatic management command. This command takes all the static files for your project, including the static files used by the Django admin and other packages in your virtual environment, and puts them under one static directory, the location of which is the STATIC_ROOT setting we added above, so they can be served by the web server.
- Open a Command Prompt
- Activate the application’s virtual environment:
C:virtualenvsfooScriptsactivate.bat [then press Enter]
- Navigate to the application’s root directory:
cd C:appsfoo [then press Enter]
- Run Django’s collectstatic management command:
python manage.py collectstatic [then press Enter]
- Django will then tell you the directory into which it’s going to copy the static files, and ask you to confirm since this process overwrites any existing files in the directory. Type yes at this prompt and press Enter.
- The static files will then be copied to the directory indicated by the STATIC_ROOT setting.
Add a static Virtual Directory to the IIS Web Site
Now we have all our static files in one place, but we still haven’t told IIS where they’re located. We’ll accomplish this by adding a static virtual directory to the IIS web site for our application.
Note that the name of the virtual directory in IIS must match the value of the STATIC_URL setting in the Django application’s settings.py file, absent the beginning and trailing slashes. For our sample application we’re using a value of /static/ for the STATIC_URL setting, so the name of the virtual directory in IIS will be static.
Create a virtual directory in IIS as follows:
- Open IIS Manager
- On the left-hand side under “Connections,” expand the server’s tree
- Expand the “Sites” folder
- Expand the foo web site. At this point, things should look like this:
- Right-click the foo web site and click “Add Virtual Directory”
- In the Add Virtual Directory dialog, enter the following values:
Physical path: C:appsfoofoostatic
- Click “OK.” You’ll see the static virtual directory appear under the web site.
Configure Handler Mappings for the static Virtual Directory
The last step is to tell IIS which handler to use to serve files out of the static virtual directory. Since at this point our Django Handler is set to serve all files for our application, even with the static virtual directory in place the Django Handler will still be attempting to serve these files.
IIS already has a static file handler active in the web site, but it’s down further in the list of handlers than the global Django Handler we configured, so to get IIS to serve the static files under the static virtual directory we’ll move the static file handler to the top of the handler list on the static virtual directory.
- Open IIS Manager
- Expand the server tree
- Expand the foo web site
- Click on the static virtual directory
- Double-click the “Handler Mappings” icon. You’ll see the following list of handler mappings:
- On the right-hand side under “Actions” click on “View Ordered List …”
- You’ll now see a list of the handler mappings in the order in which they’re run, with the Django Handler at the top.
- Click on the StaticFile handler at the bottom of the list, then click “Move Up” under “Actions” on the right-hand side.
- Note at this point you may receive a warning that by moving handlers you are detaching this virtual directory from the inheritance of the parent’s handler mappings. This is what we want to do, so if you get this warning click “Yes.”
- Continue to click “Move Up” until the StaticFile handler is at the top of the list of Handler Mappings.
With the StaticFile handler at the top of the list of Handler Mappings, requests that come into the static directory will be handled by the StaticFile handler as opposed to being processed by the Django Handler, so IIS will serve the static files now.
Confirm that everything is working by going to http://localhost:81/admin in a browser. You should now see the CSS being applied to the page.
Additional Concerns with Static Files
- Don’t include the directory to which the STATIC_ROOT setting is pointing in your application’s code repository; these files should not be tracked and versioned from that location, and the Django development server handles static files for you by serving them directly from their various locations. The collectstatic management command should be run as a normal part of the deployment process for production instances of your application.
- For complete information about Django’s handling of static files, and production deployment of static files, please refer to the following section of the Django documentation:
At this point your Django application should be playing nicely with IIS.
The information in this section is merely for reference, and to retain some of the research that was performed in the preparation of this guide even though it ultimately may not have been used as part of the final configuration steps.
Interesting things I came across while preparing this guide, in no particular order:
- http://stackoverflow.com/questions/34840354/django-on-iis-django-core-exceptions-appregistrynotready-apps-arent-loaded-ye (where I discovered that most of the examples of running Django on IIS had an older reference to the WSGI handler)
- https://pip.pypa.io/en/latest/user_guide/#installing-from-local-packages (good information about how to package up applications for deployment on an server without internet access)
- http://www.pyinstaller.org/ (another option for packaging up Django applications for automated deployment)
Additional Avenues of Exploration
- It is possible to use a web.config file at the web site level instead of the GUI IIS configuration for FastCGI and the site-specific handlers; see http://stackoverflow.com/questions/9794985/iis-this-configuration-section-cannot-be-used-at-this-path-configuration-lock for details about what needs to be enabled to support this. While it’d be handy to include these as part of the application’s codebase, it does involve installing and enabling a bunch of additional IIS add-ons at the root level of IIS, none of which are necessary for the purposes of running a Django app.
Install WFastCGI Gateway for IIS and Python 3.4
Installing WFastCGI for IIS through the IIS Manager is completely optional. It’s simply an alternate way of installing Python (in this case Python 3.4 specifically), and also provides the wfastcgi.py file that is required to configure a handler in IIS for Python applications.
If you perform these steps, Python 3.4 will be installed at the root of the C: drive, and this distribution of Python 3.4 will also place the wfastcgi.py file in the C:Python34 directory. You can then leverage this file or copy it into your application’s directory to configure the IIS handler.
- Open IIS Manager
- Click on the server in the list under “Connections” on the left-hand side
- At this point you may see a dialog box prompting you to install Microsoft Web Platform:
- If you see this dialog box, click “Yes.” This will open the download page in a web browser.
- If you do not see this box, under “Actions” on the right-hand side of IIS Manager, click on “Get New Web Platform Components.” This will open the download page in a web browser.
- You will be prompted to launch the Microsoft Web Platform application every time you launch IIS Manager, so if you see this dialog box after you have already installed the Web Platform Installer, feel free to check “Do not show this message” and then click “No.”
- On the Microsoft Web Platform web page, click the “Free Download” button.
- After the download completes, located the downloaded file and double-click to run it. As of the time of this writing the file is called wpilauncher.exe
- If you see a Security Warning dialog, click “Run” to run the installer.
- After the installation completes, the Web Platform Installer 5.0 application will launch.
- In the Web Platform Installer 5.0 application, in the search box on the top right, type “fastcgi” (without the quotes) and press Enter.
- In the search results, locate “WFastCGI 2.1 Gateway for IIS and Python 3.4” and click the “Add” button.
- At the bottom of the Web Platform Installer application, click “Install.”
- In the Prerequisites dialog that appears, click “I Accept” to accept the terms of the license.
- The WFastCGI extension will be downloaded and installed. When the installation completes, click “Finish” to close the installation dialog, and then click “Exit” to close the Web Platform Installer.
Note that doing installing the WFastCGI Gateway and Python 3.4 in this way does not automatically configure the FastCGI and Handler Mappings in IIS for you. It does install a default Python FastCGI application, but this will not necessarily automatically work with your application, and at a minimum you would still need to add a Handler Mapping for your application.