Surina94
Surina94

Reputation: 93

Django add comment model for comment

I have a model News and model Comment for it. And it works norm.

class News(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    text = models.TextField()
    for_news = models.ForeignKey(News)

In admin.py

 from .models import News, Comment
 class NewsAdd(admin.StackedInline):
    model = Comment
    extra = 0

 class newseAdmin(admin.ModelAdmin):
    inlines = [NewsAdd]

 admin.site.register(News, newseAdmin)

In view

def showNews(request, news_id=1):
    news = Article.objects.get(id=article_id)
    comments = Comment.objects.filter(comments_news_id=article_id)
    return render(request, 'page.html', {'news': news, 'comments': comments})

How can I add an opportunity to reply to a comment? What would be a cascading comment for the comment.

Upvotes: 2

Views: 6937

Answers (2)

Navid Zarepak
Navid Zarepak

Reputation: 4208

As far as I understand, you're trying to allow users replay to comments that have already been posted.

Here is what you need to do:

models.py:

class Comment(models.Model):
    text = models.TextField()
    for_news = models.ForeignKey(News)
    reply_to = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, related_name='replies')

Now you can let users reply to a certain comment by providing a comment id.

You probably need some JavaScript codes in your template. Simply anytime a user clicked on a reply button for a comment, you add a hidden field with a parent comment id and in your view, you just check if any id has been passed to your view or not.

Simple example:

views.py:

replied_comment = request.POST.get('comment_id_input_name')

try:
    comment_object = Comment.objects.get(pk=replied_comment)
except:
    comment_object = None

comment = Comment(text="Some Text", for_news=news_object, reply_to=comment_object)
comment.save()

Upvotes: 7

EarlyCoder
EarlyCoder

Reputation: 1313

Although the question is not clear, from what your code is doing, I am guessing you are trying to fetch all the comments for the piece of news.

So, in your view function, you should say this:

def showNews(request, news_id=1):
    headline_news = Article.objects.select_related().get(id=article_id)
    headline_news_comments = headline_news.news_set.all()
    return render(request, 'page.html', {'news': headline_news , 'comments': headline_news_comments })

If this is not what you are trying to do, please elaborate what you are after.

Upvotes: 0

Related Questions