Introduction to Django framework for beginners
Tags: webdev, django, backenddeveloper, beginners
Published: 2023-03-24 10:42:10

Django is a popular web framework that allows you to build web applications using Python. It is free, open source and follows the model-view-template (MVT) pattern. Django provides many features such as object-relational mapping (ORM), URL routing, template engine, forms, authentication, administration interface and more.

In this article, we will learn how to create a simple web application using Django. We will use the following steps:

Install Django and create a virtual environment.
Create a project and an app.
Define models and migrate the database.
Create views and templates.
Configure URLs and test the app.
Step 1: Install Django and create a virtual environment.
To use Django, you need to have Python installed on your system. You can check your Python version by running  
```
python -- version
```
in your terminal. You also need to install pip, which is a package manager for Python. You can check your pip version by running pip --version in your terminal.

To install Django, you can use pip to run the following command:

```
pip install django

```
This will install the latest version of Django on your system. You can check your Django version by running 

```
django-admin --version
```
in your terminal.

It is recommended to use a virtual environment when working with Django projects. A virtual environment is a way of isolating your project dependencies from other Python packages on your system. This helps to avoid conflicts and keep your project organized.

To create a virtual environment, you can use the `venv` module that comes with Python 
3. You can run the following command in your terminal:

```
python -m venv env

```
This will create a folder called env in your current directory, which will contain the files and folders for your virtual environment.

To activate your virtual environment, you need to run the following command:

```
source env/bin/activate

```
This will change your prompt to indicate that you are in the virtual environment. To deactivate it, you can run `deactivate`.

Step 2: Create a project and an app
A Django project is a collection of settings, files and applications that work together to create a web site. A Django app is a component of a project that provides some functionality, such as models, views, templates etc.

To create a new project, you can use the `django-admin `command with the `startproject` option. You can run the following command in your terminal:

```
django-admin startproject mysite

```
This will create a folder called `mysite`
 in your current directory, which will contain the files and folders for your project.

To create an app within your project, you can use the `manage.py `script with the `startapp `option. You can run the following command in your terminal:

```
python manage.py startapp myapp

```
This will create a folder called `myapp` inside your project folder, which will contain the files and folders for your app.

Step 3: Define models and migrate the database
A model is a class that defines the structure and behavior of an object that represents some data in your application. Django uses models to interact with the database and perform CRUD (create, read, update and delete) operations.

To define models for your app, you need to edit the models.py file inside your app folder. For example, let’s say we want to create a model for a blog post that has a title, content and date fields. We can write something like this:

```
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

```
Here we are importing the `models` module from Django and creating a subclass of `models.Model
`We are defining three fields for our model: title (a character field), content (a text field) and date (a date-time field). We are also overriding the `__str__ `method to return the title of the post as its string representation.

To apply our model changes to the database, we need to perform two steps: make migrations and migrate.

Making migrations means creating files that describe how to modify the database schema according to our model changes. To make migrations for our app, we can run the following command in our terminal:

```
python manage.py makemigrations myapp

```

**Step 4**: Create views and templates
A view is a function or a class that handles a request and returns a response.
A view can perform some logic, interact with models, and render a template. A template is a file that contains HTML code with some special syntax for variables, tags, and filters.
A template can display dynamic data from the context, which is a dictionary of values passed by the view.

To create views for our app, we need to edit the views.py file inside our app folder. For example, let’s say we want to create a view for the index page that displays the latest five posts. We can write something like this:

```
from django.shortcuts import render
from .models import Post

def index(request):
    # get the latest 5 posts
    posts = Post.objects.order_by('-date')[:5]
    # pass them to the context
    context = {'posts': posts}
    # render the index.html template with the context
    return render(request, 'myapp/index.html', context)

```

Here we are importing the render function from Django shortcuts and the Post model from our app models. We are defining a function called index that takes a request object as an argument. We are using the 

`Post.objects.order_by('-date')[:5] `

query to get the latest five posts from the database. We are passing them to a dictionary called context with the key posts. We are using the render function to render a template called `index.html `with the context and return it as a response.

To create templates for our app, we need to create a folder called templates inside our app folder. Inside this folder, we need to create another folder with the same name as our app `(myapp)`. This is to avoid name conflicts with other apps that may have templates with the same name. Inside this folder, we can create our template files with .html extension. For example, let’s create a template for our index page called `index.html`. We can write something like this:



```
<!DOCTYPE html>
<html>
<head>
    <title>My Blog</title>
</head>
<body>
    <h1>My Blog</h1>
    <ul>
        { % for post in posts % }
        <li><a href="{ { post.id }}">{ { 
         post.title }}</a></li>
        { % endfor % }
    </ul>
</body>
</html>

```
Here we are using HTML tags to create a basic web page with a title and a list of links. We are using Django template syntax to loop over the posts in the context and display their title and id as links. 
We are using `{ { and }} `to output variables and `{ % and % } `to execute tags.

