Django管理员和普通用户分离登录
时间: 2023-06-11 20:06:23 浏览: 199
管理员和普通用户的登录系统
在Django中,可以通过创建两个不同的用户模型来实现管理员和普通用户分离登录。一种常见的方法是使用Django自带的`AbstractBaseUser`和`PermissionsMixin`类创建自定义用户模型,然后使用Django内置的`UserAdmin`类来管理管理员用户,而普通用户则使用自定义用户模型。
以下是一些基本步骤:
1. 创建一个`AbstractBaseUser`和`PermissionsMixin`的子类,作为自定义用户模型。例如:
```python
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_superuser(self):
return self.is_staff
```
2. 在`settings.py`中修改`AUTH_USER_MODEL`设置,指向自定义用户模型:
```python
AUTH_USER_MODEL = 'myapp.CustomUser'
```
3. 创建一个自定义的管理员用户管理器,该管理器继承自`UserManager`类,并覆盖`create_superuser`方法:
```python
from django.contrib.auth.models import BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, **extra_fields)
```
4. 创建一个继承自`UserAdmin`的管理员用户管理类,该类覆盖`get_queryset`方法,以过滤出管理员用户:
```python
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext_lazy as _
from .models import CustomUser
class CustomUserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'is_staff', 'is_active']
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Permissions'), {'fields': ('is_staff', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active'),
}),
)
def get_queryset(self, request):
qs = super().get_queryset(request)
return qs.filter(is_staff=True)
```
5. 在`admin.py`中注册管理员用户管理类和自定义用户模型:
```python
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import CustomUser
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .admin import CustomUserAdmin
class CustomUserAdmin(BaseUserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'is_staff', 'is_active']
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Permissions', {'fields': ('is_staff', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active'),
}),
)
search_fields = ('email',)
ordering = ('email',)
admin.site.register(CustomUser, CustomUserAdmin)
```
6. 在需要使用普通用户登录的视图中,使用`@login_required`装饰器来限制访问,例如:
```python
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def my_view(request):
# 这里是普通用户登录后才能访问的视图逻辑
return render(request, 'my_template.html')
```
7. 在需要使用管理员登录的视图中,使用`@user_passes_test`装饰器来限制访问:
```python
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render
@user_passes_test(lambda u: u.is_staff)
def my_view(request):
# 这里是管理员登录后才能访问的视图逻辑
return render(request, 'my_template.html')
```
以上是一些基本步骤,你可以根据你的实际需求进行修改和扩展。
阅读全文