1

i want to implement something like fb does like displaying all the respective comments below their respective posts in home page
model.py

from django.db import models
from django.contrib.auth.models import User


class Post(models.Model):
    post = models.CharField(max_length=500)
    image = models.ImageField(upload_to = 'profile_image')
    user = models.ForeignKey(User ,on_delete = 'models.CASCADE')
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.post

class Comment(models.Model):
    user = models.ForeignKey(User,on_delete = 'models.CASCADE')
    post = models.ForeignKey(Post, null = True, on_delete = 'models.CASCADE')
    comment = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.comment  

views.py

from django.views.generic import TemplateView
from django.shortcuts import render, redirect,get_object_or_404
from django.contrib.auth.models import User
from home.forms import HomeForm,Home,CommentForm
from home.models import Post ,ImagePost,Comment


class HomeView(TemplateView):
    template_name = 'home/home.html'

    def get(self, request):
        form = HomeForm()
        form1 = CommentForm()
        posts = Post.objects.filter(user = request.user).order_by('-created')
        comments = Comment.objects.all()
        users = User.objects.exclude(id=request.user.id)
        args = {
            'form': form, 'posts': posts, 'users': users, 'form1':form1,
            'comments':comments,
        }
        return render(request, self.template_name, args)

    def post(self, request):
        form1 = CommentForm()
        text = ''
        if request.method == 'POST':
            form = HomeForm(request.POST,request.FILES)
            if form.is_valid():

                post = form.save(commit=False)
                post.user = request.user
                post.save()
                text = form.cleaned_data['post']
                form = HomeForm()
                form1 = CommentForm()
                return redirect('home:home')
    def cmnt(self , request):
        text = ''
        form1 = CommentForm()
        if request.method == 'POST':
            form1 = CommentForm(request.POST,post.id)
            if form.is_valid():
                comment = form.save(commit = False)
                comment.user = request.user
                comment.post = request.post
                comment.save()
                text = form.cleaned_data['comment']
                form1 = CommentForm()
                form = HomeForm()
                return redirect('home:home')

            args = {'form': form, 'text': text , 'form1':form1}
            return render(request, self.template_name, args)

home.html

{% extends 'base.html' %}
{%  load static %}

{% block body %} 
<div class="container">
    <div class="col-md-8">
        <h2>Home</h2>
        <form  method="POST" enctype="multipart/form-data" type = 'file'>
            {% csrf_token %}
            {{ form.post }}
            {{ form.image }}
            <br>
            <button type="submit">Submit</button>
        </form>
        <h2>{{ text }}</h2>
        {% for post in posts %}
            <h1>{{ post.post }}</h1>
            <br>
            <img src="{{ post.image.url }}" width = 240 >
            <p>Posted by {{ post.user.get_full_name }} on {{ post.created }}</p>
        <form  method="POST" enctype="multipart/form-data" type = 'file'>
            {% csrf_token %}
            {{ form1.comment }}
            <br>
            <button type="submit">Submit</button>
        </form>

            {% for comment in comments %}
            {% if comment.post_id == post.id %}
            <h1>{{ comment.comment }}</h1>
            <p>commented by {{ comment.user.get_full_name }} on {{ comment.created }}</p>
            {% endif %}
            {% endfor %}
        {% endfor %}

    </div>

</div>
{% endblock %}  

using my django admin i am able to assign comments to the respective post and display it

i am finding difficulty to assign comment's post_id with the post id

urls.py

from django.conf.urls import url 
from django.urls import path
from .import views
from home.views import HomeView


app_name = "home"
urlpatterns = [
     path('',HomeView.as_view(), name='home'),
     ]

3 Answers3

0

first, change Comment model like this:

class Comment(models.Model):
    user = models.ForeignKey(User,on_delete = 'models.CASCADE')
    post = models.ForeignKey(Post, null = True, on_delete = 'models.CASCADE')
    text = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.text

second, you don't need return list of comment to the template. do like this in your template:

{% extends 'base.html' %}
{%  load static %}

{% block body %} 
<div class="container">
    <div class="col-md-8">

        <h2>{{ text }}</h2>
        {% for post in posts %}
           <h1>{{ post.post }}</h1>
           <br>
           <img src="{{ post.image.url }}" width = 240 >
           <p>Posted by {{ post.user.get_full_name }} on {{ post.created }}</p>

            {% for comment in post.comment_set.all %}

                <h1>{{ comment.text }}</h1>
                <p>commented by {{ comment.user.get_full_name }} on {{ comment.created }}</p>            
           {% endfor %}
        {% endfor %}

</div>
Ali
  • 2,541
  • 2
  • 17
  • 31
  • by making the changes i am able to display comments but, i want logged in users to add comments for that i made a comment form(u can see it in home.html form1 is COMMENTS FORM) [link](http://dpaste.com/28H8TB9) i get this error – Prince Nihith Jul 08 '18 at 09:20
  • If my answer is correct, check it out and put this question in another post so that others can use it. – Ali Jul 08 '18 at 09:27
0

I think your problem is here

form1 = CommentForm(request.POST,Post.id)

p in post should be lowercase

form1 = CommentForm(request.POST,post.id)

you have two POST forms. for every post write separate view. you accept both form in just one view. it's incorrect.

Ali
  • 2,541
  • 2
  • 17
  • 31
0
def post(self, request):
    form1 = CommentForm()
    text = ''
    if request.method == 'POST':
        form = HomeForm(request.POST,request.FILES)
        if form.is_valid():

            post = form.save(commit=False)
            post.user = request.user
            post.save()
            text = form.cleaned_data['post']
            form = HomeForm()
            form1 = CommentForm()
            return redirect('home:home')

in post method you redirect to home page. it means, you call get method of HomeView.

in get method, you need below variable in context dict

args = {
        'form': form, 'posts': posts, 'users': users, 'form1':form1,
        'comments':comments,
    }

but you don't set value for these variables.

Ali
  • 2,541
  • 2
  • 17
  • 31