How to Quickly Start a Django Project and a Django App

    Daniel Diaz
    Share

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

    Django is the Python web framework of choice for building web applications. It’s a mature, full-featured, flexible and open-source framework that lets you build anything from a simple CRUD application to a more complex, multi-app project like a photo-sharing app.

    Requirements

    You don’t need previous knowledge to set up a Django project. But Django is a Python framework, so to use it you should have strong foundations using Python.

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

    Most macOS and Linux systems have Python 3 installed by default, but if you’re using Windows, you’ll need to download and install Python. You can follow this guide from the official Python website.

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

    Open a terminal with application finder

    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 # My result
    

    If you didn’t get a result of the form Python 3.x, don’t panic. There are two options:

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

      python3 --version
      
      Python 3.9.7 # Again, my result
      
    • if you got an Unknown command error, tried to run python3, and still got another error, you’ll need to download and install Python from the official website.

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

    What’s a Django Project?

    A Django project is a Python package needed to make a web application work. It contains everything you need to build the backend (server-side development, what the 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 retrieved, and so on.

    You can also think of it as a collection of settings, and small Python modules named apps. We’ll talk about them later, but as a pre-concept, an app is another set of Python files that solve a specific task of your app.

    Through this article, you’ll learn about the sophisticated structure of a Django project. But from the start I want you to know that a Django project can be narrowed down 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 bring a Django “Hello, World!” project to life:

    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('<h1>A minimal Django response!</h1>')
    
    
    urlpatterns = [
        path(r'', index),
    ]
    
    if __name__ == '__main__':
        execute_from_command_line(sys.argv)
    

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

    How to Set up a Django Project

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

    First of all, you need to know that Django is an external package. In other words, it doesn’t come built-in with Python, so you’ll need 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’ll need to create a virtual environment. It’s a good practice to create a virtual environment for each Django project you build, so you can keep track of dependencies.

    Maybe the code you have in a Django 2.6 project may not work with Django 3.0. A virtual environment lets you 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’ll 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 active your virtual environment, you need to activate it with the following command:

    source .venv/bin/activate
    

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

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

    A way to check that your shell is activated is by looking for changes in your prompt. In my case, what I saw is pictured below.

    Virtual Environment Prompt

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

    pip install django # Latest version
    pip install django==2.2 # Specific version
    

    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>
    

    It’s worth mentioning that some names are reserved for Django — django or django-admin. Don’t worry if you get an error. Just try to use a different project name:

    django-admin startproject django
    # CommandError: 'django' conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name.
    django-admin startproject django-admin
    # CommandError: 'django-admin' is not a valid project name. Please make sure the name is a valid identifier.
    

    A common practice is to name your project as config, and this has some 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 on 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 chose, 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 of your project. It doesn’t matter to Django, so you can actually rename it to whatever you want.
    • config/config/ is the actual Django project folder. It contains the setting files of your project.
    • manage.py is a Python script with the same functionality of django_admin but uses your project’s settings.
    • __init__.py makes config/config a Python package.
    • settings.py is the core file of 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 let you deploy your project to a server.

    I know Django’s project structure may be a bit complex at the start, but with time, it starts to just make sense. Every file has a purpose, and the development process becomes really pleasant.

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

    django-admin startproject <project_name> .
    

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

    django-admin startproject config .
    

    Try each command on your own, and decide which one is the best for you.

    To finish this section, we’ll start the Django development server, and check 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 in localhost:8000/ and you should see Django’s default page.

    Django welcome page

    How to Set up a Django App

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

    From the official docs: “An app is a Web application that does something”. That something is a specific functionality such as a user’s app, a comments app, a chat app.

    The more feature-targeted your apps are, the better.

    A Django application is self-contained, which means it can be reused from project to project. That’s why you can install an external app, like Django-allauth, and use it in your project, just by adding it to the INSTALLED_APPS variable.

    You’ll spend most of your time working with apps, because, one by one, they build all the features of your project.

    From now on, you’ll be using the manage.py utility, so to create an app, 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 your app names. If you want to create an app for integrating payments with PayPal, or Stripe, name it simply payments:

    python manage.py startapp payments
    

    Let’s go in-depth into the structure of a Django app:

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

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

    Command Cheatsheet

    We’ve used a lot of commands in this tutorial, so here’s a summary of the purpose of each command.

    Command Description
    python -m venv (name_of_venv) Creates a virtual environment
    source (venv)/bin/activate Activates a virtual environment
    django-admin startproject (project_name) Starts a Django project
    django-admin startproject (project_name) . Sets up a project in the same directory
    python manage.py runserver Runs the Django server
    python manage.py startapp (app_name) Creates a Django app

    Conclusion

    Django is a full-battery web framework that lets you build any kind 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 learned to:

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

    To tke this a step further, check out “Build a Photo-sharing App with Django”.