- Article
- 9 minutes to read
APPLIES TO: Azure Database for PostgreSQL - Flexible Server
In this tutorial you will learn how to deploy a Django application in Azure using App Services and Azure Database for PostgreSQL - Flexible Server in a virtual network.
Prerequisites
If you don't have an Azure subscription, create a free account before you begin.
This article requires that you're running the Azure CLI version 2.0 or later locally. To see the version installed, run the az --version
command. If you need to install or upgrade, see Install Azure CLI.
You'll need to login to your account using the az login command. Note the id property from the command output for the corresponding subscription name.
az login
If you have multiple subscriptions, choose the appropriate subscription in which the resource should be billed. Select the specific subscription ID under your account using az account set command. Substitute the subscription ID property from the az login output for your subscription into the subscription ID placeholder.
az account set --subscription <subscription id>
Clone or download the sample app
- Git clone
- Download
APPLIES TO: Azure Database for PostgreSQL - Flexible Server
Clone the sample repository:
git clone https://github.com/Azure-Samples/djangoapp
Then go into that folder:
cd djangoapp
The djangoapp sample contains the data-driven Django polls app you get by following Writing your first Django app in the Django documentation. The completed app is provided here for your convenience.
The sample is also modified to run in a production environment like App Service:
- Production settings are in the azuresite/production.py file. Development details are in azuresite/settings.py.
- The app uses production settings when the
DJANGO_ENV
environment variable is set to "production". You create this environment variable later in the tutorial along with others used for the PostgreSQL database configuration.
These changes are specific to configuring Django to run in any production environment and aren't particular to App Service. For more information, see the Django deployment checklist.
Create a PostgreSQL Flexible Server in a new virtual network
Create a private flexible server and a database inside a virtual network (VNET) using the following command:
# Create Flexible server in a VNET[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]az postgres flexible-server create --resource-group myresourcegroup --location westus2
This command performs the following actions, which may take a few minutes:
- Create the resource group if it doesn't already exist.
- Generates a server name if it is not provided.
- Create a new virtual network for your new postgreSQL server. Make a note of virtual network name and subnet name created for your server since you need to add the web app to the same virtual network.
- Creates admin username , password for your server if not provided. Make a note of the username and password to use in the next step.
- Create a database
postgres
that can be used for development. You can run psql to connect to the database to create a different database.
Note
Make a note of your password that will be generate for you if not provided. If you forget the password you would have to reset the password using az postgres flexible-server update
command
Deploy the code to Azure App Service
In this section, you create app host in App Service app, connect this app to the Postgres database, then deploy your code to that host.
Create the App Service web app in a virtual network
In the terminal, make sure you're in the repository root (djangoapp
) that contains the app code.
Create an App Service app (the host process) with the az webapp up command:
# Create a web app[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]az webapp up --resource-group myresourcegroup --location westus2 --plan DjangoPostgres-tutorial-plan --sku B1 --name <app-name># Enable VNET integration for web app.[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]# Replace <vnet-name> and <subnet-name> with the virtual network and subnet name that the flexible server is using.[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]az webapp vnet-integration add -g myresourcegroup -n mywebapp --vnet <vnet-name> --subnet <subnet-name># Configure database information as environment variables[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]# Use the postgres server name , database name , username , password for the database created in the previous steps[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]az webapp config appsettings set --settings DJANGO_ENV="production" DBHOST="<postgres-server-name>.postgres.database.azure.com" DBNAME="postgres" DBUSER="<username>" DBPASS="<password>"
- For the
--location
argument, use the same location as you did for the database in the previous section. - Replace <app-name> with a unique name across all Azure (the server endpoint is
https://\<app-name>.azurewebsites.net
). Allowed characters for <app-name> areA
-Z
,0
-9
, and-
. A good pattern is to use a combination of your company name and an app identifier. - Create the App Service plan DjangoPostgres-tutorial-plan in the Basic pricing tier (B1), if it doesn't exist.
--plan
and--sku
are optional. - Create the App Service app if it doesn't exist.
- Enable default logging for the app, if not already enabled.
- Upload the repository using ZIP deployment with build automation enabled.
- az webapp vnet-integration command adds the web app in the same virtual network as the postgres server.
- The app code expects to find database information in a number of environment variables. To set environment variables in App Service, you create "app settings" with the az webapp config appsettings set command.
Tip
Many Azure CLI commands cache common parameters, such as the name of the resource group and App Service plan, into the file .azure/config. As a result, you don't need to specify all the same parameter with later commands. For example, to redeploy the app after making changes, you can just run az webapp up
again without any parameters.
Run Django database migrations
Django database migrations ensure that the schema in the PostgreSQL on Azure database match those described in your code.
Open an SSH session in the browser by navigating to https://<app-name>.scm.azurewebsites.net/webssh/host and sign in with your Azure account credentials (not the database server credentials).
In the SSH session, run the following commands (you can paste commands using Ctrl+Shift+V):
(Video) Introducing Flexible Server in Azure Database for PostgreSQL & MySQL | Azure Fridaycd site/wwwroot# Activate default virtual environment in App Service containersource /antenv/bin/activate# Install packagespip install -r requirements.txt# Run database migrationspython manage.py migrate# Create the super user (follow prompts)python manage.py createsuperuser
The
createsuperuser
command prompts you for superuser credentials. For the purposes of this tutorial, use the default usernameroot
, press Enter for the email address to leave it blank, and enterpostgres1
for the password.
Create a poll question in the app
In a browser, open the URL http://<app-name>.azurewebsites.net. The app should display the message "No polls are available" because there are no specific polls yet in the database.
Browse to http://<app-name>.azurewebsites.net/admin. Sign in using superuser credentials from the previous section (
root
andpostgres1
). Under Polls, select Add next to Questions and create a poll question with some choices.Browse again to http://<app-name>.azurewebsites.net/ to confirm that the questions are now presented to the user. Answer questions however you like to generate some data in the database.
Congratulations! You're running a Python Django web app in Azure App Service for Linux, with an active Postgres database.
Note
App Service detects a Django project by looking for a wsgi.py file in each subfolder, which manage.py startproject
creates by default. When App Service finds that file, it loads the Django web app. For more information, see Configure built-in Python image.
Make code changes and redeploy
In this section, you make local changes to the app and redeploy the code to App Service. In the process, you set up a Python virtual environment that supports ongoing work.
Run the app locally
In a terminal window, run the following commands. Be sure to follow the prompts when creating the superuser:
# Configure the Python virtual environment[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]python3 -m venv venvsource venv/bin/activate# Install packages[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]pip install -r requirements.txt# Run Django migrations[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]python manage.py migrate# Create Django superuser (follow prompts)[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]python manage.py createsuperuser# Run the dev server[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]python manage.py runserver
Once the web app is fully loaded, the Django development server provides the local app URL in the message, "Starting development server at http://127.0.0.1:8000/. Quit the server with CTRL-BREAK".
Test the app locally with the following steps:
Go to http://localhost:8000 in a browser, which should display the message "No polls are available".
(Video) Azure #17 - Azure Database for PostgreSQL | Azure TutorialGo to http://localhost:8000/admin and sign in using the admin user you created previously. Under Polls, again select Add next to Questions and create a poll question with some choices.
Go to http://localhost:8000 again and answer the question to test the app.
Stop the Django server by pressing Ctrl+C.
When running locally, the app is using a local Sqlite3 database and doesn't interfere with your production database. You can also use a local PostgreSQL database, if desired, to better simulate your production environment.
Update the app
In polls/models.py
, locate the line that begins with choice_text
and change the max_length
parameter to 100:
# Find this lie of code and set max_length to 100 instead of 200[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]choice_text = models.CharField(max_length=100)
Because you changed the data model, create a new Django migration and migrate the database:
python manage.py makemigrationspython manage.py migrate
Run the development server again with python manage.py runserver
and test the app at to http://localhost:8000/admin:
Stop the Django web server again with Ctrl+C.
Redeploy the code to Azure
Run the following command in the repository root:
az webapp up
This command uses the parameters cached in the .azure/config file. Because App Service detects that the app already exists, it just redeploys the code.
Rerun migrations in Azure
Because you made changes to the data model, you need to rerun database migrations in App Service.
Open an SSH session again in the browser by navigating to https://<app-name>.scm.azurewebsites.net/webssh/host. Then run the following commands:
cd site/wwwroot# Activate default virtual environment in App Service container[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]source /antenv/bin/activate# Run database migrations[!INCLUDE [!INCLUDE [applies-to-postgresql-flexible-server](../includes/applies-to-postgresql-flexible-server.md)]python manage.py migrate
Review app in production
Browse to http://<app-name>.azurewebsites.net and test the app again in production. (Because you only changed the length of a database field, the change is only noticeable if you try to enter a longer response when creation a question.)
Tip
You can use django-storages to store static & media assets in Azure storage. You can use Azure CDN for gzipping for static files.
Manage your app in the Azure portal
In the Azure portal, search for the app name and select the app in the results.
By default, the portal shows your app's Overview page, which provides a general performance view. Here, you can also perform basic management tasks like browse, stop, restart, and delete. The tabs on the left side of the page show the different configuration pages you can open.
Clean up resources
If you'd like to keep the app or continue to the next tutorial, skip ahead to Next steps. Otherwise, to avoid incurring ongoing charges you can delete the resource group create for this tutorial:
az group delete -g myresourcegroup
The command uses the resource group name cached in the .azure/config file. By deleting the resource group, you also deallocate and delete all the resources contained within it.
Next steps
Learn how to map a custom DNS name to your app:
Tutorial: Map custom DNS name to your app
Learn how App Service runs a Python app:
Configure Python app
FAQs
Can we use Django in Azure? ›
In this tutorial, you'll deploy a data-driven Python web app (Django or Flask) with the Azure Database for PostgreSQL relational database service. The Python app is hosted in a fully managed Azure App Service which supports Python 3.7 or higher in a Linux server environment.
How do I host my Django app with Azure? ›- [ git init ] Initialize your local repo as a git repo.
- [ git remote add origin ] Link your local repo with the remote repo on GitHub.
- [ git pull ] Pull the remote . ...
- [ git add ] Add all files for staging.
- [ git commit ] Save changes to your local repo by “committing” them.
- Create a repository for your app code.
- Provision the target Azure App Service.
- Create an Azure DevOps project and connect to Azure.
- Create a Python-specific pipeline to deploy to App Service.
- Run the pipeline.
- Run a post-deployment script.
- Considerations for Django.
- Run tests on the build agent.
- Step 1: Creating a Python Virtual Environment for your Project. ...
- Step 2: Creating the Django Project. ...
- Step 3: Pushing the Site to GitHub. ...
- Step 4: Deploying to DigitalOcean with App Platform. ...
- Step 5: Deploying Your Static Files.
For hosting web applications built on Django, you will need to use a platform that lets you deploy the app. One of these platforms is Heroku. Heroku is a cloud platform on which users can build and deploy applications. Heroku relies on Git, a revision control system that lets you manage the program code of your app.
How do I host AWS Django? ›- Step 1: Select EC2 from AWS Console.
- Step 2: Launch a new instance.
- Step 3: Select Ubuntu 18.04 server.
- Step 4: Download pem file which will be used as password.
- Step 5: Wait for initialization to complete.
- Right click the publish folder and select Deploy to Web App...
- Select the subscription the existing Web App resides.
- Select the Web App from the list.
- Visual Studio Code will ask you if you want to overwrite the existing content. Click Deploy to confirm.
- Include the new appsetting. {env}. json in the publishOptions in file project. json .
- Go to Azure Portal and open the web application.
- Select application settings.
- Add an entry for ASPNETCORE_ENVIRONMENT and set it to whatever you want.
- Go to the application folder: Console Copy. cd msdocs-python-flask-webapp-quickstart.
- Create a virtual environment for the app: Windows. macOS/Linux. Cmd Copy. ...
- Install the dependencies: Console Copy. pip install -r requirements.txt.
- Run the app: Console Copy. flask run.
- Create an App Service for your web app on the Azure portal.
- On the App Service's page, scroll to the Development Tools section, select Extensions, then select + Add.
- Scroll down in the list to the extension that contains the version of Python you want:
How do I deploy a webapp in Python? ›
- Brush Up on the Basics. Distribute Your Python Code. ...
- Build a Basic Python Web Application. Set Up Your Project. ...
- Deploy Your Python Web Application. ...
- Convert a Script Into a Web Application. ...
- Improve the User Interface of Your Web Application. ...
- Conclusion.
- Requirements.
- Register a repository on Docker Hub.
- Create the first Azure resources.
- Building and testing the container locally.
- Creating the Azure resources for the Container Instance.
- Optional: Disable access via environment variables to key vault.
Gunicorn is the recommended HTTP server for use with Django on Heroku (as referenced in the Procfile above). It is a pure-Python HTTP server for WSGI applications that can run multiple Python concurrent processes within a single dyno (see Deploying Python applications with Gunicorn for more information).
Where can I deploy Django app for free? ›On Heroku, one can deploy Django apps for free. For your web app, Heroku also lets you choose your own name for your app. Hence you can create custom domain names for your web application and launch it on the internet so that all your friends can see your cool web projects!
Does Django need a web server? ›Django, being a web framework, needs a web server in order to operate. And since most web servers don't natively speak Python, we need an interface to make that communication happen. Django currently supports two interfaces: WSGI and ASGI.
How do I launch Django app? ›- Create a superuser. You will be prompted to enter a username, email, and password. python manage. py createsuperuser.
- Start a local web server: python manage. py runserver.
- Log in to the admin site using the username and password you used when you ran createsuperuser .
- Select Python Version 3.9.12.
- Application Root is the directory where you will place the code files of your Django project. ...
- Application URL is the domain or subdomain where your app will run.
- In the Application Startup File, type passenger_wsgi.py.
- In the Application Entry Point, type application.
- Use the Django framework outside of a project.
- Call Django management commands on an app that is independent of a project.
- Write a script that invokes Django tests, optionally using a single test label.
- Build a setup.py file to define your package.
- Modify the setup.py script to accommodate tox.
Django Rest Framework API / Deploy Django API To AWS ... - YouTube
How do you deploy in asgi Django? ›- Introduction.
- Prerequisites.
- Step 1 — Installing the Packages from the Ubuntu Repositories.
- Step 2 — Creating the PostgreSQL Database and User.
- Step 3 — Creating a Python Virtual Environment for your Project.
- Step 4 — Creating and Configuring a New Django Project.
- Creating the Django Project.
- Adjusting the Project Settings.
How do I deploy Django app to Heroku? ›
- Demo: What You'll Build.
- Project Overview.
- Prerequisites.
- Step 1: Scaffold a Django Project for Hosting. Create a Virtual Environment. ...
- Step 2: Create a Local Git Repository. ...
- Step 3: Create a Free Heroku Account. ...
- Step 4: Install the Heroku CLI.
- Step 5: Log In With the Heroku CLI.
- Prerequisites. ...
- Create an Azure App Service in the Azure portal. ...
- Build your app with Azure Pipelines. ...
- Use the Azure Web App task. ...
- Use a service connection. ...
- Deploy to a virtual application. ...
- Deploy to a slot.
Deploy by using Visual Studio. If you have the Visual Studio solution, right-click the web application project, and then select Publish. Deploy by using an FTP client. In the Azure portal, download the publish profile for the web app that you want to deploy your code to.
How do I deploy to the Azure App Service in Visual Studio? ›Create or open an Azure cloud service project in Visual Studio. In Solution Explorer, right-click the project, and, from the context menu, select Convert > Convert to Azure Cloud Service Project. In Solution Explorer, right-click the newly created Azure project, and, from the context menu, select Publish.
How do I connect to Azure App Service? ›- In the Azure portal, search for and select App Services, and then select your app.
- In the app's left menu, select Configuration > Application settings. ...
- To add a new connection string, click New connection string. ...
- In the dialog, you can stick the connection string to the current slot.
- When finished, click Update.
- Go to the Pipelines page, select the appropriate pipeline, and then select Edit.
- Locate the Variables for this pipeline.
- Add or update the variable.
- To mark the variable as secret, select Keep this value secret.
- Save the pipeline.
The Azure App Service Environment (ASE) is a Premium feature offering of the Azure App Service. It gives a single-tenant instance of the Azure App Service that runs right in your own Azure virtual network (VNet), providing network isolation and improved scaling capabilities.
What are function apps in Azure? ›A function app lets you group functions as a logical unit for easier management, deployment, scaling, and sharing of resources. From the Azure portal menu or the Home page, select Create a resource. In the New page, select Compute > Function App.
How do I deploy Flask app to Azure using GitHub? ›- Prepare your Flask app. First create a your Flask project on your computer (if you haven't yet). ...
- Push to GitHub. ...
- Create an account on Azure. ...
- Create an App Service. ...
- Wait for the App Service to be created. ...
- App Services list. ...
- Connect your GitHub account to Azure. ...
- One last thing.
- Choose a Python version. ...
- Install a text editor or IDE. ...
- Start a new project with virtualenv. ...
- Install Flask and the Twilio Python SDK. ...
- Create a simple Flask application. ...
- The Django Alternative. ...
- Install ngrok.
Does Python install PIP? ›
PIP is automatically installed with Python 2.7. 9+ and Python 3.4+ and it comes with the virtualenv and pyvenv virtual environments.
What is Microsoft Oryx? ›Oryx is a system for building user code into runnable artifacts, in particular for use with Azure Web Apps. It currently supports Python and Node. js codebases. Built artifacts are expected to be used with one of the runtime images also published under mcr.microsoft.com/oryx .
Where is requirements TXT Python? ›It also stores all files and packages on which that project is dependent or requires to run. Typically this file "requirement. txt" is stored (or resides) in the root directory of your projects.
How do I deploy a web application? ›- Select the Web Application node.
- Select the Web Application you want to redeploy.
- Uncheck the Deployed box in the right-hand pane.
- Click Apply.
- Check the Deployed box in the right-hand pane.
- Click Apply.
- Set up your development environment.
- Create a new Ember app using Ember CLI.
- Add more content to your Ember app.
- Create a server with Express.
- Add an interactive Ember route.
- Deploy to Heroku.
- A2 Hosting.
- Kamatera Express.
- Chemicloud.
- Cloudzy.
- PythonAnywhere.
- Platform.sh.
- FastComet.
- Heroku.
- Step1: Create a python code locally which copies input file from storage account and loads it to Azure SQL database.
- Step2: Test the python code locally. Save python code as .py file.
- Step3: Upload . ...
- Step4: Use Custom activity, which in turn uses Azure batch services to take the python code from .
All Microsoft Azure services are available by using Python.
How do I run a Python script from a VM? ›How to write, run and debug a Python script in VMS IDE - YouTube
Do you need Apache with Django? ›Django will work with any version of Apache which supports mod_wsgi. The official mod_wsgi documentation is your source for all the details about how to use mod_wsgi. You'll probably want to start with the installation and configuration documentation.
Is Django good for production? ›
High-level: When to use Django
If you can check even a few of the statements below (without strongly disagreeing with any), chances are that Django is good for your project. You need to develop a web app or API backend. You need to move fast, deploy fast, and also make changes as you move ahead.
Generally, simple django websites cost around INR 35,000 to INR 50,000 excluding server and API costs. If you integrate ReactJS in it, the cost would likely be anywhere north of INR 75,000.
Where can I host my Django backend? ›- Amazon Web Services (AWS)
- Azure (Microsoft)
- Google Cloud Platform.
- Hetzner.
- DigitalOcean.
- Heroku.
Django offers a highly secure approach to develop web applications as it prevents attacks like XSS(Cross-Site Scripting), CSRF (Cross-Site Request Forgery), SQL injection, etc.
Is Django server-side or client side? ›Django is an extremely popular and fully featured server-side web framework, written in Python.
Is Django front end or backend? ›“The technically correct answer,” Willison told me when I asked him about this, “is that a backend framework like Django works with any frontend framework, because of separation of concerns: if a web framework can respond to HTTP requests with JSON and HTML, it can be used with anything.”