下面是Django自定义User模型、认证、权限控制的完整攻略,主要包括以下几个步骤:
- 创建自定义User模型
Django提供了一个内置的User模型,但是如果我们需要添加自定义的字段或属性,就需要创建自定义的User模型。具体操作步骤:
- 在models.py中定义自定义的User模型,在其中继承AbstractBaseUser类:
```python
from django.contrib.auth.models import AbstractBaseUser
class CustomUser(AbstractBaseUser):
# 定义自定义的字段或属性
...
```
- 在settings.py中配置自定义User模型:
python
AUTH_USER_MODEL = 'myapp.CustomUser'
- 实现用户认证系统
Django提供了多种用户认证方法,本着安全第一的原则,我们通常使用JWT认证方式。具体操作步骤:
- 安装django-rest-framework-simplejwt:
pip install djangorestframework-simplejwt
- 在settings.py中配置JWT认证方式:
python
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
- 在views.py中定义认证API:
```python
from rest_framework_simplejwt.views import TokenObtainPairView
class CustomTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
```
- 在serializers.py中定义认证API的序列化器:
```python
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
# 定义需要额外返回的字段
...
```
- 实现权限控制
Django提供了多种权限控制方式,我们通常使用基于视图的权限控制方式。具体操作步骤:
- 在views.py中定义需要权限控制的API,并添加相应的permission_class:
```python
from rest_framework.permissions import IsAuthenticated
class CustomAPIView(APIView):
permission_class = [IsAuthenticated]
...
```
- 在serializers.py中定义需要权限控制的API的序列化器,并添加相应的字段:
```python
from rest_framework import serializers
class CustomSerializer(serializers.ModelSerializer):
# 定义需要返回的字段
...
class Meta:
model = CustomModel
fields = ['id', 'name', 'description', 'is_public']
read_only_fields = ['id', 'is_public']
extra_kwargs = {'name': {'required': True}}
```
示例:
- 示例1:创建自定义User模型和认证API
```python
# models.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
class CustomUserManager(BaseUserManager):
def create_user(self, email, password):
if not email:
raise ValueError("Users must have an email address")
user = self.model(email=email, is_active=True, last_login=timezone.now())
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def get_full_name(self):
return self.first_name + " " + self.last_name
def get_short_name(self):
return self.first_name
# serializers.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
token['first_name'] = user.first_name
token['last_name'] = user.last_name
return token
# views.py
from rest_framework_simplejwt.views import TokenObtainPairView
class CustomTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
```
- 示例2:实现基于视图的权限控制
```python
# views.py
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
class CustomAPIView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
response_data = {"message": "Hello, world!"}
return Response(response_data)
```
以上就是Django自定义User模型、认证和权限控制的完整攻略,希望能对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Django自定义User模型、认证、权限控制的操作 - Python技术站