我正在通过用类扩展类来编写创建用户API。API 对于常规(如 、 、 .但后来我决定也存储用户。因此,我创建了一个新字段,用于将用户的个人资料图片的路径存储在同一扩展模型中。usersAbstractBaseUsermodel fieldsEmailFieldCharFieldBooleanFieldprofile_pictureprofile_pictureImageFieldusersmodels.pyclass Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='Images/', max_length=None, blank=True) is_active = models.BooleanField(default=True) # defing a custome user manager class for the custome user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email'然后我更新了类以添加UserAPIViewparser_classes = (FileUploadParser)view.pyfrom django.shortcuts import renderfrom . import viewsfrom rest_framework.views import APIViewfrom django.db import IntegrityErrorfrom rest_framework import statusfrom . import models, serializersfrom rest_framework.response import Responsefrom django.core.mail import send_mailfrom rest_framework.parsers import FileUploadParserclass UserAPIViews(APIView): """ """ parser_classes = (FileUploadParser) def post(self, request, format=None): """ """ print(request.data) serialized_data = serializers.UserSerializer(data=request.data) if serialized_data.is_valid(): try: user_id = serialized_data.save() except IntegrityError as error: message = f"Email already exist." return Response ({ 'error_message' : message, 'status' : status.HTTP_226_IM_USED })
1 回答
慕村225694
TA贡献1880条经验 获得超4个赞
不是发送数据json对象,而是将数据作为表单对象发送,如果你选择将数据作为表单对象发送,那么你需要提到parser_classes = [FileUploadParser,FormParser,MultiPartParser]
以下是帮助定义表单数据的链接。Postman 请求与正文表单数据到 json
class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): request = self.context.get('request') user_obj = user.User.objects.create(**validated_data)
class UserViewSet(viewsets.ModelViewSet): queryset = user.User.objects.all() serializer_class = user_details_serializer.UserSerializer # permission_classes = (AdminAccessPermission,) filter_backends = [filters.OrderingFilter, filters.SearchFilter] parser_classes = (MultiPartParser, FormParser) search_fields = ['id', 'username', 'email', 'first_name', 'last_name', 'phone', 'status'] ordering_fields = ['id', 'username', 'email', 'first_name', 'last_name', 'phone', 'status']
添加回答
举报
0/150
提交
取消