Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Django Multisite User Model

This code is a sample for a question on Stackoverflow about making multisite user models with Django 1.7.

Usage:

Add these lines to your settings file:

AUTH_USER_MODEL='s1.Member'
SITE_ID = 1
AUTHENTICATION_BACKENDS = ( 'MyApp.MyModule.MyModelBackend',)
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from django.conf import settings
class MemberManager(UserManager):
def create_user(self, username, **kwargs):
return super(MemberManager, self).create_user(self, username, **kwargs)
def create_superuser(self, username, **kwargs):
return super(MemberManager, self).create_superuser(self, username, **kwargs)
class Member(AbstractUser):
site = models.ForeignKey(Site, null=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
default_manager = MemberManager()
on_site = CurrentSiteManager()
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):
site_id = instance.site_id or 1
instance.username = "{0}__{1}".format( instance.email, site_id )
instance.site = Site.objects.get_current()
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', settings.SITE_ID)
identifier = "{0}__{1}".format( username, site )
try:
user = UserModel.objects.get(username=identifier)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
UserModel().set_password(password)
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.