Build a Blog From Scratch With Django – Real Python
Build a Blog From Scratch With Django by Jasmine Finer Updated Oct 16, 2023 Reading time estimate 36m intermediate django projects web-dev Table of Contents Remove ads There are plenty of blogging platforms out there that you can use out of the box. However, building your own blog from scratch with Django is a great way to keep control over your content. Even if you’re just getting started with Django, its user-friendly features will allow you to focus on designing and posting your content.
In this tutorial, you’ll learn how to: Set up a new Django project Create and edit blog posts Display posts to the user Assign categories to posts Allow users to comment on posts Along the way, you’ll leverage the Django admin site and explore how to work with forms in Django. This is an ideal project to dip your toes into the world of Django, but you should have a solid foundation in Python basics . At the end of this tutorial, you’ll be able to share your knowledge through a working blog that you’ve built from scratch.
If you’re curious about how the final source code looks, then you can click the link below: Get Your Code: Click here to download your free source code to build a blog from scratch with Django. Set Up the Development Environment Whenever you’re starting a new web development project, it’s a good idea to first set up your development environment. Create a new directory for your project to live in, and cd into it: Language: Shell $ mkdir django-blog $ cd django-blog Once you’re inside the django-blog/ directory, it’s a good idea to create a virtual environment to manage dependencies.
Select your operating system below and use your platform-specific command to set up a virtual environment: Windows Linux + macOS Language: Windows PowerShell PS> python -m venv venv Language: Shell $ python -m venv venv This command will create a venv/ folder in your working directory. Inside this directory, you’ll find several files, including a copy of the Python standard library. Later, when you install new dependencies, this directory will store them too.
Next, you need to activate the virtual environment by running the following command: Windows Linux + macOS Language: Windows PowerShell PS> .\ venv \ Scripts \ activate (venv) PS> Language: Shell $ source venv/bin/activate (venv) $ With the above commands, you create and activate a virtual environment named venv by using Python’s built-in venv module. The parenthetical (venv) in front of the prompt indicates that you’ve successfully activated the virtual environment.
Now that you’ve created and activated a virtual environment, it’s time to install Django. You can do this using pip : Language: Shell (venv) $ python -m pip install Django Once you’ve set up the virtual environment and installed Django, you can now dive into creating your Django project. Remove ads Start Your Django Project A Django web application is made up of a project and apps . A Django project holds some configurations that apply to the web application as a whole, such as project settings, URLs, shared templates, and static files.
Each Django app can have its own URLs as well as its own HTML templates and static files, such as JavaScript and CSS . To create your Django project, make sure you’re in the django-blog/ directory with your virtual environment activated. Then, run the following command to create the personal_blog project: Language: Shell (venv) $ django-admin startproject personal_blog . Don’t forget to add the dot ( . ) at the end of the command above.
The dot prevents Django from creating a nested project directory for your portfolio project. Otherwise you’d end up with a personal_blog/ folder that contains a personal_blog/ subdirectory. By running the startproject command as shown above, you’ve told Django to create one personal_blog/ folder in the django-blog/ directory. Your directory structure should look something like this: django-blog/ │ ├── personal_blog/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── venv/ │ └── manage.py Once your file structure is set up, you can now start the Django development server and check that your setup was successful.
In the console, run the following command: Language: Shell (venv) $ python manage.py runserver Then, in your browser, go to http://localhost:8000 , and you should see the following: Congratulations, you’ve created a Django site! The next step is to create the blog app so that you can add views and functionality to your site. Add the Blog App That You’ll Build From Scratch Before you get into building out the functionality of this part of your site, create a new Django app named blog : Language: Shell (venv) $ python manage.py startapp blog Once you’ve created the app, you need to install it in your project.
In django-blog/personal_blog/settings.py , add the following line of code under INSTALLED_APPS : Language: Python # personal_blog/settings.py # ... INSTALLED_APPS = [ "blog.apps.BlogConfig" , "django.contrib.admin" , "django.contrib.auth" , "django.contrib.contenttypes" , "django.contrib.sessions" , "django.contrib.messages" , "django.contrib.staticfiles" , ] # ... To include an app in a Django project, you need to add a reference to its configuration class at the beginning of the INSTALLED_APPS list in settings.py .
By adding blog.apps.BlogConfig , you let Django know that the blog app you just created exists. You’re one big step closer to successfully building a blog from scratch! The next step is to create the models to define the logic on how to store your blog content in a database. Define Models to Represent Database Tables If you want to store data to display on a website, then you’ll need a database. Typically, if you want to create a database with tables and columns within those tables, then you’ll need to use SQL to manage the database.
But when you use Django, you don’t need to learn a new language because it has a built-in object relational mapper (ORM) . An ORM is a program that allows you to create classes that correspond to database tables. Class attributes correspond to columns, and instances of the classes correspond to rows in the database. So, instead of learning a whole new language to create your database and its tables, you can just write some Python classes .
When you’re using an ORM, models are the classes you build that represent database tables. In Django, these live in the models.py module of each Django app. You’re going to need three separate models for the blog: Post Category Comment Start with the code for the Category and Post models in the models.py file of your blog app: Language: Python 1 # blog/models.py 2 3 from django.db import models 4 5 class Category ( models .
Model ): 6 name = models . CharField ( max_length = 30 ) 7 8 class Post ( models . Model ): 9 title = models . CharField ( max_length = 255 ) 10 body = models . TextField () 11 created_on = models . DateTimeField ( auto_now_add = True ) 12 last_modified = models . DateTimeField ( auto_now = True ) 13 categories = models . ManyToManyField ( "Category" , related_name = "posts" ) The Category model is very basic. All that it needs is a single CharField in which you store the name of a category for your blog posts.
To keep your category names short, you set a maximum length of thirty characters. The title and body fields on the Post model also contain text. You need a CharField for the title to store a short string for the post title. The body of a post needs to be a long-form piece of text, so you use a TextField . The next two fields, created_on and last_modified , are Django DateTimeFields . These store a datetime object containing the date and time when the post was created and modified, respectively.
For created_on , the DateTimeField takes the argument auto_now_add=True . This assigns the current date and time to this field whenever you create an
The rest of this page is on the live site.