Creating a Django App - potatoscript/django GitHub Wiki

Step 1: Open Your Terminal or Command Prompt

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

Step 2: Create a New Django App

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

Step 3: Register the App in Your Project

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.


Step 4: Create Your First Model (Defining Blog Posts)

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

What did we create?

  • 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 and updated_at.

Step 5: Run Migrations to Create the Database Table

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.


Step 6: Add Some Blog Posts Using Django Admin

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:

  1. Register the model with the admin in blog/admin.py.
  2. Create a superuser so we can log in to the admin panel.

1. Register the Model in blog/admin.py

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)

2. Create a Superuser

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.


Step 7: Run the Development Server

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.


Step 8: Create Some Blog Posts

  • 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!


Step 9: Create a View to Display the Blog Posts

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.

1. Create the View

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

2. Create the URL

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'),
]

3. Update the Project’s URL Configuration

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
]

Step 10: Create the Template to Display Posts

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.

Example 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>

Step 11: View the Blog Posts

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!


⚠️ **GitHub.com Fallback** ⚠️