Search code examples
djangodjango-modelsmongoenginedjango-socialauth

How to inherit mongoengine.django.auth.User for Custom User Model?


I am pretty new with django. I am using django, mongoengine, django-social-auth to build authentication system and to store user profile in mongodb.

I am in process of using 'Custom User Model' mechanism provided by django as follows:

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

class UserProfile(User):

    imageUrl = URLField()

    def __init__(self):
        User.__init__()

settings.py include ('users' is app name):

SOCIAL_AUTH_USER_MODEL = 'users.UserProfile'

When I execute 'python manage.py runserver', got following error:

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

When I change my UserProfile class to inherit from models.Model as follows:

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__()

,running 'python manage.py runserver' started development server without an issue.

So I guess, Custom User Model must be inherited from models.Model. So how should I workaround to inherit my custom user model from mongoengine.django.auth.User.


Solution

  • From what I can see, you just create a UserProfile with one-to-one relationship to build in User model from django. So this is not true:

     SOCIAL_AUTH_USER_MODEL = 'users.UserProfile'
    

    You should create your own User model. Follow this.

    Example:

    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']