Creating Views and Templates to Display Blog Posts

Shivay DwivediShivay Dwivedi
5 min read

Welcome back! After setting up our Django project and creating a blog app, it’s time to make those blog posts visible to users on our website. In this article, we'll cover creating views and templates to display the blog posts in a web page. If you think of Django’s views as the "brains" that process data and templates as the "face" that displays it, we’re going to bring these two parts together to show your blog posts.

1. Creating Views

Views in Django are functions that handle requests and return responses. They control what content is displayed to the user and how it's displayed. In this step, we’ll create a view that fetches all the blog posts from the database and sends them to a template for display.

  1. Open Your views.py File:

    • Navigate to the blog directory in your project.

    • Open the views.py file in your text editor or IDE.

  2. Define the View Function: Add the following code to views.py:

     from django.shortcuts import render
     from .models import BlogPost
    
     def index(request):
         posts = BlogPost.objects.all()  # Fetch all blog posts from the database
         return render(request, 'blog/index.html', {'posts': posts})
    

    Explanation:

    • from django.shortcuts import render: Imports the render function, which is used to combine a template with context data.

    • from .models import BlogPost: Imports the BlogPost model so we can query the database for blog posts.

    • def index(request):: Defines a view function named index. The request argument contains information about the current web request.

    • posts = BlogPost.objects.all(): Retrieves all instances of the BlogPost model from the database. This will be a list of all blog posts.

    • return render(request, 'blog/index.html', {'posts': posts}): Uses the render function to generate the HTML response. It takes three arguments:

      • request: The request object.

      • 'blog/index.html': The path to the template that will be used to display the data.

      • {'posts': posts}: A dictionary where the key 'posts' will be available in the template, holding the list of blog posts.

2. Creating Templates

Templates are HTML files that Django uses to render content. They define how the content will look on the web page. Let’s create a template to display the list of blog posts.

  1. Create the Templates Directory:

    • Inside the blog directory, create a new directory named templates.

    • Within the templates directory, create another directory named blog. Your directory structure should look like this:

        blog/
            templates/
                blog/
                    index.html
      
  2. Create index.html:

    • Inside the blog/templates/blog directory, create a file named index.html.

    • Add the following HTML code to index.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>
                        <p><em>Published on {{ post.pub_date }}</em></p>
                    </li>
                {% empty %}
                    <li>No blog posts available.</li>
                {% endfor %}
            </ul>
        </body>
        </html>
      

Explanation:

  • <!DOCTYPE html>: Declares that this is an HTML5 document.

  • <html>...</html>: Wraps all the content of your web page.

  • <head>...</head>: Contains meta-information about the document, such as the title.

  • <body>...</body>: Contains the content of the web page.

  • {% for post in posts %} ... {% endfor %}: A Django template tag that loops through the posts list. For each post, it creates an HTML list item displaying the title, content, and publication date.

  • {% empty %}: Provides a fallback message if there are no blog posts to display.

3. Configuring URLs

To ensure that users can access the page that displays blog posts, we need to map a URL to our view.

  1. Create urls.py in the Blog Directory:

    • In the blog directory, create a file named urls.py.
  2. Add URL Patterns:

    • Add the following code to urls.py:

        from django.urls import path
        from . import views
      
        urlpatterns = [
            path('', views.index, name='index'),
        ]
      

Explanation:

  • from django.urls import path: Imports the path function used to define URL patterns.

  • from . import views: Imports the views module where our view function is defined.

  • path('', views.index, name='index'): Maps the root URL of the blog app ('') to the index view function. This means that when users visit http://127.0.0.1:8000/, Django will call the index function and use the index.html template to display the content.

  1. Include Blog URLs in the Project’s URL Configuration:

    • Open the urls.py file in your project’s main directory (where manage.py is located).

    • Update it to include the blog app’s URLs:

        from django.contrib import admin
        from django.urls import path, include
      
        urlpatterns = [
            path('admin/', admin.site.urls),
            path('', include('blog.urls')),
        ]
      

Explanation:

  • path('admin/', admin.site.urls): Includes the URL patterns for Django’s admin interface.

  • path('', include('blog.urls')): Includes the URL patterns defined in the blog.urls module. This means that the root URL ('') will be handled by the blog app.

4. Testing the Blog Page

Now it’s time to see your blog posts in action!

  1. Start the Development Server:

    • Make sure your Django development server is running. If it’s not, start it with:

        python manage.py runserver
      
  2. Visit the Blog Page:

    • Open your web browser and navigate to http://127.0.0.1:8000/.

    • You should see a list of blog posts displayed on the page. If you don’t see anything, check the following:

      • Make sure the server is running and there are no errors in the terminal.

      • Verify that you have correctly set up your view function, URL patterns, and template.

Congratulations! You’ve successfully created a view to display blog posts and set up a template to render them on your website. You’ve also configured URL patterns to make sure users can access your blog posts. In the next article, we’ll add more features to our blog, such as individual blog post pages and navigation options. Stay tuned for more exciting steps in building your blog app!

0
Subscribe to my newsletter

Read articles from Shivay Dwivedi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shivay Dwivedi
Shivay Dwivedi