【问题标题】:Relationship errors when creating Django Custom User Model创建 Django 自定义用户模型时的关系错误
【发布时间】:2014-01-08 10:12:27
【问题描述】:

我一直关注this guide 在 Django 中创建自定义用户模型。我是 Django 框架的新手,在尝试执行第八步时遇到了一系列四个错误,其中south 用于构建迁移。

错误是:

auth.user: Accessor for m2m field 'groups' clashes with related m2m field 'Group.user_set'. Add a related_name argument to the definition for 'groups'.
auth.user: Accessor for m2m field 'user_permissions' clashes with related m2m field 'Permission.user_set'. Add a related_name argument to the definition for 'user_permissions'.
member.customuser: Accessor for m2m field 'groups' clashes with related m2m field 'Group.user_set'. Add a related_name argument to the definition for 'groups'.
member.customuser: Accessor for m2m field 'user_permissions' clashes with related m2m field 'Permission.user_set'. Add a related_name argument to the definition for 'user_permissions'.

我了解多对多关系问题,我认为这是由PermissionsMixin 引起的。不过,我对此不是 100% 确定的。

这是我的自定义模型:

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

    is_staff = models.BooleanField(_('staff status'), default=False, 
                                   help_text=_('Designates whether the user can log into this admin site'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))

    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        return self.first_name

    def email_user(self, subject, message, from_email=None):
        send_mail(subject, message, from_email, [self.email])

还有自定义用户管理器:

class CustomUserManager(BaseUserManager):
    def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
        now = timezone.now()

        if not email:
            raise ValueError('The given email must be set')

        email = self.normalize_email(email)
        user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        return self._create_user(email, password, False, False, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password, True, True, **extra_fields)

Models.py 进口:

from django.db import models
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

我还创建了自定义表单和自定义管理位,就像教程一样,但不要相信它们与这个问题有关。不过,如果需要,我很乐意将它们包括在内。

Pip freeze:

pip freeze
Django==1.6.1
South==0.8.4
argparse==1.2.1
coverage==3.7.1
distribute==0.6.24
django-form-utils==1.0.1
djangorestframework==2.3.10
psycopg2==2.5.1
wsgiref==0.1.2

Settings.py:

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

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework.authtoken',
    'rest_framework',
    'south',
    'log_api',
    'member',
)

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 = 'server_observer.urls'

WSGI_APPLICATION = 'server_observer.wsgi.application'

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

LANGUAGE_CODE = 'en-GB'

TIME_ZONE = 'Europe/London'

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_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

# Where to look for templates

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, "templates"),
)

# Custom user model

#AUTH_USER_MODEL = 'member.CustomUser'
AUTH_USER_MODEL = 'auth.User'

# 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 = ''

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

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'server_observer',
        'USER': '',
        'PASSWORD': '',
        'HOST': '127.0.0.1'
    }
}

我也尝试将AUTH_USER_MODEL = 'member.CustomUser' 设置为AUTH_USER_MODEL = 'auth.User'

我被困住了,昨晚已经花了很长时间。对于任何建议,我将不胜感激。

【问题讨论】:

  • 我想说 AUTH_USER_MODEL 是这里的问题,它绝对应该指向您的 CustomUser,这应该会阻止 auth.User 被创建。
  • 我有一个在生产环境中运行的 API,所以理想情况下我希望能够迁移到新的用户模型而不丢失任何记录。
  • API 使用外键将自己与每个用户相关联。有没有办法将所有这些迁移到新的用户模型?如果我必须放弃它,这不是世界末日,但我不想这样做。
  • 不确定您的 cmets 与我的回复有什么关系。作为您链接到状态的迁移文档,只要您的外键指向 AUTH_USER_MODEL,就可以了。
  • @DanielGroves 这完全是另一个问题:)。恕我直言,您有一些选项,例如转储用户表并将其重新加载到新表中,或者尝试使用 South 进行一些粗略的操作(创建一个与默认 auth.User 具有相同字段的用户,迁移,更改字段,再次迁移...... )。我会使用转储/重新加载方法:)

标签: python django django-models


【解决方案1】:

您必须在您的 settings.py 中声明 AUTH_USER_MODEL。在你的情况下:

AUTH_USER_MODEL = 'member.customuser'

【讨论】:

    猜你喜欢
    • 2019-10-17
    • 2020-08-22
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2019-01-12
    • 2021-07-12
    • 2013-01-29
    • 2017-10-27
    相关资源
    最近更新 更多