Everything you need to know about Django(Python) as a  Beginner

Everything you need to know about Django(Python) as a Beginner

As a newbie, forget all the noise and learn Django for backend web development (well do your research and see what is suitable for you).

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. In this article, we'll cover everything a beginner needs to know about Django.

What is Django

Django is a powerful, free and open-source Python web framework that simplifies the development of complex, database-driven websites. Some of the notable sites that use Django are Dropbox, Instagram, NASA, Mozilla, and Disqus.

Django follows the “batteries included” philosophy, which means that it comes with a lot of built-in features, such as, an ORM (Object-Relational Mapper), authentication, multiple database support and security which allows a developer to generate a powerful website as quickly as possible

One of the main benefits of using Django is its emphasis on convention over configuration, which means that it has a set of pre-defined conventions for things like project layout and database schema, so you don’t have to spend a lot of time configuring your application. This makes it easy for new developers to get up and running quickly.

Now let's dive in.

Let's Dive in

Installation and Setup

To start using Django, you need to have Python installed on your system. You can check if you have Python installed by running the following command in your terminal: python --version

If you don't have Python installed, you can download it from the official Python website (python.org) and follow the installation instructions.

Once Python is installed, you need to choose a directory for your project: and then open your terminal or Powershell and run the following command.

cd desktop  # or documents or anywhere you want

# you can then create a folder for your project and cd into the folder
mkdir django-project
cd django-project

# open vscode 
code.

Before we install Django we need to install and activate a virtual environment. Think of the virtual environment as a container that helps us isolate our project dependencies.

# install the virtual environment
pip install virtualenv

# create the virtual environment
virtualenv env 

# to activate the virtual environment (on windows) 
env\Scripts\activate

# activating the virtual environment (on macOS) 
source env/bin/activate

Now let's install Django. You can do this by running the following command.

pip install django

Django project structure

Once Django is installed, you can create a new project by running the following command:

django-admin startproject myproject

This will create a new directory called "myproject" with the basic structure of a Django project. A Django project consists of one or more apps, and each app can have multiple models, views, and templates.

Here's a breakdown of the main directories and files in a Django project:

  • manage.py : A command-line utility that lets you interact with this Django project in various ways.

  • __init__.py : An empty file that tells Python that this directory should be considered as a Python package.

  • settings.py : settings for this Django project, such as database configurations, installed apps and middleware.

  • urls.py : The URL declarations for this Django Project

  • asgi.py : An entry point for ASGI-compatible web servers to serve your project.

  • wsgi.py : An entry point for WSGI-compatible web servers to serve your project

Now run your basic server using this command

python manage.py runserver

The output of the command should be visible in your broswer with this link- https://127.0.0.1:8000 like this:

Next, you will need to create a Django "app" within your project. An app is a self-contained unit of code that performs a specific function in your project. You can create an app by running the following command:

python manage.py startapp myapp

This will create a new directory called "myapp" with the basic structure of a Django app. The most important file in this directory is views.py, which contains functions that handle requests and return responses.

Your setup should look like this :

To create a view, you will need to define a function in views.py and map it to a URL pattern. To do this, you will need to create a file called urls.py in your app directory and define a URL pattern. For example:

views.py

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request, 'templates/index.html')

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

This will create a URL pattern that maps the root URL (/) to the index function in views.py.

To display the results of your view in a template, you will need to create a template and render it in your view. Django uses the Django Template Language (DTL) to render templates. You can create a template by creating a templates directory in your app directory and create an index.html file inside it.

<html>
    <body>
        <h1>Hello, Django!</h1>
    </body>
</html>

In your project urls.py file, You also need to include your app's urls

from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp', include("myapp.urls"))
]

Now let's register the app and also define our templates path in settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', 
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Conclusion

Django is a powerful and feature-rich web framework that is well-suited for building a wide range of applications.

If you're just starting out with Django, it's important to take the time to learn the basics and get familiar with the framework before diving into more advanced concepts.

This is just a basic overview of how Django works. There is a lot more to learn, such as working with models, databases, forms, static files, and authentication, but these concepts should give you a good foundation to start building your own Django.

To learn more about Django check this tutorial by Mozilla.

Also check this youtube tutorial: Django with Mosh.

Check out my Twitter page, I write about Python and Django.

Thank you