Introduction
Django is an open-source web framework that allows developers to build dynamic and scalable web applications quickly and efficiently. With its “batteries-included” philosophy, Django provides a robust set of tools and libraries to streamline many aspects of web development.
This guide will walk you through the process of building your first web application using Django. By the end of this tutorial, you will have a solid understanding of some core Django concepts and how to deploy your application.
Prerequisites
Before we start, make sure you have the following prerequisites:
- Basic understanding of Python programming
- Python installed on your computer (version 3.6 or later)
- Understanding of HTML/CSS basics
- A code editor (like VSCode, PyCharm, etc.)
Step 1: Setting Up Your Development Environment
The first step is to set up your development environment. For this, we will use venv
, which is Python’s built-in module for creating isolated environments.
Creating a Virtual Environment
python -m venv myprojectenv
Activate your virtual environment:
On Windows:
myprojectenv\Scripts\activate
On macOS/Linux:
source myprojectenv/bin/activate
Installing Django
Now that your virtual environment is activated, install Django using pip:
pip install django
Step 2: Creating a New Django Project
With Django installed, it’s time to create your first project.
django-admin startproject myproject
This command creates a new directory called myproject
with the following structure:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
Step 3: Running the Development Server
Change into the project directory and run the development server:
cd myproject
python manage.py runserver
Open your browser and go to http://127.0.0.1:8000
to see your new Django project in action!
Step 4: Creating a Django App
Django projects can contain multiple applications. Let’s create a new app called blog
:
python manage.py startapp blog
This will create a new directory structure like this:
blog/
migrations/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
Step 5: Defining Models
Now, let’s define a simple model for our blog posts. Open models.py
in the blog
directory and add the following code:
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
Step 6: Registering the Model with Admin
To manage your blog posts via the Django admin interface, you will need to register your model. Open admin.py
in the blog
directory and add:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Step 7: Configuring the App
Next, you need to let your project know about the new app. Open settings.py
in the myproject
directory and add 'blog',
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
...
'blog',
]
Step 8: Running Migrations
We need to create the database tables for our new model. Run the following commands:
python manage.py makemigrations
python manage.py migrate
Step 9: Creating a Superuser
To access the Django admin site, you need to create a superuser:
python manage.py createsuperuser
Follow the prompts to set a username, email, and password.
Step 10: Running the Server Again
Now that you’ve created your superuser, run the development server again:
python manage.py runserver
Visit http://127.0.0.1:8000/admin
and log in with the credentials you just created. You should see your Post
model available for you to manage!
Step 11: Creating Views and Templates
Next, let’s create views and templates to display our blog posts on the front end.
Creating a View
Open views.py
in the blog
directory and add the following code:
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
Creating a Template
Create a directory called templates
inside the blog
directory, and then create another directory named blog
inside that. Finally, create a file called post_list.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog Posts</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li><a href="#">{{ post.title }}</a> - {{ post.created_at }}</li>
{% endfor %}
</ul>
</body>
</html>
Step 12: Updating URLs
Next, map your view to a URL. Open urls.py
in the myproject
directory and set up URL routing:
from django.contrib import admin
from django.urls import path
from blog.views import post_list
urlpatterns = [
path('admin/', admin.site.urls),
path('', post_list, name='post_list'),
]
Step 13: Test Your Web App
Now that everything is set up, visit http://127.0.0.1:8000
to see the list of blog posts!
Step 14: Deploying Your Application
Finally, once you are happy with your application, you may want to deploy it. There are several options for deploying Django applications:
- Using Platform-as-a-Service (PaaS) providers like Heroku
- Using a cloud service like AWS or Google Cloud
- Using shared hosting that supports Django
For simplicity, we recommend starting with Heroku:
- Install the Heroku CLI.
- Create a new Heroku app using
heroku create
. - Check your requirements with
pip freeze > requirements.txt
. - Run migrations on Heroku by using
heroku run python manage.py migrate
. - Push your code to Heroku using
git push heroku master
.
Conclusion
Congratulations! You’ve built your first web application using Django. You learned how to set up your environment, create models, views, templates, and even deploy your app. Django’s modular nature and built-in features make it a powerful choice for developing web applications.
As you continue to explore Django, consider diving deeper into features such as user authentication, REST APIs, and additional third-party libraries that can enhance your projects. With practice, you can leverage Django to create complex and dynamic web applications that cater to various user needs.
Keep building, keep learning, and enjoy the journey of web development!
0 Comments