G
G
gromyko212020-09-01 14:45:06
Django
gromyko21, 2020-09-01 14:45:06

How to automatically link posts to comments?

In general, there is a small project. Through the forms, it turns out to bind only if you select in the selection window (in the post form) what we leave a comment on, but it is necessary that this be done without user participation. 5f4e329732c81505586978.png
Model

class Article(models.Model):
    """
    Модель для создания новостей на главной странице
    """
    #переменные модели

    def get_absolute_url(self):
        return reverse('articles_url', kwargs={'slug': self.slug})

class Comment(models.Model):
    post = models.ForeignKey(Article, related_name='post', on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=u"Автор", related_name="author")
    body = models.TextField(max_length=1000)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)


view
def articles(request, slug):
    articles = get_object_or_404(Article, slug__iexact=slug)
    #Комментарии

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form.instance.author = request.user
            #form.instance.post = request.article
            #Я думаю, что нужно корректировать строку выше
            form.save()
            return redirect("/")
        else:
            pass
            #messages.error(request, ('Пожалуйста, исправьте ошибки.'))
    else:
        form = CommentForm(instance=request.user)
    comment = Comment.objects.order_by('-pk')
    context = {
        'form':form,
        'comments': comment,
        'articles': articles,
    }
    return render(request, 'home/one_news.html', context)

Here, as I believe, it is necessary to bind somehow through the view, but I don’t understand exactly how.
NOT NULL constraint failed: home_comment.post_id This is the error that comes out if the post variable is not displayed through the form.
And how to show comments only for the article to which they refer? comment = Comment.objects.order_by('-pk') this option shows all comments on each article page.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-09-01
@gromyko21

post = models.ForeignKey(
    Article,
    related_name='post',
    on_delete=models.CASCADE,
    editable=False  # !!!
)

def article(request, slug):
    article = get_object_or_404(Article, slug__iexact=slug)

    # Комментарии
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment_form.instance.author = request.user
            comment_form.instance.post = article
            comment_form.save()
            return redirect('/')
    else:
        comment_form = CommentForm()

    comments = Comment.objects.order_by('-pk')
    context = {
        'article':      article,
        'comments':     comments,
        'comment_form': comment_form,
    }
    return render(request, 'home/one_news.html', context)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question