我的工作形式必须使用django rest框架序列化程序类作为表单。让我向您展示一些代码,以便您更好地理解。
在我的模型中,我有一个动态返回序列化程序类的属性:
@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数据为空。
我错过了什么?谢谢你的帮助。
答案 0 :(得分: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)