Episode 10: Building a Blog Tutorial Using Django Rest Framework and React with Comment API View

Posted by

In this tutorial, we will be continuing our Blog Tutorial series by implementing a Comment API View using Django Rest Framework and React. In the previous episodes, we have set up the basic structure for our blog application and implemented the post API view. Now, we will be adding the ability for users to leave comments on blog posts.

Step 1: Create Comment Model

First, we need to create a new model for comments in our Django application. Open your models.py file and add the following code:

from django.db import models
from django.contrib.auth.models import User

class Comment(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.content

In this model, we have a foreign key to the Post model (which we created in a previous episode), as well as a foreign key to the User model for the author of the comment. We also have a content field for the actual comment text, and a created_at field to store the timestamp when the comment was created.

Step 2: Create Comment Serializer

Next, we need to create a serializer for our Comment model. Create a new file named serializers.py in your blog app directory and add the following code:

from rest_framework import serializers
from .models import Comment

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = '__all__'

This serializer will help us serialize Comment objects into JSON format so that we can send and receive comments over the API.

Step 3: Create Comment API View

Now, we will create a new API view for handling comments. Open your views.py file and add the following code:

from rest_framework import viewsets
from .models import Comment
from .serializers import CommentSerializer

class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

This viewset provides CRUD functionality for comments, allowing users to create, retrieve, update, and delete comments using the API.

Step 4: Register Comment API View

Next, we need to register our Comment API view in the urls.py file. Open your urls.py file and add the following code:

from rest_framework.routers import DefaultRouter
from .views import CommentViewSet

router = DefaultRouter()
router.register(r'comments', CommentViewSet)
urlpatterns += router.urls

This code snippet registers our Comment API view with the Django Rest Framework router, making it accessible at the /api/comments/ endpoint.

Step 5: Create Comment Component in React

Now, let’s create a new Comment component in our React frontend to display comments on blog posts. Create a new file named Comment.js in your components directory and add the following code:

import React from 'react';

const Comment = ({ comment }) => {
    return (
        <div>
            <p>{comment.content}</p>
            <p>By: {comment.author.username}</p>
        </div>
    );
};

export default Comment;

This component will render an individual comment on a blog post, displaying the comment content and the author’s username.

Step 6: Fetch Comments in Post Component

In your Post component, add a new useEffect hook to fetch comments for the current post from the API. Here’s an example code snippet to get you started:

import React, { useState, useEffect } from 'react';
import Comment from './Comment';

const Post = ({ post }) => {
    const [comments, setComments] = useState([]);

    useEffect(() => {
        fetch(`/api/posts/${post.id}/comments/`)
            .then(response => response.json())
            .then(data => setComments(data));
    }, [post.id]);

    return (
        <div>
            <h2>{post.title}</h2>
            <p>{post.content}</p>
            <h3>Comments:</h3>
            {comments.map(comment => <Comment comment={comment} key={comment.id} />)}
        </div>
    );
};

export default Post;

This code snippet demonstrates how to fetch comments for a specific post using the fetch API in React and render them using the Comment component.

Step 7: Add Comment Form

Lastly, we can add a comment form to allow users to leave comments on blog posts. Create a new CommentForm.js file in your components directory and add the following code:

import React, { useState } from 'react';

const CommentForm = ({ postId }) => {
    const [content, setContent] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        fetch('/api/comments/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ post: postId, content })
        })
            .then(response => response.json())
            .then(data => {
                console.log('Comment saved successfully:', data);
                setContent('');
            });
    };

    return (
        <form onSubmit={handleSubmit}>
            <textarea value={content} onChange={e => setContent(e.target.value)}></textarea>
            <button type="submit">Add Comment</button>
        </form>
    );
};

export default CommentForm;

This component provides a simple form for users to enter a comment and submit it to the API. It uses the useState hook to manage the comment content and the fetch API to send the comment data to the server.

That’s it! You have now implemented a Comment API View using Django Rest Framework and React in your blog application. Users can leave comments on blog posts, and those comments can be viewed and managed through the API. Feel free to customize the implementation further to suit your needs or add more features to enhance the user experience. Happy coding!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@altyar
1 month ago

hi
I have an error and I don't know where it is
I got this message
Failed to load API definition.

Errors