简体   繁体   English

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

[英]Django Rest-framework: Unable to create a user with profile picture

I am writing a create user API by extending the class users with AbstractBaseUser class.我正在通过使用AbstractBaseUser类扩展类users编写创建用户 API。 The API was working fine for regular model fields like EmailField , CharField , BooleanField .该 API 对于常规model fieldsEmailFieldCharFieldBooleanField )工作正常。 But then I decided to store the profile_picture of users as well.但后来我决定也存储用户的profile_picture So I create a new field profile_picture as ImageField to store the path of user's profile picture in the same extended users model.所以我创建了一个新的字段profile_picture作为ImageField来存储用户的个人资料图片在同一个扩展users模型中的路径。

models.py模型.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'

Then I updated UserAPIView class to add parser_classes = (FileUploadParser)然后我更新了UserAPIView类以添加parser_classes = (FileUploadParser)

view.py查看.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
                })

            subject = 'Eitan - Case Manager Account Credentials'
            body = f"Hi {serialized_data.validated_data.get('first_name')} Your case manager account is ready. Please use following credentials to login. Email - {serialized_data.validated_data.get('email')}, Password - {serialized_data.validated_data.get('password')} Thank You! Team Eitan."
            sender = "steinnlabs@gmail.com"
            to = serialized_data.validated_data.get('email')

            send_mail(subject, body, sender, [to], fail_silently=False)

            success_message = f"User has been created."

            return Response({
                'success_message' : success_message,
                'status' : status.HTTP_201_CREATED
            })

        else:
            return Response (serialized_data.error_messages)

Updated settings.py to add MEDIA_ROOT and MEDIA_URL更新settings.py以添加MEDIA_ROOTMEDIA_URL

settings.py设置.py

# Image upload configurations
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/

Now, when I pass the object to the endpoint http://127.0.0.1:8000/user/create/ it returns -现在,当我将对象传递给端点http://127.0.0.1:8000/user/create/它返回 -

{
    "detail": "Missing filename. Request should include a Content-Disposition header with a filename parameter."
}

JSON object JSON 对象

{
    "first_name": "Abhishek",
    "last_name": "Muley",
    "email": "yogesh@steinnlabs.com",
    "password": "1234",
    "profile_picture":"Users/jeetpatel/Desktop/sample_image.png"
}

Instead of sending data json object, send data as form object, if you choose to send the data as form object, then you need to mention parser_classes = [FileUploadParser, FormParser, MultiPartParser]不是发送数据json对象,而是将数据作为表单对象发送,如果选择将数据作为表单对象发送,则需要提及parser_classes = [FileUploadParser, FormParser, MultiPartParser]

Following is the link to help to define form data.以下是帮助定义表单数据的链接。 Postman request with body Form data to json 带有正文表单数据的邮递员请求到 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM