Day 39: Introduction to Django

Basics of Django, Setting Up a Project, and Creating an App

Harshil Chovatiya
6 min readOct 5, 2024

Learn the Fundamentals of Django and Build Your First Web Application

Day 39 :Basics of Django, Setting Up a Project, and Creating an App | Harshil Chovatiya
Day 39 :Basics of Django, Setting Up a Project, and Creating an App | Harshil Chovatiya

Introduction

Welcome to Day 39 of our Python learning journey! Today marks an exciting transition as we dive into Django, a powerful web framework for building robust and scalable web applications. Django, known for its “batteries-included” philosophy, provides a comprehensive set of tools to streamline the development process, making it a popular choice for developers worldwide. In this blog, we’ll cover the basics of Django, walk through setting up a new project, and create a simple application to get you started.

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It aims to make it easier to build web applications quickly by providing reusable components and a straightforward development process. Django follows the Model-Template-View (MTV) architectural pattern, which helps in organizing code and separating concerns effectively.

Key Features of Django

  • Object-Relational Mapping (ORM): Simplifies database interactions by allowing you to define your database schema using Python classes.
  • Automatic Admin Interface: Provides a built-in admin panel to manage application data.
  • Form Handling: Offers robust form handling capabilities, including validation and rendering.
  • URL Routing: Manages URL patterns and maps them to views.
  • Authentication: Includes user authentication and authorization functionalities.

Setting Up a Django Project

Prerequisites

Before diving into Django, ensure you have the following prerequisites:

  • Python: Django is a Python framework, so make sure Python is installed on your system. Django supports Python 3.6 and above.
  • Pip: Python’s package installer, which you will use to install Django.

1. Installing Django

To start using Django, you first need to install it. This can be done using pip:

pip install django

Output:

Collecting django
Downloading Django-3.2.9-py3-none-any.whl (7.9 MB)
|████████████████████████████████| 7.9 MB 2.0 MB/s
Collecting pytz
Downloading pytz-2021.3-py2.py3-none-any.whl (500 kB)
|████████████████████████████████| 500 kB 3.0 MB/s
Collecting sqlparse>=0.2.2
Downloading sqlparse-0.4.2-py3-none-any.whl (42 kB)
|████████████████████████████████| 42 kB 1.2 MB/s
Installing collected packages: pytz, sqlparse, django
Successfully installed django-3.2.9 pytz-2021.3 sqlparse-0.4.2

2. Creating a New Django Project

Once Django is installed, you can create a new project using the django-admin command:

django-admin startproject myproject

This command creates a new directory called myproject with the following structure:

Creating a New Django Project structure | Harshil Chovatiya
Creating a New Django Project structure | Harshil Chovatiya
  • manage.py: A command-line utility that lets you interact with your project.
  • myproject/: The project package directory containing the project’s settings and configuration files.

3. Running the Development Server

Navigate into your project directory and start the development server to verify that everything is set up correctly:

cd myproject
python manage.py runserver

Output:

Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 04, 2023 - 12:00:00
Django version 3.2.9, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

By default, the server will start on http://127.0.0.1:8000/. Open this URL in your web browser, and you should see Django’s default welcome page, indicating that your project is running successfully.

Creating a Django App

In Django, a project is a collection of settings and configurations, while an app is a specific component of your project. For example, in a blog application, the blog section itself is an app within the project. Let’s create a simple app to understand how this works.

1. Creating an App

Use the startapp command to create a new app:

python manage.py startapp myapp

This command will create a new directory called myapp with the following structure:

New Django Project structure | Harshil Chovatiya
New Django Project structure | Harshil Chovatiya
  • models.py: Define your data models here.
  • views.py: Create your views and handle the logic of your application.
  • urls.py: Define URL patterns for the app (you may need to create this file manually).

2. Configuring the App

To integrate the app into your project, you need to add it to the INSTALLED_APPS list in the settings.py file of your project:

# myproject/settings.py
INSTALLED_APPS = [
# Django default apps...
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Your app
'myapp',
]

3. Creating Models

Models define the structure of your data and are represented as Python classes. Let’s create a simple model for a blog post:

# myapp/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title

In this model:

  • title: A character field for the title of the post.
  • content: A text field for the post content.
  • created_at: A datetime field that automatically records the creation time.

4. Migrating the Database

Once you define your models, you need to create and apply migrations to update the database schema:

python manage.py makemigrations

Output:

Migrations for 'myapp':
myapp/migrations/0001_initial.py
- Create model Post
python manage.py migrate

Output:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, myapp, sessions
Running migrations:
Applying myapp.0001_initial... OK

The makemigrations command generates migration files based on changes in your models, and migrate applies these changes to the database.

5. Creating an Admin User

To interact with your models using Django’s admin interface, you need to create a superuser:

python manage.py createsuperuser

Output:

Username (leave blank to use 'yourname'): admin
Email address: admin@example.com
Password:
Password (again):
Superuser created successfully.

6. Registering Models in Admin

To make your model accessible in the admin interface, register it in admin.py:

# myapp/admin.py

from django.contrib import admin
from .models import Post
admin.site.register(Post)

Now, run the server and access the admin interface at http://127.0.0.1:8000/admin/, and log in with your superuser credentials.

7. Creating Views

Views handle the logic and render the responses. Let’s create a basic view to display a list of blog posts:

# myapp/views.py
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'post_list.html', {'posts': posts})

8. Configuring URLs

You need to define URL patterns for your app. Create a urls.py file in the myapp directory and configure it:

# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
]

Then, include these URLs in your project’s main URL configuration:

# myproject/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]

9. Creating Templates

Templates define how your data is presented. Create a templates directory inside your myapp directory, and then create a post_list.html file:

<!-- myapp/templates/post_list.html -->
<!DOCTYPE html>
<html>
<head>
<title>Blog Posts</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<small>Created at: {{ post.created_at }}</small>
</li>
{% empty %}
<li>No posts available.</li>
{% endfor %}
</ul>
</body>
</html>

This template iterates over the posts context variable and displays each post's title, content, and creation date.

10. Running the Application

Now, start the development server:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser. If you have added posts via the admin interface, they will be displayed:

Blog post Output Of simple WebApp in Django | Harshil Chovatiya
Blog post Output Of simple WebApp in Django | Harshil Chovatiya

Conclusion

Today, we introduced you to Django, a powerful web framework for Python, and walked through the process of setting up a new project and creating a basic app. We covered:

  • Setting Up Django: Installing Django, creating a project, and running the development server.
  • Creating an App: Adding a new app to your project, configuring it, and defining models, views, and URLs.
  • Templates: Rendering data with HTML templates.
  • Admin Interface: Using Django’s built-in admin interface to manage your models.

With this foundational knowledge, you can start building more complex web applications and explore Django’s advanced features, such as user authentication, form handling, and deployment.

Stay tuned for tomorrow, where we will delve deeper into Django’s capabilities and build more advanced features for our project.

Happy coding!

by Harshil Chovatiya

--

--

Harshil Chovatiya
Harshil Chovatiya

Written by Harshil Chovatiya

Passionate Python and Flutter developer creating dynamic apps and tools. Focused on seamless user experiences and backend efficiency.

No responses yet