Pritam
Pritam

Reputation: 333

Cannot create superuser in Django

I wanted to use email instead of username to login. But while creating superuser I am getting the following error

TypeError: create_superuser() missing 1 required positional argument: 'username' 

users/view.py

from django.shortcuts import render

from django.urls import reverse_lazy
from django.views import generic
from django.views.generic import TemplateView

from .forms import CustomUserCreation

class SignUp(generic.CreateView):
    form_class = CustomUserCreation
    success_url = reverse_lazy('home')
    template_name = 'signup.html'

class HomePage(TemplateView):
    template_name = 'home.html'
    def dispatch(self, request, *args, **kwargs):
        print (self.request.user)
        return super(HomePage, self).dispatch(request, *args, **kwargs)

users/models.py

#users/models.py
import sys
sys.path.insert(0,'..')

from django.db import models
from django.contrib.auth.models import AbstractUser
import questions_and_answers
from django.utils.translation import gettext as _

fields_ = questions_and_answers.fields
def apply_defaults(cls):
    for name, value in fields_.items():
        setattr(cls, name, models.CharField(default=value[1]))
    return cls

#@apply_defaults
class CustomUser(AbstractUser):
    q1 = models.CharField(max_length=200, default='0')
    q2 = models.CharField(max_length=200, default='0')
    count = models.IntegerField(default=0)
    USERNAME_FIELD = 'email'
    email = models.EmailField(_('email address'), unique=True) # changes email to unique and blank to false
    REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS

users/forms.py

class CustomUserCreation(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'email')
class CustomUserChange(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'email',)

I am pretty beginner in django, hence no idea what went wrong. Please help. Thanks in advance.

Upvotes: 0

Views: 346

Answers (1)

dirkgroten
dirkgroten

Reputation: 20702

That's because your CustomUser class is still using the default Manager, which defines the create_superuser method and requires a username (it doesn't check the value for USERNAME_FIELD, that's only used in the login and authentication backend).

You should override the Manager with your own and redefine create_superuser(), as shown in this example in the official docs. You should also override the create_user method.

This is actually described here

Upvotes: 4

Related Questions