0

试图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_nameand没有问题first_name。我找不到该问题的任何解决方案,如果有人能告诉我正确的路径,我将不胜感激。

4

1 回答 1

1

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

new_order = self.fields.keyOrder
于 2013-05-31T18:32:38.110 回答