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

时间:2014-01-13 19:22:18

标签: python django

我可以借助之前question

中收到的答案创建扩展用户

我做了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 个答案:

答案 0 :(得分:1)

managers.py缺少一个条件is_staff = True所以在DB中它保存为False所以我无法登录管理站点。