2

Django 2.2 Python 3.6 После заполнения формы, комментарий прилетает в django, но не сохраняется в БД... Модели постов и комментариев в одном приложении. Ни каких трейсбэков не получаю. Не понимаю что и где я проглядел...

Views.py

def post_detail(request, slug):
    post = Post.objects.get(slug=slug)

    if request.method == 'POST':
        new_comment_form = NewCommentForm(request.POST, instance=post)

        if 'add_comment' in request.POST and new_comment_form.is_valid():
            comment = new_comment_form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.content = request.POST.get('content')
            comment.active = True
            comment.save()
    else:
        new_comment_form = NewCommentForm()

    context = {
        'post': post,
        'new_comment_form': new_comment_form,
    }
    template = 'content/post_detail.html'
    return render(request, template, context)

Forms.py

class NewCommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = (
            'content',
        )

    def save(self, commit=True):
        comment = super(NewCommentForm, self).save(commit=False)
        comment.content = self.cleaned_data['content']

        if commit:
            comment.save()
        return comment

Models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='post_comments', on_delete=models.CASCADE, verbose_name='Комментарии')
    author = models.ForeignKey(VertexUser, related_name='comment_author', on_delete=models.CASCADE, verbose_name='Автор')
    content = models.TextField('Содержание', blank=True)
    like = models.PositiveIntegerField('Лайки', default=0, blank=True, null=True)
    dislike = models.PositiveIntegerField('Дизлайки', default=0, blank=True, null=True)
    publication_date = models.DateTimeField('Дата публикации', auto_now=True, null=True)
    active = models.BooleanField('Опубликовано', default=True)

    def __str__(self):
        return f'Автор {self.author} | Опубликовано {self.publication_date}'

    class Meta:
        verbose_name = 'Комментарий'
        verbose_name_plural = 'Комментарии'

Спасибо за внимание.

2
  • 'add_comment' in request.POST это что? 30 ноя 2019 в 13:02
  • @m0nte-cr1st0 Это я разбираю request.POST что бы узнать какой инпут нажал пользователь. Но проблему я уже решил ))) instance=post была лишней, сразу не заметил... 30 ноя 2019 в 14:07

1 ответ 1

0

new_comment_form = NewCommentForm(request.POST, instance=post)

Привязка в post была лишняя.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.