在Django中使用Djoser库来构建RESTful认证接口,首先需要安装Djoser和Django REST framework:
pip install djoser django-rest-framework
接下来,在你的settings.py
中添加djoser
和rest_framework
到INSTALLED_APPS
:
INSTALLED_APPS = [
# ...
'djoser',
'rest_framework',
# ...
]
然后,在urls.py
中添加Djoser的URLs:
urlpatterns = [
# ...
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.authtoken'))
# ...
]
确保你已经设置了REST_FRAMEWORK
和DJOSER
的配置,例如:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
}
DJOSER = {
'LOGIN_FIELD': 'email',
'SEND_ACTIVATION_EMAIL': False,
'SERIALIZERS': {
'user_create': 'your_app_name.serializers.UserCreateSerializer',
'user': 'your_app_name.serializers.UserCreateSerializer',
},
}
在your_app_name/serializers.py
中定义你的序列化器:
from rest_framework import serializers
from django.contrib.auth.models import User
from djoser.serializers import UserCreateSerializer
class UserCreateSerializer(UserCreateSerializer):
class Meta(UserCreateSerializer.Meta):
model = User
fields = ('id', 'username', 'email', 'password')
确保你已经创建了Token的模型,如果没有,运行以下命令:
python manage.py migrate djangorestframework.authtoken
现在,你已经配置了Djoser来使用RESTful认证接口。你可以通过发送HTTP请求到/auth/
来使用这些接口,例如注册、登录等。