Creating a Django App - potatoscript/django GitHub Wiki
Before you start, make sure you are in the directory where your Django project is located. If your project is called mysite
, navigate to the mysite
folder:
cd mysite
To create an app, you use the startapp
command followed by the name of your app. In our case, letβs call it "blog".
python manage.py startapp blog
This will create a new folder called blog
in your project directory with the following structure:
blog/
βββ __init__.py # Marks this directory as a Python package
βββ admin.py # Configuration for the Django admin interface
βββ apps.py # Configuration for the app itself
βββ migrations/ # Database migrations (handles changes to your models)
βββ models.py # Where we define our data models (e.g., blog posts)
βββ tests.py # Where we write tests for the app
βββ views.py # Where we define how our app responds to web requests
βββ urls.py # Where we define the URLs for our app
Now that we've created the app, we need to register it with the main project so Django knows to include it. To do that, we need to add our app to the INSTALLED_APPS
list in the settings.py
file.
- Open
mysite/settings.py
- Find the
INSTALLED_APPS
list and add'blog'
to it:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # Add the 'blog' app here
]
Now Django will know that the blog app exists and can start working with it.
In Django, models are where you define the structure of your data, like how blog posts will be stored in the database. Letβs create a model to represent a Blog Post.
- Open
blog/models.py
and add the following code:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200) # Title of the blog post
content = models.TextField() # Content of the blog post
created_at = models.DateTimeField(auto_now_add=True) # Automatically set the creation time
updated_at = models.DateTimeField(auto_now=True) # Automatically set the update time
def __str__(self):
return self.title # This makes the Post object print as its title
- CharField: A field for short text, used for the title of the blog post.
- TextField: A field for long text, used for the content of the blog post.
-
DateTimeField: A field for dates and times, used for
created_at
andupdated_at
.
Now that we've defined our model, we need to create a database table to store our blog posts. We do this by running migrations.
- First, create a migration file that tells Django to create the database table:
python manage.py makemigrations blog
- Then, apply the migration to create the actual table in the database:
python manage.py migrate
This will set up the database table for our Post
model.
Django comes with a built-in admin interface where you can easily add, edit, and delete objects in your database.
To use the admin, we need to do two things:
-
Register the model with the admin in
blog/admin.py
. - Create a superuser so we can log in to the admin panel.
Open blog/admin.py
and add the following code to register the Post
model:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Run the following command to create a superuser account. This account will allow you to log into the Django admin interface.
python manage.py createsuperuser
It will prompt you to enter a username, email, and password for the superuser.
Now that we have everything set up, let's start the Django development server to see the changes.
python manage.py runserver
Once the server is running, open a web browser and go to:
http://127.0.0.1:8000/admin/
Log in with the superuser credentials you just created. You should see the Post model in the admin panel.
- In the Django admin, click on Posts and then Add Post.
- Fill in the title and content for a new blog post, and click Save.
You can add as many posts as you want!
We need to display the blog posts on the front-end of the website. To do this, we'll create a view and a URL to display the posts.
Open blog/views.py
and add a view that retrieves all the blog posts and passes them to a template.
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all() # Get all posts from the database
return render(request, 'blog/post_list.html', {'posts': posts}) # Render the template with the posts
Next, we need to link the view to a URL. Open blog/urls.py
and add this code to define the URL:
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
]
Make sure your mysite/urls.py
file includes the blog
appβs URL configuration:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')), # Include the blog app's URLs
]
We need to create a template to display the blog posts. Django will look for the template inside the blog/templates/blog
directory.
Create a folder templates/blog/
inside the blog
directory, and inside that folder, create a file called 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>
{% endfor %}
</ul>
</body>
</html>
Finally, open your web browser and go to:
http://127.0.0.1:8000/
You should see a list of all the blog posts you added through the admin panel!