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

来源:互联网 发布:汽车修理软件哪个好 编辑:程序博客网 时间:2024/05/02 06:10
摘要: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
= User.objects.get(pk=1# Get the first user in the system
user_address = u.get_profile().home_address
原创粉丝点击