Cookicutter-django自定义用户字段从未保存到数据库

mfuanj7w  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(96)

我正在为cookiecutter-django的一个平庸(我猜)问题而挣扎...
我将字段invitation_code添加到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
    )

然后我将相同的字段添加到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")}),
    )

问题是,当一个新用户保存到DB时,invitation_code字段总是None
谢谢你的帮忙!

ki0zmccv

ki0zmccv1#

解决了!
为了让一切正常运行,我还必须定制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()

相关问题