向django-userena表单添加额外的字段

7 python django registration

我在用django-userena.我有一个名为的模型UserProfile.我在注册表单中添加了额外的字段.并且这些字段显示正确但不保存数据.我想将一些字段数据保存到另一个Model(Business)中.例如,我有两个像contact和的字段business.我想联系字段将去UserProfile模型和business字段将去Business Model.任何线索?谢谢

这是我的代码

class SignupFormExtra(SignupForm):
    address = forms.CharField(label=_(u'Address'),max_length=30,required=False)
    contact = forms.CharField(label=_(u'Contact'),max_length=30,required=False)
    business = forms.CharField(label=_(u'Business Name'),max_length=30,required=False)

    def save(self):
        """
        Override the save method to save the first and last name to the user
        field.

        """

        user_profile = super(SignupFormExtra, self).save(commit=False)

        user_profile.address = self.cleaned_data['address']
        user_profile.contact = self.cleaned_data['contact']
        user_profile.business = self.cleaned_data['business']

        user_profile.save()

        return user_profile
Run Code Online (Sandbox Code Playgroud)

更新:我将这些值存储在User实例上...我想将它们存储在Profile模型上 - 一个绑定到User的实例

wun*_*nki 10

Userena的作者在这里.我已经收到了与"no_access"的电子邮件通信,但如果其他人遇到同样的问题,则值得指出解决方案.第一个错误是该save方法返回一个配置文件.这不是真的,它返回一个Django User.因此,您首先必须获取配置文件并对其进行更改.保存配置文件,然后再次返回用户以使其与Userena兼容.

对于Business模型,只需在save方法中添加它.

class SignupFormExtra(SignupForm):
    address = forms.CharField(label=_(u'Address'),max_length=30,required=False)
    contact = forms.CharField(label=_(u'Contact'),max_length=30,required=False)
    business = forms.CharField(label=_(u'Business Name'),max_length=30,required=False)

    def save(self):
        """
        Override the save method to save the first and last name to the user
        field.

        """
        # Original save method returns the user
        user = super(SignupFormExtra, self).save()

        # Get the profile, the `save` method above creates a profile for each
        # user because it calls the manager method `create_user`.
        # See: https://github.com/bread-and-pepper/django-userena/blob/master/userena/managers.py#L65
        user_profile = user.get_profile()

        # Be sure that you have validated these fields with `clean_` methods.
        # Garbage in, garbage out.
        user_profile.address = self.cleaned_data['address']
        user_profile.contact = self.cleaned_data['contact']
        user_profile.save()

        # Business
        business = self.cleaned_data['business']
        business = Business.objects.get_or_create(name=business)
        business.save()

        # Return the user, not the profile!
        return user
Run Code Online (Sandbox Code Playgroud)

创建表单后,不要忘记覆盖urls.py中的userena表单.这样的事情会做:

url(r'^accounts/signup/$',
        userena_views.signup,
        {'signup_form': SignupFormExtra}),
Run Code Online (Sandbox Code Playgroud)

这应该够了吧!祝好运.

  • 真棒!现在你所要做的就是更新文档:) http://docs.django-userena.org/en/latest/faq.html#how-do-i-add-extra-fields-to-forms (2认同)