我在编写视图集和使用django rest docs时尝试记录 API 。我有以下问题:
如果我尝试发送反向相关字段的值,它需要值列表,但是在 Form-data 中发送数据时,它以字符串的形式出现。
文档 UI 中没有文件上传选项。
以下是我的代码:
模型.py
class Area(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
address = models.TextField()
image = models.ImageField(upload_to='area/')
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now=True)
zipcode = models.CharField(max_length=15, null=True)
is_verified = models.BooleanField(default=False)
class Meta:
ordering = ('-modified_on',)
class Email(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField()
area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, related_name='email')
class Phone(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
phone = models.CharField(max_length=15)
area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, related_name='phone')
视图.py
class AreaViewSet(viewsets.ModelViewSet):
"""
create:
Create a new area instance.
"""
serializer_class = AreaSerializer
parser_classes = (FormParser, MultiPartParser,FileUploadParser)
queryset = User.objects.all()
permission_classes = [AllowAny, ]
filter_backends = (DjangoFilterBackend,)
filter_fields = ('first_name',)
def create(self, request):
data = self.request.data
with transaction.atomic():
name = data['name']
address = data['address']
email = json.loads(data['email'])
phone = json.loads(data['phone'])
zipcode = data['zipcode']
area = Area.objects.create(name=name,address=address, zipcode=zipcode)
for i in email:
Email.objects.create(email=i['email'], area = area)
for i in phone:
Phone.objects.create(phone=i['phone'], area=area)
return Response({'status': {'code': status.HTTP_200_OK,
'error': None,
'message':' Area has been added.'
},
'data': None})
序列化程序.py
class AreaSerializer(serializers.ModelSerializer):
email = EmailSerializer(many=True)
phone = PhoneSerializer(many=True)
class Meta:
model = Area
fields = '__all__'
我正在使用 http://www.django-rest-framework.org/topics/documenting-your-api/
默认文档中的图像字段中没有文件上传。
谢谢