我在用户admin中有一个用户列表,该用户列表中有一个名为domain(email-domain)的列,现在,当一个用户使用其邮件ID登录时,他应该只能看到其域的用户,而不能看到其他域的用户。例如,如果sourabh@gmail.com登录,则仅gmail用户应该可见。
admin.py
from .models import User
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
class UserAdmin(BaseUserAdmin):
list_display = ('email', 'domain','admin', 'is_active', 'is_staff')
list_filter = ('admin', 'is_staff', 'is_active', 'groups', 'domain')
fieldsets = (
(None, {'fields': ('email', 'password', 'domain')}),
('Permissions',{ 'fields': (
'is_active',
'is_staff',
'is_superuser',
)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
models.py
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
from django.db import models
class MyUserManager(BaseUserManager):
def _create_user(self, email, password, domain, is_staff, is_superuser, **extra_fields):
if not email:
raise ValueError('Users must have an email address')
email = self.normalize_email(email)
user = self.model(
email=email,
domain = domain,
is_staff=is_staff,
is_active=True,
is_superuser=is_superuser,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, domain, **extra_fields):
return self._create_user(email, password, domain, False, False, **extra_fields)
def create_superuser(self, email, password, domain, **extra_fields):
user=self._create_user(email, password, domain, True, True, **extra_fields)
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=254, null=True, blank=True)
is_staff = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
domain = models.CharField(max_length=254)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
admin = models.BooleanField(default=False) # a superuser
objects = MyUserManager()
def __str__(self):
return self.email
答案 0 :(得分:0)
这实际上已在the admin documentation中明确涉及;您应该覆盖get_queryset
。
class UserAdmin(BaseUserAdmin):
...
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(domain=request.user.domain)