Django Web Application

Setting up Python Django on Mac – Part 1

Share and Enjoy !

Shares

Table of Contents

  1. Virtual environment
    1. Create a Virtual Environment.
    2. Activate and Deactivate the Virtual Environment.
  2. Install packages
    1. Tracking Dependencies.
    2. Reinstalling Dependencies
  3. First Django Project
  4. Folder Structure
  5. Development Server
  6. Conclusion

Python Django is a free web framework. It is an open-source, high-level Python framework that helps programmers build clean applications. It is a popular framework because Django provides speed, flexibility, scalability and high security to the application. 

Before starting, I hope you already have Python on your machine. If not, you can go through the Python installation tutorial. The below command will check the list of packages installed globally for our system.

We use the most popular Python package installer, “pip” to install and manage Python packages for projects. If you have Python 3 installed on your machine then do not worry, PIP is already installed. We will ensure it is updated to the latest version before proceeding.

$ python -m pip install --upgrade pip
$ pip list OR pip3 list
Python Django - Pip List
Setting Up Python Django On Mac - Part 1 5

Virtual environment

You may face version issues when you are working on multiple projects. For example, you installed the Python Django framework on your system ( Globally ) and started a project called myProject1. At that time, the Python Django version was x.x.1. Now you have upgraded the version to x.x.2 for your new Python project called myProject2. You have two projects using different versions, the first will use an older version, and the second will use a recent version. Your first Python project may not work correctly with the updated version. It will be excruciating to manage multiple projects with multiple package versions. 

To avoid the above situation, we need a virtual environment which helps us create a virtual area for every web project. Whatever packages we require in a project will be installed in a virtual environment. Each package is now limited to that web project and does not affect another one. The virtual environment is a self-contained directory. We can activate and deactivate it by command. By using a virtual environment, we can organise Python Django project dependencies with any conflicts.

Create a Virtual Environment.

Let’s start the Python Django installation. The first step is to create a virtual environment for Python Django. Create a parent directory where you will create a virtual environment along with auto-generated web application directories and files. It is best practice to create a parent directory for every Python project. Use the below command to create a virtual environment.

$ mkdir django_demo - # Parent or Root folder 
$ cd django_demo
$ python -m venv demo_venv

You can see the environment folder django_venv. Now let’s learn how to activate or deactivate the environment.

Activate and Deactivate the Virtual Environment.

When we activate the virtual environment, you ensure that all Python packages will be installed in an isolated directory. After activation, we can use the project’s own Python interpreter and install any package that will be used in your project. 

$ source demo_venv/bin/acticate (environment_name/bin/activate)

The virtual environment is now created and activated successfully. Executing the “which python” command will show a virtual environment’s Python path that can be used in our project. Python version will be the same as was used to create a virtual environment. We will learn in our other blog about changing or updating versions of the Python frameworks or packages or dependencies.

(demo_venv) $ which python

/Users/arjunondkar/Projects/python/django_demo/demo_venv/bin/python

We can see a Python interpreter and other management scripts in a virtual environment folder that we will use during project development.

To deactivate the environment execute the deactivate command, and your command prompt will return to normal. It is best practice to deactivate the development environment once you have completed your work. Now pip or python commands will interact with your globally installed Python environment and not from environment Python. 

Note:

Do not save any project file or folder in the environment folder.

Install packages

Now time to install packages for the Python project. Some default packages are already installed when you create a virtual environment. We can check which packages are installed by executing the pip3 list or pip list command. 

(demo_venv) $ python -m pip install <package_name>

The above command will install the Python package and dependencies in an isolated location. You must ensure that your virtual environment is activated before installing any package. Check your command prompt, The name of the virtual environment must be visible in parentheses, as you can see in the above example (demo_venv). If it is missing, then your Python environment is inactive and you can not install packages. Without activation when you install the package it will install globally. Another way to check is, to execute the “which python” command, It will point to your project path if the development environment is active it will show the global Python path.

PyPi ( Python Package Index ) is the centre location of all Python packages and dependencies where developers can develop and share Python packages, and frameworks. It is a package repository developed by the Python community. We are setting up the Python Django project. Django is a web framework and it is also hosted on PyPi. We will use the Python package manager, ‘pip’ to install it. There are multiple Python Django versions available. Always use the latest version whenever you start a new project. You can install any version by mentioning the package’s version in the installation command. 

(demo_venv) $ python -m pip install django

The above command will install the latest version of a package. Suppose you want to install a specific version, so how will install the required version package? It is simple, you just need to mention the package version.

