用Django REST framework 写一个注册功能
时间: 2024-02-20 20:58:38 浏览: 125
web开发注册功能
好的,以下是用 Django REST framework 写一个注册功能的步骤:
1. 创建一个 Django 项目和应用
```
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
```
2. 安装 Django REST framework
```
pip install djangorestframework
```
3. 修改 settings.py 文件
```
INSTALLED_APPS = [
...
'rest_framework',
'myapp',
]
...
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
}
```
4. 创建用户模型
```
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
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_staff(self):
return self.is_admin
```
5. 创建用户序列化器
```
from rest_framework import serializers
from myapp.models import User
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('email', 'password')
def create(self, validated_data):
user = User.objects.create_user(
email=validated_data['email'],
password=validated_data['password'],
)
return user
```
6. 创建注册视图
```
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from myapp.serializers import UserSerializer
class RegisterView(generics.CreateAPIView):
serializer_class = UserSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
```
7. 添加 url
```
from django.urls import path
from myapp.views import RegisterView
urlpatterns = [
path('register/', RegisterView.as_view()),
]
```
现在我们可以使用 POST 请求访问 `/register/`,发送 email 和 password 参数即可注册用户并返回一个 Token。
阅读全文