Django is one of the most popular web frameworks for Python. Known for its simplicity, scalability, and versatility, Django makes it easy for developers, especially beginners, to create robust web applications quickly. Whether you're creating a simple blog or a full-featured e-commerce site, Django provides all the tools you need to get up and running.
This guide will walk you through everything a beginner needs to know about setting up and building a Django project from scratch.
What Is Django
Django is a high-level web framework for Python that promotes rapid development and clean, pragmatic design. It follows the Model-View-Template (MVT) architectural pattern, similar to the popular Model-View-Controller (MVC) used in many other frameworks. Django is great for building web applications because it includes many built-in features that handle common web development tasks, such as:
- URL routing
- Database management
- User authentication
- Form handling
- Admin interface
Prerequisites For Django
Before you can start building a Django project, there are a few prerequisites you'll need to have in place:
- Python: Django is built on Python, so you'll need Python installed on your machine. Django supports Python 3.8 and above.
-
To check if you have Python installed, open your terminal or command prompt and type:
bashpython --version
-
If you don't have it installed, download and install Python from the official site: python.org.
-
- Pip: Pip is Python’s package manager and comes pre-installed with Python. It will allow you to install Django and other necessary libraries.
-
To check if pip is installed, run:
bashpip --version
-
- Virtual Environment: It’s best practice to use a virtual environment for Python projects. This isolates your project's dependencies from the system Python packages.
-
You can install the
venv
module with the following command if it's not already installed:bashpip install virtualenv
-
Step-By-Step Guide: Starting Your First Django Project
Step 1: Install Django
Once you have Python and pip set up, you're ready to install Django. The best way to install Django is by using pip within a virtual environment.
-
Create a virtual environment
-
Navigate to the directory where you want to create your project and create a new virtual environment:
bashpython -m venv myenv
myenv
is the name of the virtual environment in the example above. You can name it whatever you like.
-
Activate the virtual environment:
-
On Windows:
bashmyenv\Scripts\activate
-
On macOS/Linux:
bashsource myenv/bin/activate
-
-
You’ll know your virtual environment is active when you see
(myenv)
before your terminal prompt.
-
-
Install Django Now that your virtual environment is active, install Django using pip:
bashpip install django
Once the installation is complete, you can verify it by typing:
bashdjango-admin --version
Step 2: Create A New Django Project
Now that Django is installed, you can create your first Django project.
-
Start a new Django project Use Django’s
startproject
command to create a new project. This command generates a directory structure and configuration files for your project.bashdjango-admin startproject myproject
This will create a new directory called
myproject
, which contains the following files:- manage.py: A command-line utility for managing your project (e.g., running the server, migrations).
- myproject/: The project directory, containing:
- init.py: Marks this directory as a Python package.
- settings.py: Contains all configuration settings for your project.
- urls.py: A URL routing file that maps URLs to views.
- wsgi.py: A file used to deploy the project to a WSGI-compatible web server.
- asgi.py: Similar to
wsgi.py
, but used for asynchronous deployment.
-
Run the Development Server: After creating your project, navigate into the project directory:
bashcd myproject
You can now run Django’s built-in development server to test that everything is working correctly:
bashpython manage.py runserver
Open your browser and go to
http://127.0.0.1:8000/
. You should see Django’s default welcome page, confirming that your project is up and running.If you do not see Django’s default welcome page, go through the previous steps and try again.
Step 3: Create Your First Django App
In Django, a project is made up of apps. An app is a self-contained module that handles one specific task in your project. For example, you could have separate apps for user authentication, blog posts, and comments in a blog project.
-
Create a new app: To create an app, run the following command inside your project directory:
bashpython manage.py startapp myapp
This will create a new directory called
myapp
, containing files like:- models.py: Defines the database schema.
- views.py: Handles the logic for processing requests and returning responses.
- urls.py: Maps URLs to views (you'll need to create this manually).
- admin.py: Configures the app for the Django admin panel.
-
Register the app: After creating the app, you need to tell Django about it by adding it to the
INSTALLED_APPS
list insettings.py
.Open
myproject/settings.py
and add'myapp',
to theINSTALLED_APPS
list:pythonINSTALLED_APPS = [ # Default Django apps... 'myapp', ]
Step 4: Create Models And Migrate The Database
Models in Django define the structure of your database tables. Once you've defined your models, Django will automatically create the database tables based on those models.
-
Define a model: In
myapp/models.py
, define a simple model for a blog post:pythonfrom django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() published_at = models.DateTimeField(auto_now_add=True)
In the above example:
Post
is the table name.title
,content
, andpublished_at
are the columns in thePost
table.
-
Run migrations: Django uses a migration system to apply changes to the database. To create and apply migrations:
-
Generate the migration file:
bashpython manage.py makemigrations
-
Apply the migration to the database:
bashpython manage.py migrate
-
Step 5: Create Views And URL Routing
Now that we have a model, let’s create a simple view to display data and link it to a URL.
A view file is used to defining the logic for handling requests and returning responses. Views are responsible for processing the data received from models or forms, and then rendering it to use templates or other types of responses.
-
Create a view: In
myapp/views.py
, define a simple view to display all blog posts:pythonfrom django.shortcuts import render from .models import Post def home(request): posts = Post.objects.all() return render(request, 'home.html', {'posts': posts})
-
Set up URL routing: Create a
urls.py
file in themyapp/
directory and add the following code:pythonfrom django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]
Then, include your app’s URLs in the project’s
urls.py
(located in themyproject/
directory):pythonfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]
Step 6: Create Templates
Django uses the Template system to render HTML content dynamically.
-
Create a template directory: Inside your app folder (
myapp
), create a folder calledtemplates
. Inside this folder, create ahome.html
file:html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Blog Home</title> </head> <body> <h1>Blog Posts</h1> <ul> {% for post in posts %} <li>{{ post.title }} - {{ post.published_at }}</li> {% endfor %} </ul> </body> </html>
-
Run the server: Run the development server again to see your blog home page:
bashpython manage.py runserver
Visit
http://127.0.0.1:8000/
, and you should see the blog posts listed dynamically.
Step 7: Use The Django Admin Panel
Django comes with an admin panel that allows you to manage your app’s data easily.
-
Register the Model: In
myapp/admin.py
, register the Post model:pythonfrom django.contrib import admin from .models import Post admin.site.register(Post)
-
Create a superuser: To access the admin panel, you need to create a superuser account:
bashpython manage.py createsuperuser
Follow the prompts to create a username, email, and password.
-
Access the admin panel: Start the development server and visit
http://127.0.0.1:8000/admin/
. Log in using the superuser credentials, and you can now manage your blog posts directly from the admin interface.
Conclusion
Setting up a Django project for the first time might seem overwhelming, but following these steps will help you understand the basics of building and managing a Django application. From setting up your environment to creating models, views, and templates, Django provides a powerful and flexible framework for developing web applications. Once you’ve mastered these basics, you’ll be able to create more complex features and dive into more advanced aspects of Django.
Key Takeaways:
- Install Django in a virtual environment for better dependency management.
- Use Django’s built-in tools to generate apps, models, and handle URL routing.
- Django’s admin interface is a powerful tool for managing app data.
Now that you have a solid foundation, you can continue exploring Django’s features, such as handling forms, authentication, and deploying your project.