该视图未返回HttpResponse对象。它返回了None。请求方法:POST

时间:2015-03-28 21:02:29

标签: python django

提交表单时出现问题。几天前它工作了,我在这段代码中没有改变,但现在它失败了。是否有可能不同的模块使该部分代码崩溃? 回溯:

环境:

Request Method: POST
Request URL: http://127.0.0.1:8000/users/new/

Django Version: 1.7.3
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'mojblog',
 'users')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/home/marta/django/djangovenv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  130.                                  % (callback.__module__, view_name))

Exception Type: ValueError at /users/new/
Exception Value: The view users.views.create didn't return an HttpResponse object. It returned None instead.

代码:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from users.forms import UserCreationForm
from django.contrib.auth.models import User
from users.models import Profile


def test(request):
    return HttpResponse('users!')


def create(request):
    if request.method =="POST":
        new_user=User()
        form = UserCreationForm(request.POST, instance=new_user)
        if form.is_valid():
            new_user=form.save(commit=False)
            new_user.is_active=False
            new_user.save()
            return redirect("users:new")

    else:
        form = UserCreationForm()
        return render(request, 'users/create.html', {'form1': form})


    # else:
    #   return HttpResponse("something")        

def activate(request, key):

    profile=Profile.objects.get(secret=key)
    user=profile.user
    user.is_active=True
    user.save()



    return render(request, 'users/activate.html', {})

1 个答案:

答案 0 :(得分:3)

create视图中,如果请求是POST但表单无效,则代码不会返回任何内容。

不应该使用单独的GET块,而应使用标准模式:

if request.method =="POST":
    form = ...
    if form.is_valid():
        ...
        return redirect(...)
else:
    form = ...
return render(request, 'users/create.html', {'form1': form})

在这种情况下,最终的返回捕获该情况,并重新呈现表单,以便显示错误。