在 django Rest 框架中执行 CRUD API Rest,我创建了基于类的视图。但是当我在浏览器中运行我的应用程序时,我没有收到用于发布数据的表单。当我向下滚动时获取媒体类型和内容选项而不是我的模型字段。
这是我的模型:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from djongo import models as djongo_models
from bson.objectid import ObjectId
from django.contrib.auth.hashers import make_password, check_password
from django.core.validators import RegexValidator
from api.enums import Status, UserRole
class UserManager(BaseUserManager):
def create_user(self, username, email, password=None, **extra_fields):
if not email:
raise ValueError('The email is required')
email = self.normalize_email(email)
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('role', UserRole.ADMIN)
return self.create_user(username, email, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
mongo_id = djongo_models.ObjectIdField()
def save(self, *args, **kwargs):
if not self.mongo_id:
self.mongo_id = ObjectId()
super().save(*args, **kwargs)
username = models.CharField(max_length=20, blank=False)
name = models.CharField(max_length=20, blank=False, default='')
lastname = models.CharField(max_length=20, blank=False, default='')
password = models.CharField(max_length=128, blank=False,)
def set_password(self, raw_password):
self.password = make_password(raw_password)
def check_password(self, raw_password):
return check_password(raw_password, self.password)
phone_number = RegexValidator(regex=r'^\+\d{1,3}\s\d{6, 14}$', message='Insert a valid phone number and it\'s country code')
email = models.EmailField(unique=True, blank=False)
birth_date = models.DateField(null=True)
role = models.CharField(max_length=10, choices=[(role, role.value) for role in UserRole],)
status = models.CharField(max_length=20, choices=[(tag, tag.value) for tag in Status])
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(default=None)
deleted = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'phone_number', 'birth_date', 'role', 'status']
objects = UserManager()
def __str__(self):
return self.email
序列化器.py
from rest_framework import serializers
from api.models import User
from rest_framework_simplejwt.tokens import RefreshToken
class UserRegistrationsSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = (
'username',
'email',
'password',
'phone_number',
'birth_date',
'role',
'status',
)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
name=validated_data['name'],
lastname=validated_data['lastname'],
phone_number=validated_data['phone_number'],
birth_date=validated_data['birth_date'],
role=validated_data['role'],
status=validated_data['status'],
)
user.set_password(validated_data['password'])
user.save()
return user
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'name',
'lastname',
'password',
'phone_number',
'email',
'birth_date',
'role',
'status',
)
read_only_fields = (
'id',
'mongo_id',
'created_at',
'updated_at',
'deleted'
)
def get_token(self, obj):
refresh = RefreshToken.for_user(obj)
token = {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
return token
和views.py:
from django.http.response import JsonResponse
from rest_framework import status
from django.contrib.auth import authenticate
from api.models import User
from api.serializers import UserSerializer, UserRegistrationsSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
class UserRegister(APIView):
def post(self, request):
serializer = UserRegistrationsSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
serializer = UserSerializer(user)
return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserLogin(APIView):
def post(self, request):
email_or_username = request.data.get('email_or_username')
password = request.data.get('password')
user = authenticate(request, email=email_or_username, password=password)
if not user is None:
serializer = UserSerializer(user)
return JsonResponse(serializer.data, status=status.HTTP_200_OK)
return JsonResponse({'Detail': 'Invalid Credentials'}, status=status.HTTP_401_UNAUTHORIZED)
class UserList(ListAPIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
users = User.objects.all()
users_serializer = UserSerializer(users, many=True)
return JsonResponse(users_serializer.data, status=status.HTTP_200_OK)
class UserDetail(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def get_object(self, pk):
try:
return User.objects.get(pk=pk)
except User.DoesNotExist:
return JsonResponse({'message': 'The User does not exists'}, status=status.HTTP_404_NOT_FOUND)
def get(self, request, pk, format=None):
user = self.get_object(pk)
serializer = UserSerializer(user)
return JsonResponse(serializer.data)
def put(self, request, pk, format=None):
user = self.get_object(pk)
serializer = UserSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
user = self.get_object(pk)
user.deleted = True
user.save()
return JsonResponse(status=status.HTTP_204_NO_CONTENT)
class DeletedUsers(ListAPIView):
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]
authentication_classes = [JWTAuthentication]
queryset = User.objects.filter(deleted=True)
当我去帖子请求用户注册时:
浏览器中的内容部分实际上是您的请求正文。但是如果你想使用 HTML 表单插入数据,你需要来自 Rest Framework generics 模块的通用视图,而不是简单的 APIView。