如何使用django rest框架从angularjs客户端将图像上传到django?

时间:2016-11-06 06:12:21

标签: angularjs django django-rest-framework

我无法弄清楚如何从angularjs发布图像。 我是django和django-rest-framework的新手。 提前谢谢。

models.py

class UserImages(models.Model):
   owner = models.ForeignKey('auth.User', related_name='UserImages')
   user=models.ForeignKey(Profile)

   # highlighted = models.TextField(default=None,blank=True,null=True)
   likes=JSONField(null=True,blank=True)
   image=models.ImageField()
   pub_date=models.DateTimeField(default=now)
   def __str__(self):
      return str(self.owner)

serializers.py

class ImageSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='user.username')
image_url = serializers.SerializerMethodField('gett_image_url')
class Meta:
    model=UserImages
    fields=('id','owner','image','likes','image','image_url','owner')
def gett_image_url(self,obj):
    return obj.image.url

views.py(我尝试过的)

class Profile_List(APIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly)
parser_classes = (FileUploadParser,)
def get(self, request, format=None):
    profiles=Profile.objects.all()
    serializer=ProfileSerializer(profiles, many=True)
    return Response(serializer.data)
def post(self, request, format=None):
    req=request.data
    image = req['display_image']
    req['user']=self.request.user.id
    #self.request.user.
    serializer=ProfileSerializer(data=req)
    if serializer.is_valid():
        serializer.save(owner=self.request.user)
        return Response(serializer.data,status=status.HTTP_201_CREATED)
    return Response(serializer.errors,status=status.HTTP_403_FORBIDDEN)

我无法弄清楚我应该如何设计视图,我读到了一些关于FileUploadParser的内容,但是它在我脑海中的视线代码片段会很好。 谢谢。

0 个答案:

没有答案