2017-09-15 74 views
0

我在另一个项目中使用了这个确切的代码,唯一的区别是我改变了模型名称,网址模式和模板名称,因为它是一个不同的项目。但是,我收到这个错误,我不知道为什么。我正在尝试将用户带到一个详细信息页面,该信息页面既包含帖子,也包含对帖子的任何评论,还包含一个链接,该链接指向允许用户向帖子添加评论的页面。ValueError at/feed/post/5/comment /视图feed.views.add_comment_to_post没有返回HttpResponse对象。它返回None而不是

应用Views.py:

@login_required 
def add_comment_to_post(request,pk): 
    post = get_object_or_404(UserPost,pk=pk) 
    if request.method == 'POST': 
     form = CommentForm(request.POST) 
     if form.is_valid(): 
      comment = form.save(commit=False) 
      comment.post = post 
      comment.save() 
      return redirect('feed:post_detail', pk=userpost.pk) 
     else: 
      form = CommentForm() 
     return render(request,'feed/comment_form.html',{'form':form}) 

userpost_detail.html(在URL中post_detail)

{% extends 'base.html' %} 

{% block content %} 

    <h1 class="posttitle">{{ userpost.title }}</h1> 

    <p class="postcontent">{{ userpost.post_body }}</p> 

    {% if request.user.is_authenticated and request.user == post.author %} 
     <a class="link" href="{% url 'feed:edit_post' post.id %}">Edit Post</a> 
    {% endif %} 

    <hr> 


    <a href="{% url 'feed:add_comment' userpost.id %}">Add Comment</a> 

    <div class="container"> 
     {% for comment in post.comments.all %} 
     <br> 
      {% if user.is_authenticated or comment.approved_comment %} 
       {{ comment.create_date }} 
       <a class="btn btn-warning" href="{% url 'comment_remove' pk=comment.pk %}"> 
        <span class="glyphicon glyphicon-remove"></span> 
       </a> 
       <p>{{ comment.comment_body }}</p> 
       <p>Posted By: {{ comment.author }}</p> 
      {% endif %} 
      {% empty %} 
      <p>No Comments</p> 
     {% endfor %} 
    </div> 

{% endblock %} 

comment_form.html:

{% extends 'base.html' %} 

{% block content %} 

    <h1>New Comment</h1> 
    <form class="post-form" method="POST"> 
     {% csrf_token %} 
     {{ form.as_p }} 
     <button type="submit" class="save btn btn-default">Add Comment</button> 
    </form> 

{% endblock %} 

回溯和错误:

Traceback (most recent call last): 
    File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner 
    response = get_response(request) 
    File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 198, in _get_response 
    "returned None instead." % (callback.__module__, view_name) 
ValueError: The view feed.views.add_comment_to_post didn't return an HttpResponse object. It returned None instead. 

回答

1

如果请求不是POST,您的视图不会返回任何内容。

问题是缩进之一。最后三行 - 从else开始 - 需要被移回一个级别。

+0

我现在有一个完整性错误'/ IntegrityError at/feed/post/5/comment/ NOT NULL约束失败:feed_usercomment.author_id'但除此之外它现在可以工作,谢谢。 – Garrett

+0

你大概需要在保存之前设置'comment.author = request.user'。 –

+0

修好了,谢谢 – Garrett

相关问题