您的位置:首页 > 编程语言 > Go语言

Django 中如何给 User 增加额外的 Profile 信息

2007-03-05 03:18 253 查看
摘要:http://www.b-list.org/weblog/2006/06/06/django-tips-extending-user-model

这里的做法是定义一个独立的模型及独立的数据表来表示 profile.

1. 首先添加一个 model 来专门定义 profile:

from django.db import models
from django.contrib.auth.models import User
     
class UserProfile(models.Model):
    url = models.URLField()
    home_address = models.TextField()
    phone_numer = models.PhoneNumberField()
    user = models.ForeignKey(User, unique=True)

(注意上面代码里用 ForeignKey 搭配 unique=True 的设置,取代了老的做法 OneToOneField)

2. 然后在 settings.py 里面设置一下,让 Django 的框架知道你定义了这个模型作为 profile:

AUTH_PROFILE_MODULE = 'myapp.UserProfile'

这一步需要特别当心,只需要写 appname.ModelName 即可。如果写多了,则可能出现 "too many values to unpack" 的错误。

3. 当然还需要执行一下同步数据库操作:

python manage.py syncdb
4. 现在可以利用内建的 User 模型的 get_profile 方法获取到对应的 Profile 对象:

from django.contrib.auth.models import User
u = User.objects.get(pk=1) # Get the first user in the system
user_address = u.get_profile().home_address
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息