- Article
- 9 minutes to read
APPLIES TO: Azure Database for PostgreSQL - Flexible Server
In this tutorial you'll 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 log in 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
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 VNETaz 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 isn't 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 appaz webapp up --resource-group myresourcegroup --location westus2 --plan DjangoPostgres-tutorial-plan --sku B1 --name <app-name># Enable VNET integration for web app.# Replace <vnet-name> and <subnet-name> with the virtual network and subnet name that the flexible server is using.az webapp vnet-integration add -g myresourcegroup -n mywebapp --vnet <vnet-name> --subnet <subnet-name># Configure database information as environment variables# Use the postgres server name , database name , username , password for the database created in the previous stepsaz 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 many 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) How to deploy PostgreSQL on Azurecd 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 environmentpython3 -m venv venvsource venv/bin/activate# Install packagespip install -r requirements.txt# Run Django migrationspython manage.py migrate# Create Django superuser (follow prompts)python manage.py createsuperuser# Run the dev serverpython 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) Introducing Flexible Server in Azure Database for PostgreSQL & MySQL | Azure FridayGo 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 200choice_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 containersource /antenv/bin/activate# Run database migrationspython 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
How do I deploy Django project on Azure App Service? ›
- [ 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.
- Sign in to the Azure portal. ...
- Create an Azure Database for PostgreSQL flexible server. ...
- Create an Azure Linux virtual machine. ...
- Install PostgreSQL client tools. ...
- Connect to the server from Azure Linux virtual machine. ...
- Clean up resources.
- Step 1 — Install and Configure Python 3. ...
- Step 2 — Install PostgreSQL. ...
- Step 3 — Configure PostgreSQL. ...
- Step 4 — Create a Virtual Environment. ...
- Step 5 — Install Django. ...
- Step 6 — Generate a Django Project. ...
- Step 7 — Start a Django App. ...
- Step 8 — Configure the Database Connection.
- 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.
Navigate to your app in the Azure portal and select Deployment Center under Deployment. Follow the instructions to select your repository and branch. This will configure a DevOps build and release pipeline to automatically build, tag, and deploy your container when new commits are pushed to your selected branch.
How do I deploy a Python application in Azure App Service? ›- 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.
- Start Azure Data Studio.
- The first time you start Azure Data Studio the Connection dialog opens. ...
- In the form that pops up, go to Connection type and select PostgreSQL from the drop-down.
- Fill in the remaining fields using the server name, user name, and password for your PostgreSQL server.
For organizations that need to customize their PostgreSQL deployments, and need to overcome the limitations of the Azure Database for PostgreSQL managed service, the self-managed Azure VM option is the most appropriate option.
What is Azure Database for PostgreSQL Flexible servers? ›Azure Database for PostgreSQL - Flexible Server is a fully managed database service designed to provide more granular control and flexibility over database management functions and configuration settings.
How to deploy Django project with PostgreSQL? ›...
Django application
- Create a new project.
- Create a new environment.
- Create a new application. To follow the guide, you can fork and use our repository. ...
- Select application port. After the application is created: ...
- Use Dockerfile.
How do you create a Django app and connect it to a database? ›
- Step - 1: Create a virtual environment and setting up the Django project.
- Step - 2 Create new Database.
- Step - 3: Update the settings.py.
- Step - 4 Install mysqlclient package.
- Step - 5 Run the migrate command.
- Install ODBC driver: Instructions.
- Install pyodbc: Python Copy. pip install pyodbc.
- Install mssql-django: Python Copy. pip install mssql-django.
Postgresql is the preferred database for Django applications due to its open-source nature; and it's also ideal for complex queries.
Which server is best for Django? ›- Amazon Web Services (AWS)
- Azure (Microsoft)
- Google Cloud Platform.
- Hetzner.
- DigitalOcean.
- Heroku.
The Django developer team itself recommends that you use Python virtual environments!
What are the three kinds of app service in Azure? ›- Web Apps.
- API Apps.
- Logic Apps.
- Function Apps.
Go to App Service plan > Networking > VNet integration in the portal. Select the virtual network your app connects to. Under the routing section, add the address range of the virtual network that's peered with the virtual network your app is connected to.
How many apps can I run on Azure App Service plan? ›Usage Tiers | Free Try for free | Premium Enhanced performance and scale |
---|---|---|
Web, mobile, or API apps | 10 | Unlimited |
Disk space | 1 GB | 250 GB |
Maximum instances | – | Up to 30* |
Custom domain | – | Supported |
- In Solution Explorer, right-click the project and select Publish.
- In the Publish dialog, select Azure and select the Next button.
- Select Azure App Service (Windows) and select the Next button.
- Select Create a new Azure App Service. ...
- Select the Create button.
We can deploy our mobile backend services on Azure using Azure Mobile apps. By implementing our mobile backend service on Azure, our mobile backend will be able to communicate with different Azure services. We can able to take advantage of various features that are provided by Azure Mobile Apps.
How does Python connect to Azure Database? ›
- Step 1: Connect. import pyodbc cnxn = pyodbc.connect('DRIVER={Devart ODBC Driver for SQLAzure};Server=myserver;Database=mydatabase;Port=myport;User ID=myuserid;Password=mypassword')
- Step 2: Insert a row. ...
- Step 3: Execute query.
- An Azure account with an active subscription. Create an account for free.
- An Azure Database for PostgreSQL - Flexible Server. To create flexible server, refer to Create an Azure Database for PostgreSQL - Flexible Server using Azure portal.
- Python 2.7 or 3.6+.
- Latest pip package installer.
To access Azure Database for PostgreSQL from your local computer, ensure that the firewall on your network and local computer allow outgoing communication on TCP port 5432.
How do I connect to a Postgres database application? ›- Step 1: Launch SQL Shell (psql) program tool.
- Step 2: To use the default value specified in the square bracket [ ], just press Enter and move on to the next line. ...
- Step 3: Now, interact with the database server using SQL commands.
PostgreSQL is based on 𝐇𝐓𝐀𝐏 (Hybrid transactional/analytical processing) architecture, so it can handle both OLTP and OLAP well.
How do I deploy a PostgreSQL Database in Azure? ›- Sign in to the Azure portal. Open your web browser and go to the portal. ...
- Create an Azure Database for PostgreSQL server. ...
- Get the connection information. ...
- Connect to the PostgreSQL database using psql. ...
- Clean up resources. ...
- Next steps.
Azure Database for PostgreSQL is a fully-managed database as a service with built-in capabilities, such as high availability and intelligence.
Is Azure Database for PostgreSQL PaaS or SAAS? ›With Azure, your PostgreSQL Server workloads can run in a hosted virtual machine infrastructure as a service (IaaS) or as a hosted platform as a service (PaaS).
Which is faster Postgres or SQL Server? ›We mentioned partitioning, and while both PostgreSQL and SQL Server support partitioning, PostgreSQL does so more efficiently and for free. PostgreSQL also has better concurrency, which is important when multiple processes need to access and modify shared data at the same time.
Is Azure Database for PostgreSQL free? ›You're not charged for Azure Database for PostgreSQL - Flexible Server services that are included for free with your Azure free account unless you exceed the free service limits.
How do I run a Django project in a virtual environment? ›
- Install Package. First, install python3-venv package by using the following command.
- Create a Directory. $ mkdir djangoenv. ...
- Create Virtual Environment. $ python3 -m venv djangoenv. ...
- Activate Virtual Environment.
Benefits of using PostgreSQL with Django
Django has django. contrib. postgres to make database operations on PostgreSQL. If you are building an application with maps or you are storing geographical data, you need to use PostgreSQL, as GeoDjango is only fully compatible with PostgreSQL.
Django officially supports the following databases: PostgreSQL. MariaDB. MySQL.
How does Django integrate with existing database? ›- Create a Django project by running django-admin.py startproject mysite (where mysite is your project's name). ...
- Edit the settings file in that project, mysite/settings.py , to tell Django what your database connection parameters are and what the name of the database is.
- Download Python installer. Install Python3 if your machine does not have it. Visit Python download page.
- Install and verify Python. a. Double click the installer, follow instructions on the screen. b. After finished install. Run py -V in command line to verify it.
Django uses the database with the alias of default when no other database has been selected. If you attempt to access a database that you haven't defined in your DATABASES setting, Django will raise a django. utils. connection.
What is the best way to connect your Azure VM to your Azure SQL Database? ›First, connect to the SQL Server virtual machine with remote desktop. After the Azure virtual machine is created and running, click the Virtual Machines icon in the Azure portal to view your VMs. Click the ellipsis, ..., for your new VM. Click Connect.
How do I connect Azure SQL Database to Web app? ›- In the Publish dialog, scroll down to the Service Dependencies section. ...
- Select Azure SQL Database and click Next.
- In the Configure Azure SQL Database dialog, click +.
- Next to Database server, click New. ...
- Add an administrator username and password. ...
- Click OK.
- On the MySQL server blade, under the Settings heading, click Connection Security to open the Connection Security blade for Azure Database for MySQL.
- Select ON in Allow access to Azure services, then Save.
One of the main disadvantages or cons of using Django for web app development is it presents a steep and deep learning curve to budding and novice developers and designers. Even though it is a clear and simple framework developed using python language. It can make things difficult to learn for inexperienced developers.
Should I use PostgreSQL or MySQL for Django? ›
“Django provides support for a number of data types which will only work with PostgreSQL. There is no fundamental reason why (for example) a contrib. mysql module does not exist, except that PostgreSQL has the richest feature set of the supported databases so its users have the most to gain.”
What is the limitation of Django? ›Not for smaller projects. All the functionality of Django comes with lots of code. It takes server's processing and time, which poses some issues for low-end websites which can run on even very little bandwidth.
What is the best way to deploy Django app? ›- 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.
Even though Django never got to the same level of popularity as Ruby, it has managed to grow over the years. I've personally been using it for over 15 years. Version 3.1 was recently released as of a few months ago. Some of the largest websites in the world using Django are Instagram, Pinterest & Mozilla.
Is NASA using Django? ›5. NASA. The website of the United States National Aeronautics and Space Administration (NASA) is built using Django.
Do professionals use Django? ›Django is a Python-based web framework giving developers the tools they need for rapid, hassle-free development. You can find that several major companies employ Django for their development projects. Here are 9 global companies using Django: Instagram.
Does Django use MVC or MVT? ›From IDEA to Product Using Python / Django
And like most modern framework, Django supports the MVC pattern. First let's see what is the Model-View-Controller (MVC) pattern, and then we will look at Django's specificity for the Model-View-Template (MVT) pattern.
Visual Studio Code
VS Code is a complete code editor with premium features and many coders say it's the best IDE editor out there. Compatibility: Windows, Linux, Mac OS. Top plugins and features: Built-in git.
- Install packages and configure variables We install packages needed for production and add a . ...
- Create requirements. ...
- Make changes to our settings. ...
- Make sure that the production settings are used in deployment.
- Push code updates to GitHub.
- Pushing our code to Azure.
- Migrating our database schema.
- Prepare your environment.
- Create backing services.
- Run the app on your local computer.
- Use the Django admin console.
- Deploy the app to the App Engine standard environment.
- Updating the application.
- Configuring for production.
- Understand the code.
How do I deploy Django? ›
- Initialize your Django application's local database. ...
- Run manage.py createsuperuser to create an administrator. ...
- Run manage.py collectstatic to populate the static directory with static assets (JavaScript, CSS, and images) for the admin site. ...
- Deploy your application.
- Amazon Web Services (AWS)
- Azure (Microsoft)
- Google Cloud Platform.
- Hetzner.
- DigitalOcean.
- Heroku.
- Install ODBC driver: Instructions.
- Install pyodbc: Python Copy. pip install pyodbc.
- Install mssql-django: Python Copy. pip install mssql-django.
The Django sample application configures settings in the azureproject/production.py file so that it can run in Azure App Service. These changes are common to deploying Django to production, and not specific to App Service.