没有保存DRF数据的上载模型数据

时间:2019-02-16 04:16:46

标签: django django-rest-framework django-views

我正在尝试通过api端点为我的CustomerDetails模型上传照片以及其他数据。数据似乎已保存,但是当我检查表时,没有数据存在。

这是我的模特:

git push origin master --hard

这是我的序列化器和网址

class CustomerDetails(models.Model):
    Sizes = (
    ('Sizes', (
        ('small', 'small'),
        ('medium', 'medium'),
        ('large', 'large'),
            )),
        )
    CATEGORIES = (
    ('Usage', (
        ('Headache', 'Headache'),
        ('Backaches', 'Insomnia'),
        ('Menstrual Cramps & Pains','Menstrual Cramps 
            )),
        )
    CUSTYPE = (
    ('Customer Type',(
        ('Athlete', 'Athlete'),
        ('Non-Athlete', 'Non-Athlete'),
        )),
    )
    
    age = models.IntegerField(default="21", blank=True)
    nick_name = models.CharField(max_length=500, blank=True)
    average_order = models.FloatField(default = "0.0", blank=True)
    completed_orders = models.IntegerField(default = "0", blank=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer')
    customer_type = MultiSelectField(choices=CUSTYPE, default = CUSTYPE, max_length=100)
    current_selfie = models.ImageField(upload_to= 'sefies/', blank=True, default='')
    favorite_color = MultiSelectField(choices=TYPE, max_length=100)
    interested_in = MultiSelectField(choices=CATEGORIES, max_length=1000)
    last_signin = models.DateTimeField(default = timezone.now)
    liked_stores = models.ManyToManyField('Stores')
    liked_products = models.ManyToManyField('Product')
    phone = PhoneField(blank=True, help_text='Contact phone number')
    shares = models.IntegerField(default = "0", blank=True)
    signup = models.DateTimeField(default = timezone.now)

    def __str__(self):
        return self.customer.user.get_full_name()

这是我正在使用的apiView:

   
  url(r'^api/customer/create_customer_details/$', apis.CustomerDetailViewset.as_view()),


class CustomerDetailUploader(serializers.ModelSerializer):
    customer = CustomerDetailSerializer()
 
    current_selfie = serializers.SerializerMethodField()

    
    def get_current_selfie(self, store):
        request = self.context.get('request')
        current_selfie_url = CustomerDetails.current_selfie.url
        return request.build_absolute_uri(current_selfie_url)

    class Meta:
        model = CustomerDetails
        fields = ('nick_name', 'customer', 'current_selfie', 'favorite_color', 'interested_in', 'customer_type')

我正在尝试为每个用户注册时创建一个新的customerDetails页面,将数据分配给Customer,然后保存详细信息。每当我尝试调用该函数时,都会收到成功消息:

[15 / Feb / 2019 22:56:10]“ POST / api / customer / create_customer_details /?access_token = U3EvAbo1HhOwNAgcEYUR4WOegul6ye HTTP / 1.1” 201 99

任何人都可以让我知道如何解决此问题吗?

2 个答案:

答案 0 :(得分:1)

您可以使用DRF尝试保存图像(Base64)

serializer.py

class Base64ImageField(serializers.ImageField):


    def to_internal_value(self, data):

        from django.core.files.base import ContentFile
        import base64
        import six
        import uuid

        # Check if this is a base64 string
        if isinstance(data, six.string_types):
            # Check if the base64 string is in the "data:" format
            if 'data:' in data and ';base64,' in data:
                # Break out the header from the base64 content
                header, data = data.split(';base64,')

            # Try to decode the file. Return validation error if it fails.
            try:
                decoded_file = base64.b64decode(data)
            except TypeError:
                self.fail('invalid_image')

            # Generate file name:
            file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
            # Get the file name extension:
            file_extension = self.get_file_extension(file_name, decoded_file)

            complete_file_name = "%s.%s" % (file_name, file_extension, )

            data = ContentFile(decoded_file, name=complete_file_name)

        return super(Base64ImageField, self).to_internal_value(data)

    def get_file_extension(self, file_name, decoded_file):
        import imghdr
        extension = imghdr.what(file_name, decoded_file)
        extension = "jpg" if extension == "jpeg" else extension

        return extension

 class CustomerDetailUploader(serializers.ModelSerializer):
      customer = CustomerDetailSerializer()

      current_selfie = Base64ImageField()
     class Meta:
        model = CustomerDetails
       fields = ('nick_name', 'customer', 'current_selfie', 'favorite_color', 'interested_in', 'customer_type')

在api.py

class CustomerDetailViewset(APIView):

     parser_classes = (MultiPartParser, FormParser)


     def post(self, request, *args, **kwargs):


        file_serializer = CustomerDetailUploader(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
        return Reponse ({})

希望它对您的问题有帮助

答案 1 :(得分:1)

也许您有一些错误,但是您没有看到它们,因为您总是返回201。第一个Response应该在if分支内部。 您的代码:

def post(self, request, *args, **kwargs):
        file_serializer = CustomerDetailUploader(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
        return Response(file_serializer.data, status=status.HTTP_201_CREATED)
        return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

正确的代码:

def post(self, request, *args, **kwargs):
        file_serializer = CustomerDetailUploader(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
            return Response(file_serializer.data, status=status.HTTP_201_CREATED)
        return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)