该视图未返回HttpResponse对象。它返回None

时间:2019-01-28 11:12:01

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

为了测试表单登录,我在视图索引中返回了一个字典。当我单击提交按钮时,我收到此消息错误:

The view accueil.views.index didn't return an HttpResponse object. It returned None instead.

我在哪里弄错了?

def index(request):
formConnex = ConnexionForm()
if request.method=='POST':
    formConnex =ConnexionForm(request.POST)
    if formConnex.is_valid():
        envoi = True
        surnom = formConnex.cleaned_data['surnom']
        password = formConnex.cleaned_data['passeword']
        formConnex = ConnexionForm()   
        dicInfoCon =    {
            'surnom_key':email,
            'password_key':password,
            'envoi_key':envoi
        }

        return render(request,'accueil/index.html',dicInfoCon)
else:
    envoi = False
    formConnex = ConnexionForm() 
    return render(request, 'accueil/index.html', 'formConnex_Key':formConnex})

2 个答案:

答案 0 :(得分:1)

问题仅仅是您的最终返回行缩进得太远。将其移回一个缩进,这样它也可以捕获请求为POST但表单无效的情况。

答案 1 :(得分:-1)

问题在于表格无效。它不从函数返回任何内容。确切地说:

if request.method=='POST':
    formConnex =ConnexionForm(request.POST)  # Please use snake_case
    if formConnex.is_valid():
        envoi = True
        surnom = formConnex.cleaned_data['surnom']
        password = formConnex.cleaned_data['passeword']
        formConnex = ConnexionForm()   
        dicInfoCon = {
            'surnom_key':email,
            'password_key':password,
            'envoi_key':envoi
        }

        return render(request,'accueil/index.html',dicInfoCon)
  # Here should be an else block with how the view should handle if the form is not valid

因此,您可以像这样更新方法(我添加了一些重构):

def index(request):
    formConnex = ConnexionForm(request.POST or None) # Please use snake_case, according to PEP-8 style guide
    if request.method == 'POST':
        if formConnex.is_valid():
            envoi = True
            surnom = formConnex.cleaned_data['surnom']
            password = formConnex.cleaned_data['passeword']
            dicInfoCon = {
                'surnom_key': email,
                'password_key': password,
                'envoi_key': envoi
            }
            return render(request, 'accueil/index.html', dicInfoCon)

    return render(request, 'accueil/index.html', {'formConnex_Key':formConnex})