Django is a high-level web framework written in Python that encourages rapid development and clean, pragmatic design. It’s a popular choice among developers for building robust web applications due to its simplicity, scalability, and flexibility. In this tutorial, we will go over the basics of Django and walk you through how to set up a simple web application.
Setting up Django
First, you’ll need to install Django. You can do this using pip, the Python package installer. Open your terminal and run the following command:
pip install Django
Once Django is installed, you can create a new Django project by running:
django-admin startproject myproject
This will create a new directory called myproject
with the following structure:
myproject/
├── manage.py
└── myproject/
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
The manage.py
file is a command-line utility that lets you interact with your Django project. You can use it to run the development server, create migrations, and more.
The settings.py
file contains all the configuration settings for your Django project, such as database settings, static files configuration, and installed apps.
The urls.py
file defines the URL patterns for your project. When a request is made to your server, Django uses the URL patterns in this file to determine which view function should be called.
The wsgi.py
file is used to deploy your Django project on a web server.
Creating a Django app
In addition to the project, you’ll also need to create a Django app. Apps are like modules that you can plug into your Django project to add functionality. To create a new app, run the following command:
python manage.py startapp myapp
This will create a new directory called myapp
with the following structure:
myapp/
├── migrations/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py
The models.py
file is where you define your database models using Django’s Object-Relational Mapping (ORM) system. This allows you to interact with your database using Python classes instead of raw SQL queries.
The views.py
file contains your view functions, which handle requests and return responses. Views are responsible for processing user input, interacting with the database, and rendering templates.
The urls.py
file in your app’s directory defines the URL patterns for that specific app. This allows you to organize your project’s URLs into different files for better readability and maintainability.
Configuring the database
By default, Django uses SQLite as the database for development. However, you can easily change this to use another database like MySQL, PostgreSQL, or Oracle. To configure the database settings, open the settings.py
file in your project directory and update the DATABASES
variable with the appropriate settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
Replace the ENGINE
and NAME
values with the appropriate database settings for your development environment. You’ll also need to install the necessary database adapter using pip if you’re using a different database.
Creating models
Before you can interact with your database, you’ll need to define your models. Models are Python classes that represent tables in your database. Each model class corresponds to a table, and each attribute on the class represents a column in the table.
For example, let’s create a simple Post
model with a title
and content
field:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
To create the database table for this model, run the following command:
python manage.py makemigrations
python manage.py migrate
The makemigrations
command generates the database migration file based on your model changes, while the migrate
command applies the migration to your database.
Creating views
Once you have your models set up, you can create views to interact with the database. Views are Python functions that receive HTTP requests and return HTTP responses. Let’s create a simple view that displays a list of posts:
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'myapp/post_list.html', {'posts': posts})
In this view, we’re fetching all the Post
objects from the database and passing them to a template called post_list.html
along with the request
object.
Creating templates
Templates are HTML files that define the structure of your web pages. Django uses a template engine called Django Template Language (DTL) to render templates with dynamic content. Create a new directory called templates
inside your app directory and create a file called post_list.html
with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Post List</title>
</head>
<body>
<h1>Post List</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% endfor %}
</ul>
</body>
</html>
In this template, we’re iterating over each post in the posts
list and displaying the title
attribute for each post.
Configuring URLs
To access your views, you’ll need to map them to URLs. Open the urls.py
file in your app’s directory and add the following URL pattern:
from django.urls import path
from . import views
urlpatterns = [
path('posts/', views.post_list, name='post_list'),
]
This URL pattern maps the post_list
view to the /posts/
URL. You can now access this view by visiting http://localhost:8000/posts/
in your browser.
Running the development server
To test your Django application, run the development server using the following command:
python manage.py runserver
This will start the Django development server on http://localhost:8000/
. You can now visit your app in the browser and see the list of posts displayed on the page.
Conclusion
Congratulations! You’ve successfully set up a simple Django web application that displays a list of posts. Django is a powerful framework that offers a lot of features out of the box, such as user authentication, admin panels, and form handling. As you continue to work with Django, you’ll discover even more ways to build robust and scalable web applications. Happy coding!