How to quickly start a Django project and a Django application

0


In this tutorial, we’ll learn the difference between a Django project and a Django application, and how to start a new Django project.

Django is the Python web framework of choice for building web applications. It is a mature, comprehensive, flexible and open source framework that allows you to create anything from a simple CRUD app to a more complex multi-app project like a photo sharing app.

Conditions

You don’t need any prior knowledge to set up a Django project. But Django is a Python framework, so to use it you need to have a solid foundation using Python.

Before you begin, make sure you have a terminal or command prompt with Python 3.6 or later.

Python 3 is installed by default on most macOS and Linux systems, but if you are using Windows you will need to download and install it Python. You can follow this guide from Python official site.

You can open a terminal by opening the application finder for your operating system and searching for Terminal, or under Windows, cmd.

Once you’ve set up a terminal, it’s time to confirm your Python version. To do this, type the following command:

python --version

Python 3.9.7 

If you didn’t get any output from the Python 3.x form, don’t panic. There are two options:

  • if python --version returned a Python 2.x version, you will need to use python3 with this tutorial. This usually happens with some macOS systems, as well as some Linux distributions like Ubuntu. Try to run the following command:

    python3 --version
    
    Python 3.9.7 
    
  • if you have a Unknown command error i tried to run python3, and still another error, you will have to download and install Python from the official site.

Now that you know which Python command to run in your terminal, let’s dive into Django projects.

What is a Django project?

A Django project is a Python package required for a web application to function. It contains everything you need to build the backend (server side development, what users don’t see) of your site. The normal functionality of a Django project determines how you interact with the database, authentication, how data is fetched, etc.

You can also think of it as a collection of parameters and small Python modules called apps. We’ll cover that later, but as a pre-concept, an app is another set of Python files that solve a specific task for your app.

Through this article, you will learn about the sophisticated structure of a Django project. But right off the bat, I want you to know that a Django project can be reduced to a single file, something similar to a Flask project.

A quick demonstration of this is the Minimal django project. This is a file with 23 lines of code that allows us to provide a Django “Hello, World!” life Project :

import sys

from django.conf import settings
from django.urls import path
from django.core.management import execute_from_command_line
from django.http import HttpResponse

settings.configure(
    DEBUG=True,
    ROOT_URLCONF=sys.modules[__name__],
)


def index(request):
    return HttpResponse('

A minimal Django response!

'
) urlpatterns = [ path(r'', index), ] if __name__ == '__main__': execute_from_command_line(sys.argv)

Now, a Django project can go much further. A good example is Instagram, which has thousands of Django endpoints and still uses this framework for crucial functionality.

How to configure a Django project

Don’t be too concerned if some of the following commands seem complex. After you’ve created a few projects, you’ll know them like the back of your hand.

First of all, you should know that Django is an external package. In other words, it is not integrated with Python, so you will have to install it with PIP.

PIP is a package manager for Python, a tool that allows you to install Python packages from the Python package index (PyPI).

Now, before installing the actual Python package, you need to create a virtual environment. It’s a good practice to create a virtual environment for each Django project you build, so that you can keep track of dependencies.

Maybe the code you have in a Django 2.6 project won’t work with Django 3.0. A virtual environment allows you to have specific requirements for each project you have.

You can create a virtual environment named .venv (or whatever name you want) with the following command:

python -m venv .venv

Now if you list the files in the current directory you will see a new folder called .venv, which at the same time contains isolated Python binaries:

$ ls -lah .venv/
Permissions Size User   Date Modified Name
drwxr-xr-x     - daniel 10 nov 23:13  .
drwxr-xr-x     - daniel 10 nov 23:13  ..
drwxr-xr-x     - daniel 10 nov 23:13  bin
drwxr-xr-x     - daniel 10 nov 23:13  include
drwxr-xr-x     - daniel 10 nov 23:13  lib
lrwxrwxrwx     3 daniel 10 nov 23:13  lib64 -> lib
.rw-r--r--    69 daniel 10 nov 23:13  pyvenv.cfg

To activate your virtual environment, you must activate it with the following command:

source .venv/bin/activate

This will only work on bash shells (available on macOS and Linux). If you are using another shell, you can take a look at the next activation venv table:

Platform Shell Command to activate the virtual environment
POSIX bash / zsh $ source .venv> / bin / activate
fish $ source .venv> /bin/activate.fish
csh / tcsh $ source .venv> /bin/activate.csh
PowerShell kernel $ .venv / bin / Activate.ps1
the Windows cmd.exe C: > .venv Scripts activate.bat
PowerShell PS C: > .venv Scripts Activate.ps1

