ade desmond
ade desmond

Reputation: 484

Django how to adding comments option on a post

I am developing a blog which i want to add comment form option to it, i have added the form to the same page directly under the article, i want that went a user comment it should redirect to the same page with the article but i keep getting and error here is my code view

def comment(request, article_id):
try:
    article = Article.objects.get(pk=article_id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            article.comments_set.create(comment=comment)
            #messages.infos(request,comment)
            return redirect('blog:_article')
    #else:
        #pass
        #form = CommentForm()
        #context['form'] = form
    #return render(request,'blog/comment.html', context)
except Exception as e:
    #wriet error to file
    return render(request,'blog/404.html')

urls

from django.urls import path
from . import views




app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
path('<int:article_id>/article', views._article, name='_article'),
path('<int:article_id>/comment', views.comment, name='comment'),

]

models

class Comments(models.Model):
comment = models.TextField()
date = models.DateTimeField(default=timezone.now)
article = models.ForeignKey(Article, on_delete=models.CASCADE)

def __str__(self):
    return self.comment

form

           <form method="post" action="{% url 'blog:comment' article.id %}">
                {% csrf_token %}
                {% for field in form %}
                 {{ field.label_tag }}
                 {% render_field field class="form-control is-valid" rows="4" %}
                {% endfor %}<br>
                <button class="btn btn-success">Post</button>
            </form>

Upvotes: 1

Views: 2024

Answers (2)

ade desmond
ade desmond

Reputation: 484

I finally did it by adding the code to handle the comment in the same view that renders the articles this is my code

def _article(request, article_id):
try:
    article = Article.objects.get(pk=article_id)
    related_articles = Article.objects.filter(tags=article.tags).exclude(pk=article.pk)[:4]
    context['article'] = article
    context['related_articles'] = related_articles
    context['form'] = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            article.comments_set.create(comment=comment)
    return render(request,'blog/article.html', context)
except Exception as e:
    #write error to file
    return render(request,'blog/404.html')

Upvotes: 2

Emin Bugra Saral
Emin Bugra Saral

Reputation: 3786

If you don't want the page to redirect to another page or update the page, you should use AJAX (https://www.w3schools.com/jquery/jquery_ajax_get_post.asp) in this case. Your form will hit the url in the action by changing your page to that url so you have to handle the redirecting and rendering in your commenting view to come back to same page if you don't wanna do this dynamically.

Upvotes: 0

Related Questions