有时候我们需要基于Django的User扩展自己的用户账户,可使用以下方法。
在models.py中创建账户
class Account(models.Model):
user = models.ForeignKey(User, unique=True, related_name='profile')
name = models.CharField(max_length=30,blank=True,null=True)
city = models.CharField(max_length=60,blank=True,null=True)
province = models.CharField(max_length=50,blank=True,null=True)
country = models.CharField(max_length=50,blank=True,null=True)
description = models.CharField(max_length=300,blank=True,null=True)
favorite = models.CharField(max_length=1000,blank=True,null=True)
class Meta:
ordering=['name']
其中最关键的一项为user,将其通过外键连接到User中,注意导入头文件:from django.contrib.auth.models import User,UserManager
然后,在setting.py中配置我们的profile路径:AUTH_PROFILE_MODULE = 'account.Account' account为app的名字,Account为profile的类名
最后,一个tricky的地方。在何时创建我们的profile呢?因为有时我们需要用户先创建一个user,然后再通过其他页面补充信息。此时,需要在view.py对那个页面的处理函数加入
user = request.user
try :
profile=user.get_profile()
except:
profile= Account(user=user)
profile.save()
这样,我们就可以保证用户在已创建过profile的情况下不会再重复创建,如果没有相应profile,则会自动创建