Step 5: Configure URLs and test the app
A URL is an address that identifies a web resource on the internet. Django uses URL patterns to map URLs to views. A URL pattern is a string that contains some placeholders that match parts of a URL.

To configure URLs for our project, we need to edit two files: 

`mysite/urls.py`
 and `myapp/urls.py`. The first file is the main URL configuration for our project, where we can include other URL configurations from our apps. The second file is the URL configuration for our app, where we can define specific URL patterns for our views.

To include our app URLs in our project URLs, we need to edit `mysite/urls.py` and add an import statement and a path function like this:

```
from django.contrib import admin
from django.urls import include, path

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

```
Here we are importing the include function from Django `urls `and adding a path function that maps any URL starting with `myapp/ `to our app URLs.

To define our app URLs, we need to edit myapp/urls.py and add some import statements and path functions like this:

```

from django.urls import path
from . import views

urlpatterns = [
    # ex: /myapp/
    path('', views.index, name='index'),
    # ex: /myapp/1/
    path('<int:post_id>/', views.detail, name='detail'),
]

```
Here we are importing the path function from Django urls and our views from our app views. 

Step 6: Test and deploy the app
Testing is an important part of developing any web application. Testing helps you to ensure that your code works as expected, that it meets the requirements, and that it does not introduce any bugs or errors. Django provides a built-in testing framework that allows you to write and run tests for your app.

To write tests for your app, you need to create a file called tests.py inside your app folder. In this file, you can import the `TestCase` class from Django test and create subclasses that define test methods. Each test method should use the assert methods to check some conditions. For example, let’s write a simple test for our `index view`:

```
from django.test import TestCase
from django.urls import reverse
from .models import Post

class IndexViewTests(TestCase):
    def test_no_posts(self):
        # if no posts exist, display a message
        response = self.client.get(reverse('index'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No posts are available.")
        self.assertQuerysetEqual(response.context['posts'], [])

    def test_one_post(self):
        # if one post exists, display it
        Post.objects.create(title="Test post", content="Test content")
        response = self.client.get(reverse('index'))
        self.assertEqual(response.status_code, 200)
        self.assertQuerysetEqual(
            response.context['posts'],
            ['<Post: Test post>']
        )
```
Here we are importing the `TestCase` class from Django test, the reverse function from Django `urls`, and our Post model from our app models. We are creating a subclass called `IndexViewTests` that inherits from `TestCase`. We are defining two test methods: `test_no_posts` and `test_one_post`.
 The first method tests the case when there are no posts in the database. It uses the `client` attribute of the test case to make a `GET` request to the index view using the reverse function. It then checks that the response status code is 200 (OK), that the response contains the message “No posts are available.”, and that the context variable posts is an empty list. The second method tests the case when there is one post in the database. It uses the `Post.objects.create` method to create a post object with some title and content. It then makes a `GET` request to the index view and checks that the context variable posts contains one post object with the same title as created.

To run tests for your app, you can use the `manage.py` script with the `test `option. You can run the following command in your terminal:

```
python manage.py test myapp
```
This will run all the tests in your app and display the results.

Deploying is the process of making your web application accessible to users over the internet. Deploying involves choosing a hosting service, configuring your web server, setting up your database, installing your dependencies, uploading your code, and running your app.

There are many options for deploying your Django app, depending on your architecture or your particular business needs. Some of them are:

 

- Using a cloud platform as a service (PaaS) such as Heroku, Google App Engine, AWS Elastic Beanstalk etc.

- Using a cloud infrastructure as a service (IaaS) such as AWS EC2, Google Compute Engine etc.

- Using a dedicated or shared hosting service such as PythonAnywhere etc.
- Using your own server or virtual machine.

Each option has its own advantages and disadvantages and may require different steps and tools to deploy your app successfully. For more details on how to deploy Django apps using different options, you can refer to Django’s official documentation on deployment.

As an example of how to deploy a Django app using one option, we will use Railway cloud platform as a service (PaaS). Railway is a platform that allows you to easily deploy web applications using various technologies such as Django without having to worry about setting up servers or databases.

To deploy our app using Railway, we need to follow these steps:

- Sign up for Railway using GitHub account.

- Create a new project on Railway dashboard.

- Add PostgreSQL plugin to our project.

- Connect our GitHub repository with our project.

- Add environment variables for our project settings.
Deploy our project using Railway CLI or GitHub actions.
Step 1: Sign up for Railway using GitHub account
To sign up for Railway, we need to visit https://railway.app/ and click on "Sign up