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

我已经看到了一些方法,但不能决定哪一个是最好的。


当前回答

现在已经太迟了,但我的答案是给那些用最新版本的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()

其他回答

试试这个:

创建一个名为Profile的模型,并使用OneToOneField引用用户,并提供一个related_name选项。

models.py

from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    try:
        if created:
            Profile.objects.create(user=instance).save()
    except Exception as err:
        print('Error creating user profile!')

现在要使用User对象直接访问配置文件,可以使用related_name。

views.py

from django.http import HttpResponse

def home(request):
    profile = f'profile of {request.user.user_profile}'
    return HttpResponse(profile)

最简单也是django推荐的方法是通过一个OneToOneField(User)属性。

扩展现有的User模型 … 如果您希望存储与User相关的信息,您可以使用与包含附加信息字段的模型的一对一关系。这种一对一的模型通常称为概要文件模型,因为它可能存储有关站点用户的非身份验证相关信息。

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

替换自定义用户模型 有些类型的项目可能有身份验证要求,而Django内置的User模型并不总是合适的。例如,在一些网站上,使用电子邮件地址代替用户名更有意义。 [Ed:两个警告和一个通知,提到这是相当激烈的。]

我绝对不会去修改Django源代码树中的User类,也不会复制和修改认证模块。

你可以通过每次使用Django post save信号创建用户时创建一个新条目来扩展用户配置文件

models.py

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)

这将在创建新用户时自动创建一个雇员实例。

如果你想扩展用户模型,并在创建用户时添加更多信息,你可以使用django-betterforms (http://django-betterforms.readthedocs.io/en/latest/multiform.html)。这将创建一个包含UserProfile模型中定义的所有字段的用户添加表单。

models.py

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)

forms.py

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,
    }

views.py

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)

addUser.html

<!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>

urls . py

from django.conf.urls import url, include
from appName.views import *
urlpatterns = [
    url(r'^add-user/$', AddUser.as_view(), name='add-user'),
]

注意:这个答案是不赞成的。如果你使用的是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

自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