ValueError:未返回HttpResponse对象。它返回None

时间:2019-01-18 09:18:47

标签: python django python-3.x django-forms django-views

我要编辑帖子时遇到问题。当我按编辑时-我遇到了这个问题:

ValueError at /post/19/edit/
The view blog.views.post_edit didn't return an HttpResponse object. It returned None instead.

urls.py:

url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'),

views.py:

def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
    form = PostForm(request.POST, request.FILES, instance=post)
    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.published_date = timezone.now()
        post.save()
        return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
        return render(request, 'blog/post_edit.html', {'form':form})

post_edit.html:

{% block content %}
<h1>Edit Post</h1>
<form method="post" class="post-form" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}

2 个答案:

答案 0 :(得分:0)

您的request.method不是POST。只要做:

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        if form.is_valid():
        ....
        else:
        .....
    # return a response in cases when request.method is not POST
    return HttpResponse()

答案 1 :(得分:0)

您的缩进在两个地方是错误的。如果请求不是POST,则需要实例化空白表格。并且您需要在所有情况下都返回。所以:

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
     else:
        form = PostForm(instance=post)
     return render(request, 'blog/post_edit.html', {'form':form})

请注意,else如何与第一个if对齐,并且返回值不在两者之内。