Answer the question
In order to leave comments, you need to log in
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.
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)
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)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question