创建新用户时的AttributeError

时间:2018-02-16 18:22:32

标签: python django

我收到此错误:

Internal Server Error: /signup/
Traceback (most recent call last):
  File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\python\lib\site-packages\django\utils\deprecation.py", line 142, in __call__
    response = self.process_response(request, response)
  File "C:\python\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response
    if response.get('X-Frame-Options') is not None:
AttributeError: 'str' object has no attribute 'get'

尝试渲染此视图时:

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.is_active = False
            new_user.save()
            current_site = get_current_site(request)
            subject = "Activate your DC-Elects account"
            message = render_to_string('registration/account_activation_email.html', {
                'user': new_user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(new_user.id)),
                'token': account_activation_token.make_token(new_user),
            })
            new_user.email_user(subject, message)
            return reverse('elections:account_activation_sent')
    else:
        form = SignUpForm()
    return render(request, 'registration/signup.html',{
        'form': form,
    })

错误消息不是很具描述性,但是电子邮件正在使用链接正确发送,所以我很困惑为什么会出现错误。如何防止此错误并正确呈现下一个视图?

1 个答案:

答案 0 :(得分:4)

Django的视图函数应该返回HttpResponse个对象。 reverse只是一个生成url字符串而不是响应对象的方法,所以这一行:

return reverse('elections:account_activation_sent')

提出错误。

如果您需要重定向使用redirect快捷方式:

return redirect('elections:account_activation_sent')