关于Django扩展用户

来源:中文版 英文版

 

django 已经内置了用户认证的一整套处理,但总不可能满足所有用户的要求,因此在许多情况下我们需要对User进行扩展。这里有一篇不错的Blog,讲得比较详细。这篇Blog是使用django提供的userprofile扩展机制,要点如下:

  1. 在settings.py中设置要使用的UserProfile Model 信息,如:

    AUTH_PROFILE_MODULE = ‘myapp.UserProfile’

    注意,后面的字符串只能有两项,第一个是app的名字,第二个是Model的名字,其它的情况会报错。

  2. UserProfile表与User之间建议使用ForeignKey,并且key为不重复,示例如下:

    class UserProfile(models.Model):
        portrait = models.ImageField(upload_to=’photo’, blank=True)
        user = models.ForeignKey(User, unique=True)

  3. 然后在使用时,先得到user,然后通过user提供的get_profile()来得到profile对象,如:

    user.get_profile().portrait

使用get_profile的好处是移植更方便,而且在User中对get_profile的调用可以有cache处理。原本我想到是否这样当我修改了profile信息之后,是不是会有不同步的问题出现呢(因为我查了User的代码,没有cache取消的处理)。因此还在django邮件列表中发了一封邮件。不过后来想想,当一个view处理时,是不会修改profile的。但修改了profile,再得到User时应该是一个新的对象。而User的cache的处理是放在User对象的属性中,一旦产生新的User对象,原cache就无效了。因此使用cache应该没有太大的问题,而且因为get_profile()是一个方法,因此使用cache才更象以前的OneToOne的关系方式。

不过在get_profile中我并没有看到如何创建这个profile的过程,Blog中也没有讲。在我的处理中我是当用户访问与User相关的链接时,会自动判断是否存在profile信息,如果没有就创建。原来是写为decorator的,这样需要放置的地方比较多,感觉麻烦,后来在新开发的Url Filter Middleware之上,与用户权限检查合并在了一起,这样就可以不用考虑decorator了。方便多了。对应的filter函数为:

from django.contrib.auth.models import User
from utils.common import render_template
from apps.users.models import UserProfile

def check_valid_user(request, user_id):
    if request.user.is_anonymous():
        return render_template(request, ‘users/user_login.html’, {’next’:'%s’ % request.path})
    try:
        person = User.objects.get(pk=int(user_id))
    except User.DoesNotExist:
        return render_template(request, ‘error.html’, {’message’:_("User ID (%s) is not existed!") % user_id})
    try:
        profile = person.get_profile()
    except:
        #if there is no profile record existed, then create a new record first
        profile = UserProfile(user=person)
        profile.save()
    if person.id != request.user.id:
        return render_template(request, ‘error.html’, {’message’:_(‘You have no right to view the page!’)})

posted @ 2013-10-09 09:51  枫桦宁  阅读(441)  评论(0编辑  收藏  举报