只需使用电子邮件和密码UserCreationForm创建Django用户

2024-09-30 08:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在我的应用程序中只使用emailpassword字段创建一个用户帐户。因此,我的自定义用户模型模型.py是:

我定制了UserManager来创建用户

from django.contrib.auth.models import BaseUserManager

class UserManager(BaseUserManager):
    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError("Users must have an email address")
            email = self.normalize_email(email)
            user = self.model(email = email, **extra_fields)
            user.set_password(password)
            user.save()
            return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')
        return self._create_user(email, password, **extra_fields)

我的用户模型是:

^{pr2}$

在我的设置中,我添加了:

AUTH_USER_MODEL = ‘my_app_name.User’

创建用户-UserCreationForm预建类

要创建用户,我使用UserCreationFormpre-built in the django core.

在这个类中,用户名字段使用such as denoted here

根据以上所述,在我的表单.py我有:

from django.contrib.auth.forms import UserChangeForm, UserCreationForm

class CustomUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = get_user_model()

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = get_user_model()

class UserCreateForm(UserCreationForm):

    class Meta:
        fields = ("email", "password1", "password2",)
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["email"].label = "Email address"

当我尝试执行python时管理.pymakemigrations,我得到这个回溯输出错误

    bgarcial@elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts 
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
    app_config.ready()
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready
    self.module.autodiscover()
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/bgarcial/workspace/ihost_project/accounts/admin.py", line 8, in <module>
    from .forms import CustomUserChangeForm, CustomUserCreationForm
  File "/home/bgarcial/workspace/ihost_project/accounts/forms.py", line 16, in <module>
    class CustomUserCreationForm(UserCreationForm):
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/forms/models.py", line 257, in __new__
    raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
(ihost) 
bgarcial@elpug ‹ testing ●● › : ~/workspace/ihost_project

当然,我使用的是UserCreationFormdjango类核心,我强制使用django核心功能,其中username字段是必需的

如何删除用户名或修改此用户名?在

我知道不建议修改django核心,但是,如何使用UserCreationFormdjango类核心来创建一个不包含用户名字段的用户呢?在

我尝试在创建用户的地方重写表单的save方法,但是我没有明确的过程,我认为我不方便的核心是使用UserCreationFormdjango类核心。。在

class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("email", "password1", "password2",)
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["email"].label = "Email address"

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]

        # Tell to Django that not check the username

        if commit:
            user.save()
        return user

如果有人能为我指出正确的方向,我将不胜感激。:)


Tags: django用户inpyselffieldshomeemail
1条回答
网友
1楼 · 发布于 2024-09-30 08:20:27

我找到了一个有效的解决办法。在

不管怎样,请随时提出更好的解决方案!在

就像我的不方便/错误与使用UserCreationFormpre-built in the django core有关,后者是{a2},然后我继续做以下工作:

在我的表单.py在我的类中,CustomUserCreationForm是类UserCreationForm的子类,我使用email字段而不是username字段重写/添加到Meta类中。 This question post帮我。在

我的班级CustomUserCreationForm保持如下状态:

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = get_user_model()
        fields = ('email',)

然后,我继续进行迁移:

^{pr2}$

这个错误告诉我username字段不是我的User模型的属性。 这意味着Django继续尝试询问username字段,即使我用email字段覆盖了fields值。在

当然,这是逻辑的,因为我仍然继承自UserCreationFormpre-built in the django core

然后,我将username字段添加到具有null=True属性的用户模型中,这样,在创建用户帐户时不需要用户名:

class User(AbstractBaseUser, PermissionsMixin):

    # I had add the username field despite that I don't use in my User model
    username = models.CharField(_('username'), max_length=30, null=True,
            help_text=_('Required. 30 characters or fewer. Letters, digits and ''@/./+/-/_ only.'),
        validators=[RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
        ])

    email = models.EmailField(unique=True, null=True,
            help_text=_('Required. Letters, digits and ''@/./+/-/_ only.'),
        validators=[RegexValidator(r'^[\w.@+-]+$', _('Enter a valid email address.'), 'invalid')
        ])

  ...

这样,我执行迁移

bgarcial@elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts 
Migrations for 'accounts':
  accounts/migrations/0001_initial.py:
    - Create model User
(ihost) 
bgarcial@elpug ‹ testing ●● › : ~/workspace/ihost_project

python manage.py migrate accounts ...

我的用户名字段仍然保留在我的自定义用户模式中,只是这不是必需的,当我从继承自UserCreationFormUserCreateForm类创建用户时,我可以只使用电子邮件和密码创建一个用户帐户

enter image description here

我不知道这是否是解决这个麻烦的最好办法。 随时提出改进建议!在

相关问题 更多 >

    热门问题