2016-06-28 63 views
3

我正在使用必須使用django rest框架序列化程序類作爲窗體的窗體中工作。讓我給你看一些代碼,以便你更好地理解。Django Rest框架 - 爲什麼serializer.data爲空

在我的模型我有一個返回動態序列化類的屬性:

@property 
def content_serializer_class(self): 
    backend_module = self.backend_module 

    if backend_module == "youtube": 
     return YoutubeSerializer 
    elif backend_module == "googleplay": 
     return GoogleplaySerializer 
    elif backend_module == "bellone": 
     return BelloneSerializer 
    elif backend_module == "rogersvod": 
     return RogersvodSerializer 

然後我的觀點:

class ContentCreateView(LoginRequiredMixin, PermissionRequiredMixin, APIView): 
    renderer_classes = [TemplateHTMLRenderer] 
    template_name = 'delivery/content_form.html' 
    permission_required = 'delivery.change_delivery' 

    def get(self, request, delivery_id): 
     delivery = get_object_or_404(Delivery, pk=delivery_id,owner=self.request.user) 
     if not delivery.can_change: 
      raise Http404 

     return Response({'serializer': delivery.content_serializer_class, 'delivery': delivery}) 

    def post(self, request, delivery_id): 
     delivery = get_object_or_404(Delivery, pk=delivery_id,owner=self.request.user) 
     if not delivery.can_change: 
      raise Http404 

     serializer = delivery.content_serializer_class(data=request.data) 

     if not serializer.is_valid(): 
      return Response({'serializer': delivery.content_serializer_class, 'delivery': delivery}) 

     print 'serializer', serializer.data 

     nextUrl = self.request.POST.get("next", "") 
     if nextUrl: 
      return redirect(nextUrl) 
     else: 
      return redirect(reverse('delivery:delivery-detail', args=[delivery_id])) 

而且我的模板:

<form role="form" id="form-content" class="form-horizontal" method="post"> 
    {% csrf_token %} 
    <input type="hidden" id="id-next" name="next" value="" /> 
    {% render_form serializer template_pack='rest_framework/horizontal' %}    
</form> 

我跟隨this guide

問題是,當我嘗試從序列化程序(serializer.data)得到json是空的。驗證工作正常,表單呈現正常,但json數據爲空。

我錯過了什麼?謝謝你的幫助。

回答

2

由於格式通常

mymodel = MyModel.objects.get(id=model_id) 
    serializer = MyModelSerializer(mymodel,many=False) # for single object 

是等一流水平它必須是:

def content_serializer_class(self): 
    backend_module = self.backend_module 

    if backend_module == "youtube": 
     return YoutubeSerializer(self,many=False) 

    elif backend_module == "googleplay": 
     return GoogleplaySerializer(self,many=False) 

    elif backend_module == "bellone": 
     return BelloneSerializer(self,many=False) 

elif backend_module == "rogersvod": 
    return RogersvodSerializer(self,many=False) 
+0

謝謝您的回答。這個序列化程序沒有鏈接到任何模型,這只是創建一個json。無論如何,我會盡力的,謝謝 –