[Python] Django post comments not working correctly

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página