Django Rest-framework:无法创建带有个人资料图片的用户

我正在通过用类扩展类来编写创建用户API。API 对于常规(如 、 、 .但后来我决定也存储用户。因此,我创建了一个新字段,用于将用户的个人资料图片的路径存储在同一扩展模型中。usersAbstractBaseUsermodel fieldsEmailFieldCharFieldBooleanFieldprofile_pictureprofile_pictureImageFieldusers


models.py


class 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.py


from django.shortcuts import render

from . import views

from rest_framework.views import APIView

from django.db import IntegrityError

from rest_framework import status

from . import models, serializers

from rest_framework.response import Response

from django.core.mail import send_mail

from rest_framework.parsers import FileUploadParser




class 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

                })



有只小跳蛙
浏览 76回答 1
1回答

慕村225694

不是发送数据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']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python