如何为自定义用户模型继承mongoengine.django.auth.User?

时间:2013-06-15 11:45:59

标签: django django-models mongoengine django-socialauth

我对django很新。我正在使用django,mongoengine,django-social-auth来构建身份验证系统并在mongodb中存储用户配置文件。

我正在使用django提供的“自定义用户模型”机制,如下所示:

from mongoengine import *
from mongoengine.django.auth import User

class UserProfile(User):

    imageUrl = URLField()

    def __init__(self):
        User.__init__()

settings.py include('users'是应用名称):

SOCIAL_AUTH_USER_MODEL = 'users.UserProfile'

当我执行'python manage.py runserver'时,出现以下错误:

social_auth.usersocialauth: 'user' has a relation with model users.UserProfile, which has either not been installed or is abstract.

当我将UserProfile类更改为继承models.Model时,如下所示:

from mongoengine import *
from mongoengine.django.auth import User
from django.db import models

class UserProfile(models.Model):

    imageUrl = URLField()

    def __init__(self):
        User.__init__()

,运行'python manage.py runserver'启动开发服务器没有问题。

所以我想,自定义用户模型必须继承自models.Model。那么我应该如何解决从mongoengine.django.auth.User继承我的自定义用户模型。

1 个答案:

答案 0 :(得分:1)

从我所看到的,您只需创建一个具有一对一关系的UserProfile,即可在django中构建用户模型。所以这不是真的:

 SOCIAL_AUTH_USER_MODEL = 'users.UserProfile'

您应该创建自己的用户模型。关注this

示例:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin

class User(AbstractBaseUser, PermissionsMixin):

    username = models.CharField(unique=True, max_length=45, db_index=True)
    first_name = models.CharField(max_length=45)
    last_name = models.CharField(max_length=45)
    email = models.EmailField(unique=True)
    status = models.SmallIntegerField()
    activation_code = models.CharField(max_length=50, null=True, blank=True)
    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)
    login_at = models.DateTimeField()

    def __unicode__(self):
        return self.username

    def get_fullname(self):
        return '%s %s' % (self.first_name, self.last_name)

    def get_shortname(self):
        return self.first_name

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']