Django post comments not working correctly

I'm trying to create a system for my Django project that allows users to post comments on specific posts. However, this isn't working.

I tried to enter code into forms.py, views.py, urls.py and index.html in order to handle post entries. However, this has instead resulted in the submit button on index.html being without input boxes, and when it's clicked the page reloads with no update to the database.

forms.py:

class PostCommentForm(forms.ModelForm):
    class Meta:
        model = PostComment
        fields = ['post_comment']

views.py:

from .forms import PostCommentForm
from .models import *

def post_comment(request, post_id):
    post = get_object_or_404(Post_Data, pk=post_id)
    
    if request.method == 'POST':
        form = PostCommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.user = request.user
            comment.post = post
            comment.save()
            return redirect('/', pk=post_id)
        else:
            form=PostCommentForm()
            
        return render(request, 'index.html', {'form': form})

urls.py:

from .views import create_post

urlpatterns = [
    path('post/<int:post_id>/comment/', views.post_comment, name='post_comment'),
]

index.html:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit Comment</button>
</form>

models.py:

class PostComment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post_Data, on_delete=models.CASCADE)
    post_comment = models.CharField(max_length=500)
    timestamp = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return f"Comment by {self.user} on {self.post}"

The above code works as intended, but an error occurs if some parts are not typos.

First, the unknown create_post function was imported to urls.py

from .views import post_comment

urlpatterns = [
    path('post/<int:post_id>/comment/', post_comment, name='post_comment'),
]

I modified this part to imported and used the comment creation logic, post_comment.

Next problem is the indentation at views.py .

from .forms import PostCommentForm
from .models import *

def post_comment(request, post_id):
    post = get_object_or_404(Post_Data, pk=post_id)
    
    if request.method == 'POST':
        form = PostCommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.user = request.user
            comment.post = post
            comment.save()
            return redirect('/', pk=post_id)
    else:
        form=PostCommentForm()
            
    return render(request, 'index.html', {'form': form})

For post_comment to work properly, it must be changed as above.

When tested in my environment, the code above does not error occurs and works well as intended.

Back to Top