Django 在扩展用户模型并创建超级用户后无法登录

3

在之前的问题中,我得到了帮助,成功创建了扩展用户。

我执行了syncdb并创建了第一个超级用户,但现在无法登录。出现错误信息:“请输入员工账户的正确用户名和密码。请注意,两个字段都可能区分大小写。” 我在SO上找到了一些类似的问题,但要么没有答案,要么即使有答案,我也无法解决我的问题。

以下是我的最新代码: models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from epi.managers import EmployeeManager
# Create your models here.

class Employee(AbstractUser):
    emp_id = models.IntegerField('Employee Id', max_length=5,unique=True)
    dob = models.DateField('Date of Birth', null=True,blank=True)

    REQUIRED_FIELDS = ['email', 'emp_id']
    objects = EmployeeManager()

    def __unicode__(self):
        return self.get_full_name


class Department(models.Model):
    name = models.CharField('Department Name',max_length=30, unique=True,default=0)
    def __unicode__(self):
        return self.name


class Report(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    dept = models.ForeignKey(Department, verbose_name="Department")
    report1 = models.ForeignKey(Employee,null=True,blank=True, verbose_name=u'Primary Supervisor',related_name='Primary')
    report2 = models.ForeignKey(Employee,null=True,blank=True, verbose_name=u'Secondary Supervisor',related_name='Secondary')

    def __unicode__(self):
        return self.user

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from epi.models import Employee
from django import forms
from django.contrib.auth.models import Group


class EmployeeChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = Employee


class EmployeeCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = Employee

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            Employee.objects.get(username=username)
        except Employee.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])


class EmployeeAdmin(UserAdmin):
    form = EmployeeChangeForm
    add_form = EmployeeCreationForm
    fieldsets = UserAdmin.fieldsets + (
        (None, {'fields': ('emp_id', 'dob',)}),
    )

admin.site.register(Employee, EmployeeAdmin)
admin.site.unregister(Group)

managers.py

from django.contrib.auth.models import BaseUserManager


class EmployeeManager(BaseUserManager):
    def create_user(self, username,  email,emp_id,  password=None):
        if not username:
            raise ValueError('Employee must have an username.')
        if not email:
            raise ValueError('Employee must have an email address.')
        if not emp_id:
            raise ValueError('Employee must have an employee id')
        user = self.model(username=username, email=self.normalize_email(email), emp_id=emp_id)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username,  email, emp_id, password):
        user = self.create_user(username,  email, emp_id, password)
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

settings.py

"""
Django settings for employee project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$@k3%w-f3jbj(y6_fh+me+_)8&z%lt%4u(nyu^xdrn9=%&_!bl'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'grappelli',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'epi',
    'south',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'employee.urls'

WSGI_APPLICATION = 'employee.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'employee.db'),
       }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.FileSystemFinder',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.request",
    "django.core.context_processors.static",
    "django.core.context_processors.media",
)

TEMPLATE_DIRS = (
    BASE_DIR + '/templates',)

STATICFILES_DIRS = (
    ('assets', 'F:/djangoenv/testenv1/employee/static'),
      )

AUTH_USER_MODEL = 'epi.Employee'

GRAPPELLI_ADMIN_TITLE = 'MyAdmin'

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

MEDIA_ROOT = BASE_DIR + '/media/'

MEDIA_URL = '/media/'

1
我觉得你可能漏掉了一些要求(USERNAME_FIELD)。 根据Django文档: https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#django.contrib.auth.models.CustomUser - petkostas
1
谢谢您提供的参考,但我意识到我的managers.py缺少is_staff = True。对于我的错误,我深表歉意。我查询了数据库并发现is_staff被设置为0,现在我将其更改为1,现在我能够登录了。 - just10minutes
1个回答

1

managers.py缺少一个条件is_staff = True,因此在数据库中保存为False,所以我无法登录到管理网站。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接