英文:
Cookiecutter-django custom User field is never saved to DB
问题
我遇到了一个关于cookiecutter-django
的普通(我猜)问题...
我向users.models.User
模型添加了invitation_code
字段:
class User(AbstractUser):
"""
Default custom user model for pintable.
If adding fields that need to be filled at user signup,
check forms.SignupForm and forms.SocialSignupForms accordingly.
"""
#: First and last name do not cover name patterns around the globe
name = CharField(_("Full name"), max_length=255, null=True, blank=True)
first_name = None # type: ignore
last_name = None # type: ignore
invitation_code = CharField(
_("Invitation code"), max_length=8, null=True, blank=True
)
然后,我将相同的字段添加到users.forms.UserSignupForm
:
class UserSignupForm(SignupForm):
"""
Form that will be rendered on a user sign up section/screen.
Default fields will be added automatically.
Check UserSocialSignupForm for accounts created from social.
"""
invitation_code = CharField(
label=_("Invitation code"),
widget=TextInput(attrs={"placeholder": _("Invitation code")}),
)
问题是,当将新用户保存到数据库时,invitation_code
字段总是None
。我漏掉了什么吗..?
感谢您的帮助!
英文:
I'm struggling with a banal (I guess) issue with cookiecutter-django
...
I added the field invitation_code
to users.models.User
:
class User(AbstractUser):
"""
Default custom user model for pintable.
If adding fields that need to be filled at user signup,
check forms.SignupForm and forms.SocialSignupForms accordingly.
"""
#: First and last name do not cover name patterns around the globe
name = CharField(_("Full name"), max_length=255, null=True, blank=True)
first_name = None # type: ignore
last_name = None # type: ignore
invitation_code = CharField(
_("Invitation code"), max_length=8, null=True, blank=True
)
Then I added the same field to users.forms.UserSignupForm
:
class UserSignupForm(SignupForm):
"""
Form that will be rendered on a user sign up section/screen.
Default fields will be added automatically.
Check UserSocialSignupForm for accounts created from social.
"""
invitation_code = CharField(
label=_("Invitation code"),
widget=TextInput(attrs={"placeholder": _("Invitation code")}),
)
The problem is that when a new user is saved to DB, the invitation_code
field is always None
. What am I missing..?
Thanks for your help!
答案1
得分: 1
已解决!
为了使事情正常运行,我不得不自定义users.adapters.AccountAdapter
如下:
def save_user(self, request, user, form, commit=True):
dummy_user = super().save_user(request, user, form, commit=False)
dummy_user.invitation_code = form.cleaned_data["invitation_code"]
if commit:
dummy_user.save()
英文:
Solved!
To make things work I had to customize users.adapters.AccountAdapter
as well:
def save_user(self, request, user, form, commit=True):
dummy_user = super().save_user(request, user, form, commit=False)
dummy_user.invitation_code = form.cleaned_data["invitation_code"]
if commit:
dummy_user.save()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论