用自定义字段扩展User模型(与Django的身份验证应用程序绑定)的最佳方法是什么?我还可能想使用电子邮件作为用户名(用于身份验证)。
我已经看到了一些方法,但不能决定哪一个是最好的。
用自定义字段扩展User模型(与Django的身份验证应用程序绑定)的最佳方法是什么?我还可能想使用电子邮件作为用户名(用于身份验证)。
我已经看到了一些方法,但不能决定哪一个是最好的。
当前回答
下面是另一种扩展User的方法。 我觉得它比上面两种方法更清晰,简单,易读。
http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
使用上述方法:
你不需要使用 user.get_profile()。Newattribute访问额外的信息 与用户相关 你可以直接访问 通过 user.newattribute
其他回答
现在已经太迟了,但我的答案是给那些用最新版本的Django寻找解决方案的人的。
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
extra_Field_1 = models.CharField(max_length=25, blank=True)
extra_Field_2 = models.CharField(max_length=25, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
你可以在这样的模板中使用它:
<h2>{{ user.get_full_name }}</h2>
<ul>
<li>Username: {{ user.username }}</li>
<li>Location: {{ user.profile.extra_Field_1 }}</li>
<li>Birth Date: {{ user.profile.extra_Field_2 }}</li>
</ul>
在views.py中是这样的:
def update_profile(request, user_id):
user = User.objects.get(pk=user_id)
user.profile.extra_Field_1 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...'
user.save()
自2008年以来已经过去了一段时间,是时候给出一些新的答案了。从Django 1.5开始,你将能够创建自定义User类。实际上,在我写这个的时候,它已经合并到master中了,所以你可以试试。
在文档中有一些关于它的信息,如果你想深入了解,在这个提交中。
您所要做的就是将AUTH_USER_MODEL添加到具有自定义用户类路径的设置中,它扩展了AbstractBaseUser(更可定制的版本)或AbstractUser(或多或少可以扩展的旧用户类)。
对于那些懒得点击的人,这里有一个代码示例(摘自docs):
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=MyUserManager.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
u = self.create_user(username,
password=password,
date_of_birth=date_of_birth
)
u.is_admin = True
u.save(using=self._db)
return u
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
像Pro一样扩展Django用户模型(UserProfile)
我发现这个非常有用:link
摘录:
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department
在这里,我试图解释如何用额外的字段来扩展Django的Default用户模型 很简单,就这么做。
Django允许使用AbstractUser扩展默认的用户模型
注意:-首先创建一个额外的字段模型,你想添加到用户模型,然后运行命令python manage.py makemigrations和python manage.py migrate
首先运行——> python manage.py makemigrationthen
第二步运行python manage.py migrate
步骤:-创建一个带有额外字段的模型,你想在Django默认用户模型中添加这些字段(在我的例子中,我创建了CustomUser
model.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
mobile_no = models.IntegerField(blank=True,null=True)
date_of_birth = models.DateField(blank=True,null=True)
在settings.py中添加你创建的模型名称,在我的例子中CustomUser是用户模型。在settings .py中注册,使其成为默认用户模型,
#settings.py
AUTH_USER_MODEL = 'myapp.CustomUser'
最后在admin.py中注册CustomUser模型 # admin.py
@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
list_display = ("username","first_name","last_name","email","date_of_birth", "mobile_no")
然后执行命令python manage.py makemigrations
然后python manage.py migrate
然后python manage.py createsuperuser
现在你可以看到你的模型默认用户模型扩展了(mobile_no,date_of_birth)
注意:这个答案是不赞成的。如果你使用的是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
更新:请注意AUTH_PROFILE_MODULE自v1.5起已弃用:https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module