createsuperuser没有要求用户名

时间:2017-01-12 11:57:16

标签: python django

我在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 <module>
    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'

当我使用shell时:

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

可能出现什么问题? 谢谢。

2 个答案:

答案 0 :(得分:4)

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

例如,我在我的一个项目中使用此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')。您应该能够调整此示例以满足您的需求。

答案 1 :(得分:1)

这一点没有意义:

<dependency>
    <groupId>com.typesafe.play</groupId>
    <artifactId>play-java_2.11</artifactId>
    <version>${play.version}</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>com.typesafe.play</groupId>
    <artifactId>play-cache_2.11</artifactId>
    <version>${play.version}</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>com.typesafe.play</groupId>
    <artifactId>play-json_2.11</artifactId>
    <version>${play.version}</version>
    <scope>provided</scope>
</dependency>

为什么要将private val conf = new SparkConf() .setAppName("IgniteRDDExample") .setMaster("local") .set("spark.executor.instances", "2") /** Spark context */ val sparkContext = new SparkContext(conf) /** Defines spring cache Configuration path */ private val CONFIG = "examples/config/example-shared-rdd.xml" /** Creates Ignite context with above configuration configuration */ val igniteContext = new IgniteContext(sparkContext, CONFIG, false) /** Creates an Ignite RDD of Type (Int,Int) Integer Pair */ val sharedRDD: IgniteRDD[Int, Int] = igniteContext.fromCache[Int, Int]("sharedRDD") /** Fill IgniteRDD with Int pairs */ sharedRDD.savePairs(sparkContext.parallelize(1 to 1000, 10).map(i => (i, i))) /** Transforming Pairs to contain their Squared value */ sharedRDD.mapValues(x => (x * x)) /** Retrieve sharedRDD back from the Cache */ val transformedValues: IgniteRDD[Int, Int] = igniteContext.fromCache[Int, Int]("sharedRDD") transformedValues.take(5).foreach(println) /** Performing SQL query on existing cache and * collect result into a Spark Dataframe * */ val rs = transformedValues.sql("select * from Integer where number > ? and number < ? ", 10, 100) /** Show DataFrame results */ println("The count is::::::::::: "+rs.count) 设为“电子邮件”?当然它应该是“用户名”。