1949catering.com

Build a Blog Using Django 5 and Supabase: A Step-by-Step Guide

Written on

Introduction to Building a Django Blog

In this series, we will embark on a journey to develop a blog application using Django. This tutorial is designed for individuals with either a beginner or intermediate understanding of Django. Throughout the process, you will learn how to connect a database, enhance the Django Admin interface, and retrieve data from the database for display in your views.

Setting Up Your Environment

Let's get started by creating a new directory and setting up a virtual environment. If you're unsure about how to create a virtual environment, you can refer to a helpful tutorial. To install the necessary dependencies, run:

pip install Django

pip install "psycopg[binary]"

Creating Your Django Project

Next, create your Django project by executing the following command:

python3 -m django startproject django_app .

Now, add a new application for your blog:

python manage.py startapp blog

Registering the Blog App

We must inform Django about our new blog app. To do this, update the INSTALLED_APPS list in your settings.py file as follows:

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'blog.apps.BlogConfig',

]

Connecting to the Database

For our database, we will utilize Supabase (Postgres). If you prefer a local setup, feel free to choose another option, but for this tutorial, we recommend using Supabase.

  1. Go to Supabase and click on New Project.
  2. Fill in your preferred project name, select a password (which you'll need later), and choose the most suitable region for your location. Note that if you select a region far from your location, you may experience slower response times.

In the Settings -> Database section, you will find your database credentials. These will need to be configured in your Django app.

Updating Database Settings

In your settings.py, modify the DATABASES configuration as shown below, using the credentials you obtained earlier:

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.postgresql',

'HOST': 'aws-0-eu-central-1.pooler.supabase.com',

'NAME': 'postgres',

'USER': 'postgres.qaeqxwyjucocjxfvntat',

'PORT': '5432',

'PASSWORD': 'qa3Zx6e2Rn012pbx',

}

}

Defining Your Models

Here, we define our data structure. The __repr__ method ensures a user-friendly representation in the Django Admin. We also use the Meta class to set default ordering based on the publish date and define indexes for optimized queries.

The Status enum is created by subclassing models.TextChoices, providing options for 'Draft' and 'Published' statuses. Below is the model definition:

from django.db import models

from django.utils import timezone

from django.contrib.auth.models import User

class Post(models.Model):

class Status(models.TextChoices):

DRAFT = 'DF', 'Draft'

PUBLISHED = 'PB', 'Published'

title = models.CharField(max_length=250)

slug = models.SlugField(max_length=250, unique=True)

body = models.TextField()

publish = models.DateTimeField(default=timezone.now)

created = models.DateTimeField(auto_now_add=True)

updated = models.DateTimeField(auto_now=True)

status = models.CharField(max_length=2,

choices=Status.choices,

default=Status.DRAFT)

author = models.ForeignKey(User,

on_delete=models.CASCADE,

related_name='blog_posts')

class Meta:

ordering = ['-publish']

indexes = [

models.Index(fields=['publish']),

]

def __str__(self):

return f"{self.title}"

Creating Migrations

To reflect the model changes in the database, we need to create and apply migrations. Django provides built-in migrations for the user model, which will result in additional tables being created. Use the following commands:

python manage.py makemigrations

python manage.py migrate

Creating a Superuser

Before proceeding, create at least one user account:

python manage.py createsuperuser

You will be prompted for several details. Note that the password will not be visible while typing. Although you can use a simple password like 123456 for testing, remember to choose something more secure for production.

Running the Application

To start the server, run:

python manage.py runserver

Access the Django Admin interface at http://127.0.0.1:8000/admin/ using the credentials you just created.

Registering the Post Model

Currently, the Post model isn't available in the database. To remedy this, we need to register it in admin.py:

from django.contrib import admin

from .models import Post

# Register your models here.

admin.site.register(Post)

After refreshing the admin page, you should now see "Posts" listed in the Django Admin.

Adding Posts

You can now add posts that will later be displayed through views. After clicking SAVE, the newly created post will appear in the Django Admin and will be stored in your database.

Conclusion

In this part of the tutorial, we created a Django project, defined a model, connected it to a database, and successfully added data through the Django Admin interface. In the next part, we will explore how to integrate templates to present the data effectively.

Thank you for reading! If you found this article helpful, consider joining our community by following us. Your feedback is always appreciated, so feel free to share your thoughts!

In Plain English 🚀

Thank you for being part of the In Plain English community! Before you leave, don't forget to clap and follow the author ️👏️️. Stay connected with us on X, LinkedIn, YouTube, Discord, and our Newsletter. Explore more content on Stackademic, CoFeed, Venture, and Cubed. Find additional articles at PlainEnglish.io.

Video Tutorials

Check out the following video tutorials to enhance your learning experience.

This video covers the basics of building a blog with Django. It walks you through the initial setup and essential features.

In this tutorial, learn how to create a blog using Django, Python, and Bootstrap, focusing on integrating these technologies effectively.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Finding Clarity Amidst Mental Noise: Yashi's Journey

Discover how Yashi navigates mental chatter and finds clarity through self-reflection and spiritual insight.

The Impact of COVID-19: A Critical Review of Public Health Policies

Analyzing the shortcomings of public health responses to COVID-19, emphasizing the cost-benefit balance and opportunity costs.

Navigating Blended Family Dynamics: A Gift Controversy

A mother's dilemma over her stepdaughter's actions leads to a heated conflict with her fiancé, raising questions about family dynamics.