Django Tutorial: Registering Apps

beginner
11 min

Django Tutorial: Registering Apps

Welcome to the Django Tutorial: Registering Apps lesson! This tutorial is designed for both beginners and intermediate learners, so let's dive right in. 🎯

What is a Django App?

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. πŸ“

Creating Your First Django App

Let's create a simple blog app as an example. To get started, open your terminal and type the following command:

bash
django-admin startapp blog

After running this command, you'll see a new directory called blog in your project. This is your app! πŸ’‘

Registering 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:

python
INSTALLED_APPS = [ # ... 'blog', ]

Now, let's migrate the database to make our changes official:

bash
python manage.py migrate

That's it! You've registered your first Django app. βœ…

Practical Example: Creating a Post Model

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:

python
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. πŸ’‘

Quiz

Quick Quiz
Question 1 of 1

What is a Django App?

Next Steps

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