Far*_*nha 415 django django-models django-authentication django-users
使用自定义字段扩展User模型(与Django的身份验证应用程序捆绑在一起)的最佳方法是什么?我也可能希望使用该电子邮件作为用户名(用于身份验证).
Rya*_*eld 238
最痛苦的,实际上Django推荐的方法是通过一个OneToOneField(User)属性.
扩展现有的用户模型
...
如果要存储与之相关的信息
User,可以使用与包含字段的模型的一对一关系以获取其他信息.这种一对一模型通常称为配置文件模型,因为它可能存储有关站点用户的非身份验证相关信息.
也就是说,扩展django.contrib.auth.models.User和取代它也有效......
替换自定义用户模型
某些类型的项目可能具有Django的内置
User模型并不总是适合的认证要求.例如,在某些网站上,使用电子邮件地址作为识别令牌而不是用户名更有意义.[编辑:两个警告和通知随后,提到这是非常激烈的.]
我肯定会远离更改Django源代码树中的实际User类和/或复制和更改auth模块.
Rai*_*ins 223
注意:此答案已弃用.如果您使用的是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'
Run Code Online (Sandbox Code Playgroud)
每次创建用户时,这将创建一个userprofile.然后你可以使用
user.get_profile().whatever
Run Code Online (Sandbox Code Playgroud)
以下是来自文档的更多信息
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
Ond*_*ták 190
好吧,自2008年以来已经过了一段时间,现在是时候回答一些问题了.从Django 1.5开始,您将能够创建自定义User类.实际上,在我写这篇文章时,它已经合并为master,所以你可以尝试一下.
在文档中有关于它的一些信息,或者如果你想深入研究它,在这个提交中.
您所要做的就是添加AUTH_USER_MODEL具有自定义用户类路径的设置,该路径可以扩展AbstractBaseUser(更多可自定义的版本)或AbstractUser(或多或少可以扩展的旧用户类).
对于懒惰点击的人,这里的代码示例(取自文档):
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
Run Code Online (Sandbox Code Playgroud)
Ric*_*lli 43
从Django 1.5开始,您可以轻松扩展用户模型并在数据库上保留一个表.
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
class UserProfile(AbstractUser):
age = models.PositiveIntegerField(_("age"))
Run Code Online (Sandbox Code Playgroud)
您还必须将其配置为设置文件中的当前用户类
# supposing you put it in apps/profiles/models.py
AUTH_USER_MODEL = "profiles.UserProfile"
Run Code Online (Sandbox Code Playgroud)
如果您想添加许多用户的偏好,OneToOneField选项可能是更好的选择.
开发第三方库的人员注意事项:如果您需要访问用户类,请记住人们可以更改它.使用官方助手来获得正确的课程
from django.contrib.auth import get_user_model
User = get_user_model()
Run Code Online (Sandbox Code Playgroud)
Ram*_*ttu 22
下面是另一种扩展用户的方法.我觉得它比上面两种方法更清晰,更容易,更易读.
http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
使用上述方法:
Atu*_*dav 13
您可以通过使用django post保存信号在每次创建用户时创建新条目来简单地扩展用户配置文件
from django.db.models.signals import *
from __future__ import unicode_literals
class UserProfile(models.Model):
user_name = models.OneToOneField(User, related_name='profile')
city = models.CharField(max_length=100, null=True)
def __unicode__(self): # __str__
return unicode(self.user_name)
def create_user_profile(sender, instance, created, **kwargs):
if created:
userProfile.objects.create(user_name=instance)
post_save.connect(create_user_profile, sender=User)
Run Code Online (Sandbox Code Playgroud)
这将在创建新用户时自动创建员工实例.
如果您希望扩展用户模型并希望在创建用户时添加更多信息,可以使用django-betterforms(http://django-betterforms.readthedocs.io/en/latest/multiform.html).这将创建一个用户添加表单,其中包含userProfile模型中定义的所有字段.
from django.db.models.signals import *
from __future__ import unicode_literals
class UserProfile(models.Model):
user_name = models.OneToOneField(User)
city = models.CharField(max_length=100)
def __unicode__(self): # __str__
return unicode(self.user_name)
Run Code Online (Sandbox Code Playgroud)
from django import forms
from django.forms import ModelForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm
from .models import *
class ProfileForm(ModelForm):
class Meta:
model = Employee
exclude = ('user_name',)
class addUserMultiForm(MultiModelForm):
form_classes = {
'user':UserCreationForm,
'profile':ProfileForm,
}
Run Code Online (Sandbox Code Playgroud)
from django.shortcuts import redirect
from .models import *
from .forms import *
from django.views.generic import CreateView
class AddUser(CreateView):
form_class = AddUserMultiForm
template_name = "add-user.html"
success_url = '/your-url-after-user-created'
def form_valid(self, form):
user = form['user'].save()
profile = form['profile'].save(commit=False)
profile.user_name = User.objects.get(username= user.username)
profile.save()
return redirect(self.success_url)
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="." method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Add</button>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
from django.conf.urls import url, include
from appName.views import *
urlpatterns = [
url(r'^add-user/$', AddUser.as_view(), name='add-user'),
]
Run Code Online (Sandbox Code Playgroud)
像Pro一样扩展Django用户模型(UserProfile)
我发现这非常有用:链接
提取物:
来自django.contrib.auth.models导入用户
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
Run Code Online (Sandbox Code Playgroud)
已经太晚了,但我的答案是针对那些使用最新版本的 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()
Run Code Online (Sandbox Code Playgroud)
你可以在这样的模板中使用它:
<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>
Run Code Online (Sandbox Code Playgroud)
像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()
Run Code Online (Sandbox Code Playgroud)
在 Django 3.0+ 版本中这很容易。
在models.py中
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
extra_field=models.CharField(max_length=40)
Run Code Online (Sandbox Code Playgroud)
在settings.py中
首先,注册您的新应用,然后在AUTH_PASSWORD_VALIDATORS下面 添加
AUTH_USER_MODEL ='users.CustomUser'
Run Code Online (Sandbox Code Playgroud)
最后,在admin中注册你的模型,运行makemigrations和migrate,就会成功完成。
官方文档:https : //docs.djangoproject.com/en/3.2/topics/auth/customizing/#substituting-a-custom-user-model
| 归档时间: |
|
| 查看次数: |
198681 次 |
| 最近记录: |