(demo_venv) $ python -m pip install django=4.2.0
(demo_venv) $ pip list

Tracking Dependencies.

Dependency management is an important setup. Why it is important? Many times multiple developers are working on many Python Django projects then we must ensure everyone using the same packages, frameworks and versions. It also helps us during the deployment of a project on a production server. We know which dependencies and their versions we need to be installed on a production server.

To avoid any issues, we will create requirement.txt which will record a list of packages and their versions. Execute the following command to generate requirement.txt. The freeze command will write the package name and its version which is used in creating a website with Python Django project. With the help of this Txt file, we can install all packages in a single command.

$ python -m pip freeze - will display the name and version of packages
$ python -m pip freeze > requirement.txt - will write name and version of packages in mention file.
Freeze Requirement Txt File
Setting Up Python Django On Mac - Part 1 6

After every package installation, please update your requirement.txt file to avoid any mismanagement. 

Reinstalling Dependencies

In any case, if you lost your environment or want to recreate a project then you can reinstall all your dependencies using requirment.txt.

$ pip install -r requirement.txt

First Django Project

Now you have set up everything, created a virtual environment, and installed packages let’s start our Django web development with Python. The complete project is divided into two parts, the first section is the Project and the second section is the App. So a project is a parent directory, carrying and controlling the entire web applications. Every project can have multiple Apps. Let’s create our first project.

So Django-admin is a command line tool which helps us to do some administrative tasks like running the development server and creating projects and applications.

(demo_venv) $ django-admin startproject <Project Name>

So django-admin startproject command will create some directories and Python files. This is a basic structure which will be generated every time whenever we execute the strartproject command. The project structure is as follows.

(demo_venv) $ django-admin startproject django_demo

django_demo/ - Root Directory
    ├── django_demo - Project Directory
    │   ├── __init__.py
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── manage.py 

You noticed two directories generated with the same name i.e. django_demo. A top-level directory is an actual root directory holding the virtual environment, project directory and its files. You can change the name of the root directory anytime, it will not affect the project’s executions. But you can not change the project directory name. In this directory, we have a project configuration file.

If you do not want to follow the above folder structure and want to ignore the top directory, add a dot (.) at the end of a command. It will generate a project directory and files under the current working directory.

(demo_venv) $ django-admin startproject django_demo .

Folder Structure

Django follows the Model-View-Controller ( MVC ) architecture pattern. It will be called Model-View-Template ( MVT ) architecture. You may understand from its name, the entire web project is divided into the following three parts.

Model: Database structure and Data process component.

Views: It handled presentation logic and interaction with the Template.

Template: HTML and presentation data rendered by View.


Working director OR django_demo/ – Root Folder

manage.py: This file will help us to interact with our project you can run a server, create database models, and more.

django_demo/: It is the main project directory. It contains configuration and setting files.


Working director OR django_demo/django_demo/

setting.py: This file contains various configuration and setting details of the web project such as Database settings, Application settings, security keys, debugs settings, Template details and more.

urls.py: This file defines URL routing details for the web project. 

asgi.py and wsgi.py: This file provides configuration for ASGI ( Asynchronous server gateway interface ) and WSGI ( Web server gateway interface ). It helps serve your web application.

Development Server

Python Django comes with an in-build local development server. It is lightweight and runs on default port 8000 on the default IP address 127.0.0.1. It is also known as a “loopback address”. We will execute the below command to run a development server. If everything is configured correctly our server will start.

(demo_venv) $ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 02, 2023 - 10:39:20
Django version 4.2.4, using settings 'django_demo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

You can ignore the red warning. We will learn about it in our following tutorial. Currently, we can check whether our application is properly working or not. We can visit http://127.0.0.1:8000 in your browser. If you wish to change the port, you can do so by specifying a different port. For example, run (demo_venv) $ python manage.py runserver 8080 in your virtual environment.

Django Web Application
Setting Up Python Django On Mac - Part 1 7

The development server automatically reloads on every request, so most of the changes in our code take effect. Adding new files and after resolving errors, we need to restart our server manually.

Conclusion

Starting from the basics is the best way of learning any technology. You will lead to an advanced level by practising whatever you will learn. We are trying to cover every point that needs to be understood. We will learn more about fundamentals, how to build a database model, the admin interface, and more—already covered creating virtual environments and projects. If you face any issues or have any queries, please write a comment we will try to resolve it. You can always refer to the official document (https://docs.djangoproject.com/) for understanding details.

89 / 100

Share and Enjoy !

Shares

Leave a Reply