django-userena中的额外字段无法从表单中检索值

时间:2013-05-31 17:21:22

标签: django

尝试将django-userena用于我的某个项目。但是在检索其中一个表单字段的值时遇到问题。

我的表单如下所示(与演示几乎相同,只添加了phone字段):

class SignupFormExtra(SignupForm):
    first_name = forms.CharField(label=_(u'First name'), max_length=30, required=False)
    last_name = forms.CharField(label=_(u'Last name'), max_length=30, required=False)
    phone = forms.CharField(label=_(u'Phone'), max_length=15, required=False)

    def __init__(self, *args, **kw):
        super(SignupFormExtra, self).__init__(*args, **kw)
        # Put the first and last name at the top
        new_order = self.fields.keyOrder[:-2]
        new_order.insert(0, 'first_name')
        new_order.insert(1, 'last_name')
        self.fields.keyOrder = new_order

    def save(self):
        # First save the parent form and get the user.
        new_user = super(SignupFormExtra, self).save()

        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.save()

        user_profile = new_user.get_profile()
        user_profile.user = new_user
        user_profile.phone_number = self.cleaned_data['phone']
        user_profile.save()

        return new_user

现在,当我以注册形式填写字段并点击“提交”时,我收到以下错误:

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/userena/decorators.py" in _wrapped_view
28. return view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/userena/views.py" in signup
119. user = form.save()
File "/home/qwerty/dev/projects/qqq/accounts/forms.py" in save
50. user_profile.phone_number = self.cleaned_data['phone'] # problem is here

Exception Type: KeyError at /accounts/signup/
Exception Value: 'phone'

这里很奇怪的是self.cleaned_data['phone']总是空的,即使我输入数据,但访问last_namefirst_name没有问题。我找不到任何问题的解决方案,如果有人能告诉我正确的道路,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

通过执行self.fields.keyOrder[:-2],您实际上忽略了最后两个字段。你不应该对列表进行切片。

new_order = self.fields.keyOrder