我解決了這個問題,ModelViewSet和ModelSerializer
urlpatterns = patterns('',
url(r'^imageUpload', views.FileUploadView.as_view())
捲曲請求。希望這會幫助社區。
我也試圖在序列化程序本身而不是視圖中進行驗證和Object-> JSON(反之亦然)登錄。
讓我們通過實例來了解它。
說,我想創建FileUploader API。它將在數據庫中存儲諸如id,file_path,file_name,size,owner等字段。請參見下面示例模型:
class FileUploader(models.Model):
file = models.FileField()
name = models.CharField(max_length=100) #name is filename without extension
version = models.IntegerField(default=0)
upload_date = models.DateTimeField(auto_now=True, db_index=True)
owner = models.ForeignKey('auth.User', related_name='uploaded_files')
size = models.IntegerField(default=0)
現在,對於API的,這是我想要的東西:
GET: 當我火GET終點,我想每一個上傳文件的所有上述領域。
POST: 但是,對於用戶創建/上傳文件,爲什麼她必須擔心通過所有這些領域。她可以上傳文件,然後,我想,序列化程序可以從上傳的文件中獲得剩餘的字段。
Searilizer: 問題:我下面串行創建爲我的目的。但不確定是否有正確的實施方式。
class FileUploaderSerializer(serializers.ModelSerializer):
#overwrite = serializers.BooleanField()
class Meta:
model = FileUploader
fields = ('file','name','version','upload_date', 'size')
read_only_fields = ('name','version','owner','upload_date', 'size')
def validate(self, validated_data):
validated_data['owner'] = self.context['request'].user
validated_data['name'] = os.path.splitext(validated_data['file'].name)[0]
validated_data['size'] = validated_data['file'].size
#other validation logic
return validated_data
def create(self, validated_data):
return FileUploader.objects.create(**validated_data)
視圖集以供參考:
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes = (MultiPartParser, FormParser,)
# overriding default query set
queryset = LayerFile.objects.all()
def get_queryset(self, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs
哎,你知道我怎麼能解決http://stackoverflow.com/questions/26673572/django-rest-framework-upload-file-to-a-method? – psychok7
@pleasedontbelong爲什麼使用PUT方法而不是POST? – RTan
@Rego check this http://stackoverflow.com/a/14402607/361427 :) – pleasedontbelong