views:

254

answers:

1

I'm integrating MongoDB using MongoEngine. It provides auth and session support that a standard pymongo setup would lack.

In regular django auth, it's considered bad practice to extend the User model since there's no guarantee it will be used correctly everywhere. Is this the case with mongoengine.django.auth?

If it is considered bad practice, what is the best way to attach a separate user profile? Django has mechanisms for specifying an AUTH_PROFILE_MODULE. Is this supported in MongoEngine as well, or should I be manually doing the lookup?

A: 

We just extended the User class.

class User(MongoEngineUser):
    def __eq__(self, other):
        if type(other) is User:
            return other.id == self.id
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def create_profile(self, *args, **kwargs):
        profile = Profile(user=self, *args, **kwargs)
        return profile

    def get_profile(self):
        try:
            profile = Profile.objects.get(user=self)
        except DoesNotExist:
            profile = Profile(user=self)
            profile.save()
        return profile

    def get_str_id(self):
        return str(self.id)

    @classmethod
    def create_user(cls, username, password, email=None):
        """Create (and save) a new user with the given username, password and
email address.
"""
        now = datetime.datetime.now()

        # Normalize the address by lowercasing the domain part of the email
        # address.
        # Not sure why we'r allowing null email when its not allowed in django
        if email is not None:
            try:
                email_name, domain_part = email.strip().split('@', 1)
            except ValueError:
                pass
            else:
                email = '@'.join([email_name, domain_part.lower()])

        user = User(username=username, email=email, date_joined=now)
        user.set_password(password)
        user.save()
        return user
twinsant