当前位置:  开发笔记 > 编程语言 > 正文

createsuperuser不需要用户名

如何解决《createsuperuser不需要用户名》经验,为你挑选了1个好方法。

在django中修改用户模型后出现错误。

当我要创建一个超级用户时,它没有提示输入用户名,而是跳过了它,无论如何仍然需要对象属性用户名,并导致用户创建失败。

import jwt
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
PermissionsMixin)
from datetime import datetime, timedelta
from django.conf import settings
# from api.core.models import TimeStampedModel


class AccountManager(BaseUserManager):

    def create_user(self, username, email, password=None, **kwargs):
        if not email:
            raise ValueError('Please provide a valid email address')

        if not kwargs.get('username'):
            # username = 'what'
            raise ValueError('User must have a username')

        account = self.model(
                  email=self.normalize_email(email), username=kwargs.get('username'))

        account.set_password(password)
        account.save()

        return account

    def create_superuser(self,username, email, password, **kwargs):
        account = self.create_user(username, email, password, **kwargs)

        account.is_admin = True
        account.save()

        return account

class Account(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=40, unique=True)

    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length =40, blank=True)

    tagline = models.CharField(max_length=200, blank=True)

    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELD = ['username']


    objects = AccountManager()

    def __str__(self):
        return self.username

    @property
    def token(self):
        return generate_jwt_token()

    def generate_jwt_token(self):
        dt = datetime.now + datetime.timedelta(days=60)

        token = jwt.encode({
            'id': self.pk,
            'exp': int(dt.strftime('%s'))
            }, settings.SECRET_KEY, algorithm='HS256')
        return token.decode('utf-8')

    def get_full_name(self):
        return ' '.join(self.first_name, self.last_name)

    def get_short_name(self):
        return self.username

结果如下:

 manage.py createsuperuser
Running 'python /home/gema/A/PyProject/janet_x/janet/manage.py createsuperuser' command:
Email: admin@nister.com
Password: 
Password (again): 
Traceback (most recent call last):
  File "/home/gema/A/PyProject/janet_x/janet/manage.py", line 22, in 
    execute_from_command_line(sys.argv)
  File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'

当我使用外壳时:

Account.objects.create(u'administer', u'admin@ister.com', u'password123')

它返回:

return getattr(self.get_queryset(), name)(*args, **kwargs)
TypeError: create() takes 1 positional argument but 3 were given

有什么可能是错的吗?谢谢。



1> voodoo-burge..:

REQUIRED_FIELD应该为REQUIRED_FIELDS(复数),否则将不会提示您输入用户名(或其他任何必填字段),因为Django在中找不到任何内容REQUIRED_FIELDS

例如,我在一个项目中使用了此UserManager:

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, first_name=None, last_name=None, **extra_fields):
        if not email:
            raise ValueError('Enter an email address')
        if not first_name:
            raise ValueError('Enter a first name')
        if not last_name:
            raise ValueError('Enter a last name')
        email = self.normalize_email(email)
        user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, first_name, last_name):
        user = self.create_user(email, password=password, first_name=first_name, last_name=last_name)
        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)
        return user

USERNAME_FIELD被设置为emailREQUIRED_FIELDS('first_name', 'last_name')。您应该能够适应此示例以适合您的需求。

推荐阅读
拾味湖
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有