Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 仅使用电子邮件和密码创建Django用户-UserCreationForm_Python_Django_Django Users - Fatal编程技术网

Python 仅使用电子邮件和密码创建Django用户-UserCreationForm

Python 仅使用电子邮件和密码创建Django用户-UserCreationForm,python,django,django-users,Python,Django,Django Users,我需要在我的应用程序中仅使用电子邮件和密码字段创建一个用户帐户。因此,my models.py中的自定义用户模型为: 我自定义UserManager以创建用户 from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """

我需要在我的应用程序中仅使用
电子邮件
密码
字段创建一个用户帐户。因此,my models.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)
我的用户模型是:

from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import ugettext_lazy as _

class User(AbstractBaseUser, PermissionsMixin):

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

    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this site.'),
    )

    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )

    objects = UserManager()
    USERNAME_FIELD = "email"

    class Meta:
        db_table = 'auth_user'
        verbose_name_plural = 'Usuarios en la plataforma'

    def __str__(self):
        return "@{}".format(self.email)
在我的设置中,我添加了:

AUTH_USER_MODEL = ‘my_app_name.User’

创建用户-
用户创建表单
预构建类

要创建用户,我使用
UserCreationForm

在这个类中使用username字段

根据上述内容,在我的forms.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 manage.py makemigrations时,我得到了这个回溯输出错误

    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

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

我找到了一个有效的解决方案

无论如何,请随时提出更好的解决方案

比如,我的不便/错误与使用
UserCreationForm
类有关,然后我继续做以下工作:

在我的类
CustomUserCreationForm
中的my forms.py是类
UserCreationForm
的子类,我使用
email
字段而不是
username
字段,覆盖/添加到
Meta
类的属性
字段。
帮帮我

我的班级
CustomUserCreationForm
停留如下:

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = get_user_model()
        fields = ('email',)
然后,我继续执行迁移:

[1] % python manage.py makemigrations accounts 
SystemCheckError: System check identified some issues:

ERRORS:
<class 'accounts.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.User'.
通过这种方式,我执行迁移

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 ...
而且我的用户名字段仍然保留在我的自定义用户模式中,只是这不是必需的,当我从继承自
UserCreationForm
UserCreateForm
类中创建用户时,我可以创建一个仅使用电子邮件和密码的用户帐户

我不知道这是否是解决这一不便的最好办法。
请随时提出改进建议

我找到了一个有效的解决方案

无论如何,请随时提出更好的解决方案

比如,我的不便/错误与使用
UserCreationForm
类有关,然后我继续做以下工作:

在我的类
CustomUserCreationForm
中的my forms.py是类
UserCreationForm
的子类,我使用
email
字段而不是
username
字段,覆盖/添加到
Meta
类的属性
字段。
帮帮我

我的班级
CustomUserCreationForm
停留如下:

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = get_user_model()
        fields = ('email',)
然后,我继续执行迁移:

[1] % python manage.py makemigrations accounts 
SystemCheckError: System check identified some issues:

ERRORS:
<class 'accounts.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.User'.
通过这种方式,我执行迁移

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 ...
而且我的用户名字段仍然保留在我的自定义用户模式中,只是这不是必需的,当我从继承自
UserCreationForm
UserCreateForm
类中创建用户时,我可以创建一个仅使用电子邮件和密码的用户帐户

我不知道这是否是解决这一不便的最好办法。
请随时提出改进建议

@Alasdair我已经输入了整个追踪。谢谢你@阿拉斯代尔,我已经输入了整个追踪。谢谢你!