Creating Your First Django Project and App
2025-01-04Introduction
Welcome to your first step in building web applications with Django! In this guide, we'll walk you through creating your first Django project and application. By the end of this tutorial, you'll have a running Django project and a simple app ready for further development.
Understanding Django Projects and Apps
In Django, a project refers to the entire web application, including its configuration and settings. Within a project, you can have multiple apps, each responsible for a specific functionality. This modular approach promotes reusability and better organization of your code.
For example, you might have a project named myblog
with apps like posts
for blog posts and users
for user management.
Prerequisites
Before we begin, ensure you have the following:
- Django installed in your development environment.
- A text editor or IDE of your choice (e.g., VS Code, PyCharm).
- Basic understanding of Python programming.
Step 1: Creating a New Django Project
Let's start by creating a new Django project. Open your terminal or command prompt and navigate to the directory where you want to create your project.
django-admin startproject myproject
This command creates a new directory named myproject
with the following structure:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
Explanation of Files:
manage.py
: A command-line utility that lets you interact with your project.settings.py
: Contains project settings and configurations.urls.py
: Defines URL patterns for your project.wsgi.py
: An entry-point for WSGI-compatible web servers to serve your project.
Step 2: Running the Development Server
Navigate into your project directory and start the development server to ensure everything is set up correctly.
cd myproject
python manage.py runserver
After running the above commands, you should see output similar to:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
January 10, 2025 - 10:00:00
Django version 4.2, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Open your web browser and navigate to http://127.0.0.1:8000/. You should see the Django welcome page confirming that your project is up and running.
Step 3: Creating Your First Django App
With the project set up, it's time to create an app. Apps in Django are modules that encapsulate specific functionalities. For this tutorial, we'll create a simple blog
app.
python manage.py startapp blog
This command creates a new directory named blog
with the following structure:
blog/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
Explanation of Files:
models.py
: Defines the data models for the app.views.py
: Contains functions that handle requests and return responses.admin.py
: Registers models to the Django admin site.apps.py
: Configuration for the app.migrations/
: Stores database migrations.
Step 4: Registering the App with the Project
To let Django know about the new app, add it to the INSTALLED_APPS
list in settings.py
.
# myproject/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # Register the blog app
]
Adding the app to INSTALLED_APPS
enables Django to recognize and include it in various operations like migrations and the admin interface.
Step 5: Creating a Simple Model
Let's define a simple model for blog posts in blog/models.py
.
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Explanation:
title
: A short string field to store the post's title.content
: A text field for the main content of the post.published_date
: Automatically records the date and time when a post is created.__str__
: Returns the title of the post when the object is printed.
Step 6: Making and Applying Migrations
After defining your models, you need to create and apply migrations to update the database schema.
python manage.py makemigrations
python manage.py migrate
The makemigrations
command creates migration files based on the changes detected in your models, and migrate
applies those changes to the database.
Step 7: Registering the Model with the Admin Site
To manage your blog posts through Django's admin interface, register the Post
model in blog/admin.py
.
from django.contrib import admin
from .models import Post
admin.site.register(Post)
This registration allows you to add, edit, and delete blog posts via the admin panel.
Step 8: Creating a Superuser
A superuser has full access to the admin interface. Create one using the following command:
python manage.py createsuperuser
You'll be prompted to enter a username, email address, and password. Follow the prompts to complete the superuser creation.
Step 9: Accessing the Admin Interface
Start the development server if it's not already running:
python manage.py runserver
Navigate to http://127.0.0.1:8000/admin/ in your web browser. Log in using the superuser credentials you just created. You should see the Posts
section where you can add new blog posts.
Step 10: Creating Views and Templates
Now that your model is set up and registered with the admin, let's create views and templates to display the blog posts to users.
1. Defining a View
In blog/views.py
, create a view to display all blog posts:
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all().order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
This view retrieves all Post
objects from the database, orders them by the published date in descending order, and passes them to the template.
2. Creating a Template
Create a directory named templates/blog
inside the blog
app. Then, create a file named post_list.html
with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog Posts</title>
</head>
<body>
<h1>Blog Posts</h1>
{% for post in posts %}
<article>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<small>Published on {{ post.published_date }}</small>
</article>
{% empty %}
<p>No posts available.</p>
{% endfor %}
</body>
</html>
This template loops through the posts
context variable and displays each post's title, content, and published date.
3. Configuring URLs
Define a URL pattern for the post list view. Create a urls.py
file inside the blog
app with the following content:
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
]
Next, include the blog
app's URLs in the project's main urls.py
file:
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
By including blog.urls
, Django knows to look for URL patterns defined in the blog
app.
4. Viewing the Blog Posts
Start the development server if it's not running:
python manage.py runserver
Navigate to http://127.0.0.1:8000/ in your browser. You should see a list of blog posts that you've added via the admin interface.
Conclusion
Congratulations! You've successfully created your first Django project and app. You've learned how to set up the project structure, create models, register them with the admin interface, and build views and templates to display data to users.
In the next tutorial, we'll dive deeper into Django's powerful features, including creating forms, handling user input, and customizing the admin interface. Stay tuned and happy coding!