开发者

Cleanest way to implement multiple email system in django?

Hey everyone, I am pretty sure this is a fairly common problem. So in order to register an account my site you开发者_运维百科 need an email address from certain school domain (like facebook). This wouldn't be that big a problem until you start integrating other apps, like django-notification and django-registration and django-socialregistration into your site where they are sending email via user.email.

I have asked my users and most of them want an 'active_email' option - that means that they can change the email to their designated gmail or whatever.

I have come up with the following solution which isn't the cleanest of all: First, I inherit from User in django.contrib.auth and call this new class MultipleEmailUser, with email=active_email and official_email=sch_email.

Then I override django.contrib.auth's UserManager to change the API slightly, And the most painful part is to change all the source code that has User.object.find() to MultipleEmailUser.find().

Can someone suggest me a cleaner way? (My biggest headache arise from other apps only permitting to send email to User.email.)


You don't need - or want - to modify the User class. Just set up a UserProfile class with a OneToOneField back to User, and set the AUTH_PROFILE_MODULE setting. See the documentation.


Rather than a true datastore attribute, you could use a property called 'email' to expose access to whatever data you want.

Basic property syntax (from the python docs):

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

In your case, you could create true datastore attributes named, for instance, auth_email and active_email. Then, the User.email property could perform some logic in its getter function, to determine which one to return (i.e. if active_email is set, return it; otherwise, return auth_email)

It's worth noting that the syntax for property has undergone some flux. As of python 2.7, it can be implemented in a more readable way, as a decorator:

class User(BaseModel):
  @property # email
  def email(self):
    if self.active_email:
      return self.active_email
    return self.auth_email
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