gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:32:26 24 4
gpt4 key购买 nike

我正在使用 django-userena。我有一个名为 UserProfile 的模型。我在注册表单中添加了额外的字段。这些字段显示正确但数据未保存。我也想将一些字段数据保存到另一个模型 (Business) 中。例如,我有两个字段,如 contactbusiness。我希望联系人字段转到 UserProfile 模型,业务 字段转到业务模型。任何线索?谢谢

这是我的代码

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

更新:我将这些值存储在一个用户实例上...我想将它们存储在配置文件模型上——一个绑定(bind)到用户的实例

最佳答案

此处为 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

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

url(r'^accounts/signup/$',
userena_views.signup,
{'signup_form': SignupFormExtra}),

这应该可以解决问题!祝你好运。

关于python - 向 django-userena 表单添加额外字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com