视图SugarNoter.views.Index没有返回HttpResponse对象。它返回None

时间:2019-10-12 05:17:34

标签: python django

无论何时有新用户注册,即使返回HttpResponse,我也会收到此错误:

  

视图SugarNoter.views.Index没有返回HttpResponse对象。它返回None。

views.py:

def Index(request):
    if request.method=='POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            passwd = form.clean_password2()
            user = auth.authenticate(username=username, password=passwd)
            auth.login(request, user)
            return redirect(f'users/{str(request.user)}')
    else:
        context = {
            'form':UserCreationForm()
        }
        return render(request, 'index.html', context)

html文件

{% load crispy_forms_tags %}
    <div class="container">
      <div class="col-sm-6 my-5 mx-auto">
        <div class="card align-items-center justify-content-center">
          <div class="card-body">
            <form method="POST">
              {% csrf_token %}
              {{ form | crispy }}
              <button type="button" class="btn btn-danger" onclick='window.location="login"'>Login</button>
              <button type="submit" class="btn btn-success">Sign Up</button>
            </form>
          </div>
        </div>
      </div>
    </div>

我该怎么办?

1 个答案:

答案 0 :(得分:1)

form.is_valid()为假时,您还没有处理过这种情况, 在这种情况下,您没有return语句。 因此,您还需要为其他情况返回一些东西... 或将重定向语句移出if条件...

def Index(request):
    if request.method=='POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            passwd = form.clean_password2()
            user = auth.authenticate(username=username, password=passwd)
            auth.login(request, user)
        return redirect(f'users/{str(request.user)}')
    else:
        context = {
            'form':UserCreationForm()
        }
        return render(request, 'index.html', context)

希望这会有所帮助!