Courtney
Courtney

Reputation: 339

Python create_user error

I am getting an error ValueError: Users must have a valid username when trying to invoke the create_superuser command from the command line using Django 1.7.1. I am following a tutorial that creates a custom User model with the email field as the USERNAME_FIELD. It doesn't prompt me for a username and I have tried passing the username as an option with python manage.py createsuperuser --username=someusername and python manage.py createsuperuser username=someusername. Snippets of my code are below.

models.py

# Create your models here.
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from django.contrib.auth.models import BaseUserManager

class AccountManager(BaseUserManager):
    def create_user(self, email, password=None, **kwargs):
        if not email:
            raise ValueError('Users must have a valid email address.')

        if not kwargs.get('username'):
            raise ValueError('Users must have a valid 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, email, password, **kwargs):
        account = self.create_user(email, password, **kwargs)

        account.is_admin = True
        account.save()

        return account

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

    first_name = models.CharField(max_length=40, unique=True)
    last_name = models.CharField(max_length=40, unique=True)
    tagline = models.CharField(max_length=140, unique=True)

    is_admin = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    objects = AccountManager()

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

    def __unicode__(self):
        return self.email

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

    def get_short_name(self):
        return self.first_name

In the settings.py file, I have added authentication to the list of installed apps and I have defined AUTH_USER_MODEL as authentication.Account

Upvotes: 0

Views: 875

Answers (1)

user2390182
user2390182

Reputation: 73450

Set REQUIRED_FIELDS instead of REQUIRED_FIELD. This is a list of field names that createsuperuser will prompt for. It must contain all fields of your custom user model that are non-nullable/non-blankable, so in your case you might want to include first_name, last_name, and tagline as well.

This is well-documented.

Upvotes: 1

Related Questions