One way to verify that your shell is enabled is to look for changes in your prompt. In my case, what I saw is illustrated below.

Virtual environment prompt

Now install the Django package. You can install the latest version or a specific version of Django:

pip install django 
pip install django==2.2 

Start the project

Once you’ve installed Django, to start a new project, you call the django-admin command line utility and run:

django-admin startproject <project_name>

Note that some names are reserved for Django – django Where django-admin. Don’t worry if you get an error. Just try using a different project name:

django-admin startproject django

django-admin startproject django-admin

A common practice is to name your project as config, and this has certain advantages. First, it’s a name that you can keep consistent across all of your projects, and second, normally the “project” folder only stores configuration related files. You can read more about the official Django Forum:

django-admin startproject config

Django project structure

Once you’ve started a Django project, you’ll see a new folder with the name of the project you’ve chosen and a structure similar to this:

.
├── config
│   ├── config
│   │   ├── asgi.py
│   │   ├── __init__.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
└── .venv

Let’s analyze each part in depth:

  • config/ is the external folder for your project. It doesn’t matter to Django, so you can rename it however you want.
  • config/config/ is the actual Django project folder. It contains the configuration files for your project.
  • manage.py is a Python script with the same functionality as django_admin but uses your project settings.
  • __init__.py makes config/config a Python package.
  • settings.py is the base file for your project. You can add, modify or delete variables to change the behavior of your project.
  • urls.py is the file that defines the URLs of your project.
  • asgi.py and wsgi.py allow you to deploy your project on a server.

I know Django’s project structure can be a bit complex at first, but over time it starts to make sense. Each file has a purpose, and the development process becomes really enjoyable.

A common shortcut is to omit the creation of the external folder. This is useful because you won’t have to change your project structure when deploying to something like Heroku:

django-admin startproject <project_name> .

So, for example, for each Django project that you start, you can run the following command:

django-admin startproject config .

Try each order for yourself and decide which one is right for you.

To complete this section, we’ll start the Django development server and verify that the project setup was successful.

Go to the root folder of your project (where manage.py is located) and start the server with this command:

python manage.py runserver

Now jump into your browser, type localhost: 8000 / and you should see Django’s default page.

Django home page

How to configure a Django application

As I told you earlier, a Django project is different from a Django application.

According to the official doc: “An application is a web application that does something”. That something is a specific feature such as user app, comment app, chat app.

The more feature-focused your apps, the better.

A Django app is stand-alone, which means it can be reused from project to project. Therefore, you can install an external application, such as Django-allauth, and use it in your project, simply by adding it to the INSTALLED_APPS variable.

You will spend most of your time working with applications, because one by one they create all the functionality of your project.

From now on, you will use the manage.py utility, so to create an application, go to the root folder of your project and run the following command:

python manage.py startapp <app_name>

Try to be as specific as possible with the names of your apps. If you want to build an app to integrate payments with PayPal or Stripe, just name it payments:

python manage.py startapp payments

Let’s learn more about the structure of a Django application:

.
├── config
│   ├ ...
├── manage.py
└── payments
    ├── admin.py
    ├── apps.py
    ├── __init__.py
    ├── migrations
    │   └── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py
  • payments/ is the folder for your application.
  • admin.py is used to register models in the Django admin interface.
  • apps.py defines the configuration of the application.
  • models.py is used to store models, which are the objects we create to store and control data.
  • migrations/ is the folder that contains the application migration scripts. You run migrations to apply changes from our models to a database.
  • tests.py is used to test the application.
  • views.py is the file in which we define the views of our application. A view is a Python callable that receives an HTTP request and returns an HTTP response.

In your apps, you can create other files and folders, and even create templates, which are Django’s way of dynamically displaying data on a web page.

Order reminder

We’ve used a lot of commands in this tutorial, so here’s a summary of what each command is about.

Order The description
python -m venv (name_of_venv) Create a virtual environment
source (venv)/bin/activate Activate a virtual environment
django-admin startproject (project_name) Starts a Django project
django-admin startproject (project_name) . Configure a project in the same directory
python manage.py runserver Run the Django server
python manage.py startapp (app_name) Create a Django application

Conclusion

Django is a full-battery web framework that lets you build any type of application. Setting up a Django project is quick and easy, and you can start working on your project right away.

With this tutorial, you have learned how to:

  • create a virtual environment
  • install a specific version of Django
  • start a Django project
  • run a Django server
  • create a Django app
  • differentiate between a Django application and a Django project

To learn more, see “Create a photo sharing app with Django”.


Share.

Comments are closed.