Skip to content

Instantly share code, notes, and snippets.

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.


Add these lines to your settings file:

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'
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(, site_id ) = 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 )
user = UserModel.objects.get(username=identifier)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
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.