视图 form.views.form_view 没有 return HttpResponse 对象。它 return 改为 None

The view form.views.form_view didn't return an HttpResponse object. It returned None instead

我尝试了解表单验证,但出现此 ValueError,这是我的 views.py 和 forms.py 文件

forms.py :

from django import forms
from django.core import validators

class SignUp(forms.Form):
    user = forms.CharField(label='User Name', max_length=100)
    email = forms.EmailField(label='Email', max_length=100)
    password = forms.CharField(widget=forms.PasswordInput, label='PassWord')
    botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)])

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import SignUp
# Create your views here.

# 127.0.0.1/ 
def index(request):
    return render(request, 'home/index.html')

# 127.0.0.1/form
def form_view(request):
    if request.method == ('POST'):
        form = SignUp(request.POST)

        if form.is_valid():
            return HttpResponseRedirect('/')
             
          
    else:
        form = SignUp()
        return render(request, 'form.html', {'signupForm' : form})

如果表单不是 valid,则您的 views.py 中没有 else 部分,这就是它抛出错误的原因,因为如果表单验证,您还没有返回 HttpResponse 对象fails。因此,如果表单验证失败,请在 views.py 中添加 HttpResponse

# 127.0.0.1/form
def form_view(request):
    if request.method == ('POST'):
        form = SignUp(request.POST)

        if form.is_valid():
            return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect(/) # render(...) whatever you wanted if form validation fails
         
      
    else:
        form = SignUp()
        return render(request, 'form.html', {'signupForm' : form})