Django重定向不适用于注册

时间:2018-07-26 10:32:45

标签: python django django-views

ValueError at /
The view landing.views.base didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL:    http://127.0.0.1:8000/?ex=tset1&adalt=1
Django Version: 2.0.7
Exception Type: ValueError
Exception Value:    
The view landing.views.base didn't return an HttpResponse object. It returned None instead.
Exception Location: /var/www/venv/lib/python3.5/site-packages/django/core/handlers/base.py in _get_response, line 139
Python Executable:  /var/www/venv/bin/python
Python Version: 3.5.2

这是Django 2.0.7的错误 有人有主意吗?

EDIT:查看代码:

def base(request):
    c = {}
    c.update(csrf(request))

    if request.method == 'POST':
        # set form and valid
        r_form= forms.RegisterForms(request.POST)
        if r_form.is_valid():
            usr = models.YammyUsers()
            usr.contact = r_form.cleaned_data['f_contact']
            # usr.dt_reg = timezone.now()
            # usr.exchange = ex
            # usr.adalt = bool(adalt)
            # usr.source_url = sourse
            usr.save()

            c['r_form'] = r_form
            return redirect(reverse('complete'))

    else:
        r_form = forms.RegisterForms(request.GET)
        ex = request.GET.get('ex', '')
        adalt = request.GET.get('adalt', 0)
        if request.META['HTTP_REFERER']:
            sourse = request.META['HTTP_REFERER']
        else:
            sourse = ''

        c['r_form']=r_form
        return render(request,'landing/forma_reg.html',c)

1 个答案:

答案 0 :(得分:0)

这里:

def base(request):
    # code here...

    if request.method == 'POST':
        # set form and valid
        r_form= forms.RegisterForms(request.POST)
        if r_form.is_valid():
            # code here...
            return redirect(reverse('complete'))

    else:
        r_form = forms.RegisterForms(request.GET)
        # code here...
        return render(request,'landing/forma_reg.html',c)

仅当它是POST请求且表单有效时才执行第一个return语句,而仅当我是GET请求时才执行第二个return语句,因此,如果它是POST请求且表单无效,则该函数结束而没有显式返回,因此隐式返回None

实际上,修复很容易:只需缩进您的最后一个return语句,那么将以错误消息的形式重新显示无效的表单:

def base(request):
    # code here...

    if request.method == 'POST':
        # set form and valid
        r_form= forms.RegisterForms(request.POST)
        if r_form.is_valid():
            # code here...
            return redirect(reverse('complete'))

    else:
        r_form = forms.RegisterForms(request.GET)
        # code here...

    # make sure we ALWAYS return a response
    return render(request,'landing/forma_reg.html',c)