Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createsuperuser didn't ask for username

Tags:

python

django

I got an error after I modified the User Model in django.

when I was going to create a super user, it didn't prompt for username, instead it skipped it, anyway the object propery username still required and causing the user creation to failed.

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

it results this :

 manage.py createsuperuser
Running 'python /home/gema/A/PyProject/janet_x/janet/manage.py createsuperuser' command:
Email: [email protected]
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'

When I use the shell :

Account.objects.create(u'administer', u'[email protected]', u'password123')

it returns :

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

What could possibly be wrong ? Thank you.

like image 330
gema Avatar asked Jan 12 '17 11:01

gema


1 Answers

REQUIRED_FIELD should be REQUIRED_FIELDS (plural), otherwise you won't be prompted for a username (or any other required fields) because Django did not find anything in REQUIRED_FIELDS.

As an example, I use this UserManager in one of my projects:

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 is set to email and REQUIRED_FIELDS to ('first_name', 'last_name'). You should be able to adapt this example to fit your needs.

like image 70
voodoo-burger Avatar answered Oct 05 '22 15:10

voodoo-burger