在Django中使用自定义字段扩展用户模型

时间:2020-03-05 18:47:43  来源:igfitidea点击:

用自定义字段扩展User模型(与Django的身份验证应用程序捆绑在一起)的最佳方法是什么?我也可能希望使用电子邮件作为用户名(用于身份验证)。

我已经看到了几种方法,但是还不能确定哪种方法最好。

解决方案

回答

对于存储有关用户的其他信息,存在官方建议。
Django书还在Profiles部分讨论了这个问题。

回答

做到这一点最痛苦且确实是Django推荐的方法是通过OneToOneField(User)属性。

Extending the existing User model
  
  …
  
  If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.

也就是说,扩展django.contrib.auth.models.User并替换它也可以...

Substituting a custom User model
  
  Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.
  
  [Ed: Two warnings and a notification follow, mentioning that this is pretty drastic.]

我绝对不会在Django源代码树中更改实际的User类和/或者复制和更改auth模块。

回答

以下是扩展用户的另一种方法。
与上面两种方法相比,我觉得它更加清晰,容易,可读。

http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/

使用上面的方法:

  • 我们不需要使用user.get_profile()。newattribute来访问与用户相关的其他信息
  • 我们可以通过user.newattribute直接访问其他新属性

回答

注意:不建议使用此答案。如果我们使用的是Django 1.7或者更高版本,请参见其他答案。

这就是我的方法。

#in models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):  
    user = models.OneToOneField(User)  
    #other fields here

    def __str__(self):  
          return "%s's profile" % self.user  

def create_user_profile(sender, instance, created, **kwargs):  
    if created:  
       profile, created = UserProfile.objects.get_or_create(user=instance)  

post_save.connect(create_user_profile, sender=User) 

#in settings.py
AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile'

每当创建用户时,这将创建一个用户配置文件。
然后,我们可以使用

user.get_profile().whatever

这是来自文档的更多信息

http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

更新:请注意,自v1.5起,不建议使用" AUTH_PROFILE_MODULE":https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module