Welcome to the Django Tutorial: Registering Apps lesson! This tutorial is designed for both beginners and intermediate learners, so let's dive right in. π―
In Django, an app is a reusable, self-contained piece of code that performs a specific task. It's like a mini-application within your larger project. π
Let's create a simple blog app as an example. To get started, open your terminal and type the following command:
django-admin startapp blogAfter running this command, you'll see a new directory called blog in your project. This is your app! π‘
To use our new blog app, we need to register it in Django's settings. Open the settings.py file in your project directory and find the INSTALLED_APPS list. Add 'blog' to this list, like so:
INSTALLED_APPS = [
# ...
'blog',
]Now, let's migrate the database to make our changes official:
python manage.py migrateThat's it! You've registered your first Django app. β
To make our blog app functional, we'll create a Post model. In your blog directory, open the models.py file and add the following code:
from django.db import models
from django.utils.text import slugify
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)Here, we've created a Post model with fields for title, slug, content, created_at, and updated_at. The save method automatically generates a slug if one isn't provided. π‘
What is a Django App?
In the next lesson, we'll learn how to create the admin interface for our blog app and manage our Post models from there. Stay tuned! π―