Search code examples
pythondjangodjango-viewsdjango-formsdjango-templates

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 django.core import paginator
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from .models import *
from django.views.generic import ListView, CreateView, UpdateView
from django.views.generic.detail import DetailView
from .forms import *
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.core.paginator import Paginator
import random

def index(request):
    postdata=Post_Data.objects.all()
    profiledata=ProfileData.objects.all()
    likedata=Like.objects.all()
    dislikedata=Dislike.objects.all()
    commentdata=PostComment.objects.all()
    

    return render(request, 'index.html', {'title': 'RT', 'postdata': postdata, 'profiledata': profiledata, 'likedata': likedata, 'dislikedata': dislikedata, 'commentdata': commentdata})


def create_comment(request):
    if request.method == 'POST':
        comment = PostCommentForm(request.POST)
        if comment.is_valid():
            post = comment.save()
            post.user = request.user
            post.save()
            return redirect('/')
    else:
        form = PostForm()
        return render(request, 'index.html', {'comment': comment})

urls.py:

from .views import create_post

urlpatterns = [
    path('', views.index, name='RT'),
    path('', views.create_comment, name='comment-creation')
]

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}"

Solution

  • 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.


    Additional

    I thought that the post_comment you told me before and the changed create_comment were functions of the same purpose.

    from .views import create_post
    
    urlpatterns = [
        path('', views.index, name='RT'),
        path('', views.create_comment, name='comment-creation')
    ]
    

    Currently, if you look at urls.py , there are two logics(index, create_comment) on the same path.

    In a code like this, the one placed above is selected.

    That's why when you approach a path like '', the index function runs and the index function does not return the form, so of course the template variable {{form.as _p}} in the connected index.html will not return any

    tag.

    Therefore, of course, you can only see the submit button. enter image description here

    On the other hand, for the create_comment function, {{form.as _p}} will operate because it returns the form.

    def create_comment(request):
        # post = get_object_or_404(Post, 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.save()
                return redirect('/')
        else:
            form = PostCommentForm()
                
        return render(request, 'index.html', {'form': form})
    

    index.html

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

    Changed urls.py

    # I placed it above the index to show the screen when create_comment ran.
    urlpatterns = [
        path('', create_comment, name='post_comment'),
        path('', index, name='RT'),
    ]
    

    enter image description here The above form does not work, because you have to deliver the post value to generate the comment, but currently create_comment does not deliver the post.