我在另一个项目中使用这个确切的代码,唯一的区别是我更改了模型名称,网址模式和模板名称,因为它是一个不同的项目。但是,我收到此错误,我不知道为什么。我正在尝试将用户带到一个详细信息页面,其中包含帖子和帖子上的任何评论,以及一个链接,该链接指向允许用户在帖子中添加评论的页面。
app 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.
答案 0 :(得分:1)
如果请求不是POST,您的视图不会返回任何内容。
问题是缩进。最后三行 - 从else
开始 - 需要向后移动一级。