gpt4 book ai didi

python - Django 1.7 多站点用户模型

转载 作者:太空狗 更新时间:2023-10-29 21:37:06 26 4
gpt4 key购买 nike

我想为一个 Django 应用程序提供服务,该应用程序通过单个数据库但不同的用户集为多个网站提供服务。想像一个博客应用程序,它将被多个具有不同主题的域使用,但通过向模型添加站点字段来使用相同的数据库。

我使用 Django's SitesFramework为了那份工作。但问题是,我无法为不同站点分离用户模型。我想使用具有每个站点唯一的站点字段和电子邮件字段的相同用户模型。

我尝试像那样扩展 AbstractUser 模型:

from django.contrib.auth.models import AbstractUser
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager

class Member(AbstractUser):
username = None
site = models.ForeignKey(Site)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

on_site = CurrentSiteManager()

class Meta:
unique_together = ('site', 'email')

但出现错误:“Member.email”必须是唯一的,因为它被命名为“USERNAME_FIELD”。

该问题的最佳做法是什么?

最佳答案

我希望这种方法对你有帮助:

1) 保存前写用户名:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager

class Member(AbstractUser):
site = models.ForeignKey(Site)
on_site = CurrentSiteManager()

USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []

class Meta:
unique_together = ('site', 'email')

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=Member)
def compose_username(sender, instance, **kwargs):
instance.username = "{0}__{1}".format( instance.email, instance.site_id )

2) 然后覆盖ModelBackend在您的自定义身份验证后端:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model

class MyModelBackend(ModelBackend):

def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
site = kwargs.get('site')
identifier = "{0}__{1}".format( username, site )
try:
user = UserModel.objects.get(username=identifier)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)

3) 请记住在设置中设置您的自定义后端:

AUTH_USER_MODEL='s1.Member'
SITE_ID = 1
AUTHENTICATION_BACKENDS = ( 'MyApp.MyModule.MyModelBackend',)

4) 验证时包括站点:

>>> from s1.models import Member as M
>>> m1 = M()
>>> m1.site_id = 1
>>> m1.email = 'peter@hello.com'
>>> m1.save()
>>> m1.set_password('hi')
>>> m1.save()
>>>
>>> from django.contrib.auth import authenticate, login
>>> u=authenticate(username='peter@hello.com', password='hi', site=1)
>>> u
<Member: peter@hello.com_at_1>
>>>

关于python - Django 1.7 多站点用户模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com