видео:
исходный код:
# views.py class HomeDetailView(CustomSuccessMessageMixin, FormMixin, DetailView): model = Articles template_name = 'detail.html' context_object_name = 'get_article' form_class = CommentForm success_msg = 'Комментарий успешно создан, ожидайте модерации' def get_success_url(self): return reverse_lazy('detail_page', kwargs={'pk':self.get_object().id}) def post(self,request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self,form): self.object = form.save(commit=False) self.object.article = self.get_object() self.object.author = self.request.user self.object.save() return super().form_valid(form)
#models.py # Create your models here. class Articles(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='Владелец статьи', blank = True, null = True ) create_date = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200, verbose_name='Название') text = models.TextField(verbose_name='Текст') def __str__(self): return self.name class Meta: verbose_name='Статью' verbose_name_plural='Статьи' class Comments(models.Model): article = models.ForeignKey(Articles, on_delete = models.CASCADE, verbose_name='Статья', blank = True, null = True,related_name='comments_articles' ) author = models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='Автор комментария', blank = True, null = True ) create_date = models.DateTimeField(auto_now=True) text = models.TextField(verbose_name='Текст комментария') status = models.BooleanField(verbose_name='Видимость статьи', default=False)
#forms.py class CommentForm(forms.ModelForm): class Meta: model = Comments fields = ('text',) def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' self.fields['text'].widget = Textarea(attrs={'rows':5})