from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

from article.models import ArticlePost
from .forms import CommentPost


@login_required(login_url='/user/login')
def post_comment(request, article_id):
    article = get_object_or_404(ArticlePost, id=article_id)
    if request.method == 'POST':
        comment_form = CommentPost(data=request.POST)
        if comment_form.is_valid():
            new_comment_form = comment_form.save(commit=False)
            new_comment_form.article = article
            new_comment_form.user = request.user
            new_comment_form.save()
            return redirect(article)
        else:
            return HttpResponse('表单有错误，请重新填写')
    else:
        return HttpResponse('发表评论仅接受POST请求')
