0
私は別のプロジェクトでこの正確なコードを使用していますが、唯一の違いはモデル名、URLパターン、テンプレート名が異なるプロジェクトであることです。しかし、私はこのエラーが発生していると私は理由が分からない。私は、ポストとそのポストに関するコメントの両方を持つ詳細ページにユーザーを連れて来ようとしているだけでなく、ユーザーがポストにコメントを追加できるページへのリンクも持っています。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.
これで、IntegrityError at/feed/post/5/comment/ NOT NULL制約が失敗しました:feed_usercomment.author_id'が動作します。 – Garrett
保存する前に 'comment.author = request.user'を設定する必要があるでしょう。 –
ありがとうございました – Garrett