无法在Django中创建超级用户

时间:2019-03-07 14:37:21

标签: django django-custom-user

我想用电子邮件代替用户名登录。但是在创建超级用户时,出现以下错误

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',)

我是django的漂亮初学者,因此不知道出了什么问题。请帮忙。预先感谢。

1 个答案:

答案 0 :(得分:3)

这是因为您的CustomUser类仍在使用默认的Manager,该类定义了create_superuser方法并需要用户名(它不会检查USERNAME_FIELD的值,仅用于登录和身份验证后端。

您应使用自己的名称覆盖Manager,然后重新定义create_superuser(),如this example in the official docs所示。您还应该覆盖create_user方法。

这实际上是here