Streamlining Azure Django Deployment
Published: 2023-10-16 21:35:33

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/azure-django-deployment_b7528c51c3a18489fc89fd5e7766ae19.jpg" alt="Streamlining Azure Django Deployment."/></figure>

Azure is a cloud computing service that lets developers and DevOps engineers effortlessly and efficiently deploy and maintain web servers or applications. It offers amazing advantages like scalability, reliability, and security on the deployed web apps or servers.

Django is the most popular [Python backend framework](https://code.pieces.app/blog/the-top-4-python-back-end-frameworks-for-your-next-project) for rapid web development. Django allows you to create backend servers, full-stack online apps, or websites, as well as perform AI or machine learning tasks.

This step-by-step guide will walk you through the process of Azure Django deployment, understanding the deployment workflow, and enabling continuous deployment for a seamless development workflow for you.

Let's delve into the details and unlock the potential of Azure for your Django projects!

## Prerequisites

Now that you've understood the significance of Azure, here are certain prerequisites to ensure that you follow this instructional guide correctly.

- Have an account on [Azure](https://azure.microsoft.com/en-us).
- You should have a Django app ready for deployment.
- You must have a [GitHub](https://github.com/) account.


## Configuring Azure for Django Deployment

This section will walk you through the steps of creating a web app on Azure to host your Django web app or web server.

1. Login to your Azure portal and click **App Services.**

The app services are designed to host websites, web applications, API endpoints, and [backend frameworks for web development](https://code.pieces.app/blog/most-popular-backend-frameworks-for-web-development).

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image15_ce43e16eb64b009bd488d49557c6d9ba.png" alt="Azure app services."/></figure>

2. Click **Create** on the next screen to add an app service to your Azure account. To select which app service to deploy, a dropdown menu will appear.

Because you are deploying a web server that will require a database, select **Web App + Database**.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image18_bed559aad5339738c38c5ce819201c75.jpg" alt="Create a Web App + Database."/></figure>

3. Select subscriptions and resource groups, leave the region as it is, and define your web app details.  If you don't already have a Resource group, click **Create new.**

Depending on the needs of your project, you can utilize Python 3.10 or 3.11. This guide uses Python 3.10.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image19_0d3ade34fe4a93b2ec1fce9c759135c2.png" alt="Naming your app and selecting a Python version."/></figure>

4. Define your database details.

- Use the suggested engine if this is your first time using Azure and it is a hobby project.
- The other details have been pre-defined based on your web app details.
- This guide will be focused on deploying a basic app therefore there will be no need to use the Azure Redis service.
- Choose a hosting package based on your demands, such as a hobby project or a production project.
- Select **Review + Create** to create the app service and database for your Django app.


<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image16_36f68dc62e67ad3a594dba3b3b18b45d.png" alt="Review and create your app and database."/></figure>

5. On the following screen, you should be able to review the details of your web app and database. After you've double-checked that all of the information is correct, click **Create**.

Scroll to **Database(new)** and save the credentials as you will be using these to set up a PostgreSQL database on your Django project.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image4_b96deea388716aca8a8a49706370d245.png" alt="Saving your database credentials."/></figure>

6. Your deployed app should look like this. With this, you can search and connect your Django project to the created app service.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image10_74a24b8e0a994016d42b1fff99326fb6.png" alt="Your deployed app."/></figure>

## Using Azure to Deploy Django App

This section will show you how to deploy your Django application from your local machine to your newly formed Azure hosting service.

You've now configured your Azure account for deployment. It's time to make your Django project public.

1. Start by installing [Psycopg](https://pypi.org/project/psycopg2/), a PostgreSQL database adapter, first. This is used to link a PostgreSQL database server to a Django project, and install [Whitenoise](https://pypi.org/project/whitenoise/), it allows you to render static files on a server.

```
pip install psycopg2 whitenoise
```

[Save this code](https://sophyia.pieces.cloud/?p=4a674184a4)

2. Make changes to settings.py before deployment. You would need to add the whitenoise middleware, your azure web app URL to the trusted CRSF and authorized host lists, make sure that static files have a storage location, and make use of the whitenoise middleware to render them.

```
# Define ALLOWED_HOST
ALLOWED_HOSTS = ['name-of-web-app.azurewebsites.net', '127.0.0.1']

# Modify Middleware 
MIDDLEWARE = [
 'django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 # new 
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 "corsheaders.middleware.CorsMiddleware",
 "django.middleware.common.CommonMiddleware",
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# Update Staticfiles directory
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Add azure web app as trusted CRSF
CRSF_TRUSTED_ORIGINS = ["fintech-app.azurewebsites.net"]
```

[Save this code](https://sophyia.pieces.cloud/?p=e4c5468de4)

3. Update your requirements.txt or create one if you don’t have one. The requirements.txt file tells Azure which packages must be installed on the cloud area for the app to execute.

```
pip freeze > requirements.txt
```

[Save this code](https://sophyia.pieces.cloud/?p=6018408725)

4. Create a file, **.production.** Define a set of commands for Azure to Auto\_build your Django app on its cloud.

```
[config]
SCM_DO_BUILD_DURING_DEPLOYMENT = true
```

[Save this code](https://sophyia.pieces.cloud/?p=5cdf4198cc)

5. Create the _.gitignore_ file. Specific files and folders won't be taken into account when pushing to your remote repository by GitHub. By doing this, you can prevent sharing private information or pushing unwanted data.

```
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
.vscode/

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
myenv/
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/
```

[Save this code](https://sophyia.pieces.cloud/?p=f51d409a70)

6. Once you are done modifying your codebase, go to the Azure portal and choose the app service you just built. The Deployment Center should be located. Here, you can select a build source from options like GitHub, BitBucket or other source methods.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image2_007cd8a90e04dc05fe71d85eca9cdfd4.jpg" alt="Selecting a build source."/></figure>

7. Select **Deployment Center** and choose a source under **Settings**. For the sake of this guide, we’ll use GitHub.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image11_cb84f45a825ab052951094d16cd7ad82.png" alt="Selecting GitHub."/></figure>

8. If this is your first time using Azure, you will be asked to sign in with your GitHub account. To login to your GitHub account, click **Authorize**.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image12_4c5984ce22fd6d8ae228e776d287ac22.png" alt="Authorizing your GitHub account to connect to Azure."/></figure>

9. Once you authorize your GitHub account, you would need to select an organization, repository and branch that has the codebase you want to deploy.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image17_d6b0a1df3a3deaa9612bffe7fe9990a5.png" alt="Selecting a GitHub repository."/></figure>

10. Azure would create a YML file that commands for deployment. The .yml file is used to configure CI/CD pipeline for automatic Django deployments and easy building of releases. This helps manage the applications better.

To preview it, click on **Preview file** under **Workflow Configuration**. Note: if you defined any workflow yml, it will be overwritten.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image14_bbfefc9d1a4c8c69a8c8df7edd5b2bf3.jpg" alt="Previewing your workflow configuration."/></figure>

11. Once you are satisfied with the deployment settings, click **Save** to set up the deployment on GitHub actions.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image6_af231a825321192aa151d7b24aa1e20b.png" alt="Saving your deployment pipeline."/></figure>

Once your GitHub Action has been setup, you would be notified.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image5_1db7390545c742722d3597af1181503f.png" alt="Success message."/></figure>

You can see the yml file on your git remote repo that you set during the deployment process.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image13_a598eb0156a39e0a49d71fab762c9bd3.jpg" alt="Your GitHub remote repo."/></figure>

12. Add an additional code on the yml file to collectstatic file and render them. Do this close to the **install dependencies** line.

```
- name: Install dependencies
        run: pip install -r requirements.txt

      - name: Run collectstatic
        run: python manage.py collectstatic
```

[Save this code](https://sophyia.pieces.cloud/?p=af3e40bd07).

Once done, commit your changes and push to your git repo. The GitHub actions will auto-deploy the codebase to Azure.

13. Update your database details and hostname on your Azure. Click on **Configuration** and select **New application setting.** Don’t forget to add secret information on your application settings. This is to create a more secure django app.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image8_29550555502a1f7a67195365596b9f2e.jpg" alt="Configuring a new application setting."/></figure>

Define the name and the value and click **Ok** to set a secret info on your azure cloud.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image20_af6d06932d94c70c6cbfce7f1f43bf95.png" alt="Naming your database."/></figure>

Now, that’s it! Your Azure Django app is live!

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image3_5ba0ddfb737fb491bd1a01c85912cd8d.jpg" alt="Your live Azure project."/></figure>

## Migrating Database

Once your Azure Django hosting is set up and your project is up and running, you must migrate and update the tables in your database to enable full functionality.

1. Select **SSH** from the Azure portal's **Development tool** and click **Go**. With this, you can start a Linux terminal and run Python commands like creating a superuser or migrating a database.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image9_a9d80846e9fda8b8c890eea527cc0af5.png" alt="Selecting your SSH key."/></figure>

2. Run this [command](https://sophyia.pieces.cloud/?p=41844ebf1a) to migrate tables based on your existing models in the Django app.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image7_0a37ada65c63bd3802d1704b643612d9.png" alt="Migrating your tables in the Django app."/></figure>

3. Use this [command](https://sophyia.pieces.cloud/?p=9a1e48b3d9) to create a superuser to access your django admin.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image1_b905ed35490d5f0af43949be7144d98b.png" alt="Creating a Django admin."/></figure>

That’s all! You’ve managed to deploy a Django app on Azure.

## Conclusion

This guide has explained how to use Azure for a swift deployment for your Django web apps or servers. Azure is an affordable hosting platform for your hobby project, startup, or even a large scale company with lots of traffic.

Azure app services can be used to deploy any web application; web servers, mobile backends, [JSON API](https://code.pieces.app/partner-collections/how-to-build-a-json-api-with-python) endpoints, etc., regardless of what continuous deployment source you are using; GitHub, Azure repos, BitBucket, or if you are using a manual deployment source.

Overall, the best way to deploy Django apps is with Azure because of its scalability, security and flexibility. Thanks to this article, your Azure Django deployment should be a smooth process.