My comments are not being displayed in a django blog

39 views Asked by At

I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site. The snippet of my code is below.

views.py

from .models import Post
from django.utils import timezone
from .forms import PostForm, CommentsForm
from  django.contrib.auth.decorators import user_passes_test
# Create your views here.


def home(request):
    return render (request, 'blogapp/home.html')

def blog_list(request):
    post = Post.objects.order_by('-published_date')
    context = {
        'posts':post
    }
    return render(request, 'blogapp/blog_list.html', context)

def blog_detail(request, pk=None):
    detail = Post.objects.get(pk=pk)
    context = {
        'detail': detail
    }
    return render(request, 'blogapp/blog_detail.html', context)


def add_post(request, pk=None):

    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid:
            body = form.save(commit=False)
            body.published_date = timezone.now()
            body.save()
            return redirect('blog_list')
        form = PostForm()
    else:
        form = PostForm()

    context = {
        'form': form
    }
    return render(request, 'blogapp/add_post.html', context)

def add_comments(request, pk=None):
    if request.method == "POST":
        form = CommentsForm(request.POST)
        if form.is_valid:
            comment = form.save(commit=False)
            comment.date_added = timezone.now()
            comment.save()
            return redirect('blog_detail')
        form = CommentsForm()
    else:
        form = CommentsForm()

    context = {
        'form': form
    }
    return render(request, 'blogapp/add_comments.html', context)


urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="homepage"),
    path('blog/', views.blog_list, name="blog_list"),
    path('blog/post/<int:pk>/', views.blog_detail, name="blog_detail"),
    path('blog/add_post/', views.add_post, name="add_post"),
    path('blog/add_comments/', views.add_comments, name="add_comments"),
]

forms.py

from django import forms
from .models import Post, Comments

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('author', 'title', 'post_description',  'image', 'image_description', 'body',)

class CommentsForm(forms.ModelForm):
    class Meta:
        model = Comments
        fields = ('post', 'name', 'body',)



models.py

from django.db import models
from django.utils import timezone

# Create your models here.


class Post(models.Model):
    author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
    title = models.CharField(max_length=300)
    body = models.TextField()
    post_description = models.CharField(max_length=500, blank=True, null=True)
    image = models.ImageField(blank=True, null=True, upload_to="image/")
    image_description = models.CharField(max_length=500, blank=True, null=True)
    published_date = models.DateTimeField(default=timezone.now, blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()


    def __str__(self):
        return self.title



class Comments(models.Model):
    post = models.ForeignKey('Post', related_name="comments", on_delete=models.CASCADE)
    body = models.TextField()
    name = models.CharField(max_length=300)
    date_added = models.DateTimeField(default=timezone.now, blank=True, null=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)


blog_detail.html

{% extends 'base.html' %}
{% load static %}
{% block content %}
    <article>
        <strong>
            <h1><b>{{ detail.title }}</b></h1>
        </strong>
        <h3>POST AUTHOR: {{ detail.author }}</h3>
        <h4><i>{{ detail.post_description }}</i></h4>
        <h4>PUBLISHED:{{ detail.published_date }}</h4>
        <p>
        <hr>
        {% if detail.image %}
            <center>
            <br>
                <img src="{{ detail.image.url }}" width="1000" height="700">
            <br><br>
                <i>IMAGE DESCRIPTION: {{ detail.image_description }}</i>
            </center>
        {% endif %}
        <hr>
        <br><br><br>
            {{ detail.body|linebreaksbr }}
        </p>
        <hr class="solid">
        <h2>COMMENTS ...</h2><a href="{% url 'add_comments' post.pk %}">Add One</a>
           {% for comment in post.comments.all %}
                <strong>
                    {{ comment.name }}-{{ comment.date_added }}
                </strong>
                    {{ comment.body }}
           {% endfor %}
    </article>
{% endblock %}

add_comments.html

{% extends 'base.html' %}
{% block content %}
    <article>
        {% if user.is_authenticated %}
            <h1>CREATE NEW BLOG POST.</h1>
            <form method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit">ADD COMMENT</button>
                <input type="hidden" name="next" value="{% url 'blog_detail' pk=post.pk %}"/>
            </form>
        {% else %}
            <h2>Login <a href="{% url 'login' %}">HERE</a> to add comments.</h2>
        {% endif %}
    </article>

{% endblock %}
1

There are 1 answers

0
Andrey Maslov On

in your template you use {% for comment in post.comments.all %} but in template context there is no post variable you should use {% for comment in detail.comments.all %}