Building web applications with Django

Django is a high-level web framework that lets developers easily build web applications quickly. It is free and open source, and is widely used by developers all around the world. Django focuses on the reusability and pluggability of components, encouraging developers to write clean and reusable code.

In this tutorial, we will guide you through building a web application using Django, step-by-step. We will first help you get started by setting up the development environment and then walk you through the process of creating a simple web app.

Getting Started

Before we start building our web app, we need to set up our development environment. To get started, follow these steps:

1. Install Python

Django is a Python framework. So, the first step is to install Python. You can download the latest version of Python from the official website: https://www.python.org/downloads/

2. Install Django

Once you have installed Python, you can install Django using pip, the Python package manager. Open your terminal (command prompt or PowerShell for Windows) and run the following command:

pip install Django

This will install the latest version of Django on your system.

3. Create a new Django project

Now that we have installed Django, let’s create a new Django project. Open your terminal and run the following command:

django-admin startproject myproject

Replace myproject with the name of your project. This will create a new Django project in a directory with the same name.

4. Run the development server

Let’s start the development server and see if everything is working correctly. Navigate to the project directory and run the following command:

python manage.py runserver

This will start the development server on port 8000 by default. You should see a message in your terminal that says “Starting development server at http://127.0.0.1:8000/”. Open your web browser and go to http://127.0.0.1:8000/. You should see a “Welcome to Django” page.

Congratulations! You have set up your development environment and created a new Django project.

Creating a Simple Web App

Now that we have set up our development environment and created a new Django project let’s create a simple web app. Our web app will be a simple blog where users can create new posts, view posts, and leave comments.

1. Create a new Django app

In Django, a project is divided into multiple apps. An app is a standalone module that does a specific job. We will create a new app for our blog. Navigate to the project directory and run the following command:

python manage.py startapp blog

This will create a new Django app named blog.

2. Configure the database

Django comes with support for various databases, including SQLite, MySQL, and PostgreSQL. In this tutorial, we will use SQLite. Open the settings.py file in the project directory and find the DATABASES setting. Replace it with the following:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

This will configure Django to use SQLite as the default database.

3. Create the blog models

In Django, models represent the data in our application. We will create models for blog posts and comments. Open the models.py file in the blog app directory and add the following code:

from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)

This defines two models, Post and Comment. The Post model contains a title, author, and body. The Comment model contains a post, author, body, and created_on timestamp.

4. Create the blog views

In Django, views handle the HTTP requests and responses. We will create views to display the blog posts and comments, as well as a form to create new posts and comments. Open the views.py file in the blog app directory and add the following code:

from django.shortcuts import render, get_object_or_404
from .models import Post, Comment
from .forms import CommentForm

def post_list(request):
    posts = Post.objects.all()
    return render(request, 'blog/post_list.html', {'posts': posts})

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    comments = post.comments.all()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
    else:
        form = CommentForm()
    return render(request, 'blog/post_detail.html', {'post': post, 'comments': comments, 'form': form})

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

This defines three views, post_list, post_detail, and post_new. post_list displays a list of all posts, post_detail displays a single post and associated comments, and post_new displays a form to create a new post.

5. Create the blog forms

In Django, forms handle user input. We will create a form to allow users to create new comments. Open the forms.py file in the blog app directory and add the following code:

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ('body',)

This defines a form for creating a new comment. The form contains a single field for the body of the comment.

6. Create the blog templates

In Django, templates handle the display of data in HTML. We will create templates to display the blog posts and comments, as well as forms to create new posts and comments. First, create a new directory named templates in the blog app directory. Then, create the following HTML files:

base.html:

{% load static %}
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>

<div class="header">
    <h1><a href="{% url 'post_list' %}">My Blog</a></h1>
</div>

<div class="content">
    {% block content %}{% endblock %}
</div>

<div class="footer">
    ยฉ My Blog 2021
</div>

</body>
</html>

post_list.html:

{% extends 'blog/base.html' %}

{% block content %}

{% for post in posts %}
    <div class="post">
        <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2>
        <p class="meta">Posted by {{ post.author }} on {{ post.published_date }}</p>
        <p>{{ post.body }}</p>
    </div>
{% endfor %}

{% endblock %}

post_detail.html:

{% extends 'blog/base.html' %}

{% block content %}

<div class="post">
    <h2>{{ post.title }}</h2>
    <p class="meta">Posted by {{ post.author }} on {{ post.published_date }}</p>
    <p>{{ post.body }}</p>
</div>

{% for comment in comments %}
    <div class="comment">
        <p class="meta">Posted by {{ comment.author }} on {{ comment.created_on }}</p>
        <p>{{ comment.body }}</p>
    </div>
{% empty %}
    <p>No comments yet.</p>
{% endfor %}

<h3>Leave a comment</h3>

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

{% endblock %}

post_edit.html:

{% extends 'blog/base.html' %}

{% block content %}

<h1>New Post</h1>

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Save</button>
</form>

{% endblock %}

7. Create the blog URLs

In Django, URLs map the HTTP requests to the appropriate views. We will create URL patterns for our blog views. Open the urls.py file in the blog app directory and add the following code:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('post/<int_pk>/', views.post_detail, name='post_detail'),
    path('post/new/', views.post_new, name='post_new'),
]

This defines three URL patterns, one for each view.

8. Include the blog URLs in the project URLs

Now that we have created the URLs for our blog app, we need to include them in the project URLs. Open the urls.py file in the project directory and add the following code:

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

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

This includes the URLs for the blog app under the root URL.

9. Migrate the database

Finally, we need to create the database tables. Run the following command in the terminal:

python manage.py migrate

This will automatically create the necessary database tables for our app.

10. Run the development server

Let’s start the development server and see our app in action. Navigate to the project directory and run the following command:

python manage.py runserver

Open your web browser and go to http://127.0.0.1:8000/. You should see a list of blog posts. Click on a post to view it in detail and leave a comment.

Congratulations! You have created a simple web app using Django.

Conclusion

In this tutorial, we have shown you how to build a simple web app using Django. We covered the basics of Django including models, views, templates, URLs, and more. With this knowledge, you can now go on to build more complex web apps using Django. Happy coding!

Related Post