Manual rendering of serializer fields in a template?

1,354 views
Skip to first unread message

Anye Freer

unread,
Nov 16, 2016, 3:16:12 PM11/16/16
to Django REST framework
Greetings,

I'm trying to use DRF for an application that will serve both web pages and a web API and reduce duplication as much as possible, so I'm trying to create both template based views and JSON response based views for the same functions using serializers and keep the logic for how the classes are saved in the serializers and out of the individual views.

Looking at the DRF documentation I can see how to auto-render a serializer using a template pack and with the "render_form" keyword, but I do not see any way to manually lay out the template fields individually, ie. {% serializer.first_name %} etc.  Since the people who will be doing the layout  & style for these forms are not Python developers but HTML/CSS developers, it's really not desirable to have the style information in the Python code but rather to have HTML elements that can be styled by the UX resources in the templates & css files.  Separation of concerns in general dictates that it's not the best practice to put the style info into the code as well.

Can you please advise on how we can lay out the forms & style manually in the template using serializers, analogously to how it is possible using Django forms?

If this isn't possible, is it possible to use a serializer to populate a Django form and vice-versa so we could use "regular" Django forms in the template but still keep all the logic in the common serializer?

Thanks in advance!

Alex Scott

unread,
Nov 18, 2016, 1:48:46 AM11/18/16
to Django REST framework
I'm new to DRF so this might not help but the serializer actually seems pretty similar to a Django form object.  So in the template, you could actually just reference the data in the serializer via serializer.data (I'm not sure if there are problems with this).)

<input type="text" value="{{ serializer.data.name }}">

That's about as manual as you could get.

An alternative is to use template packs, as outlined here: http://www.django-rest-framework.org/topics/html-and-forms/#using-template-packs

You can also look at custom renderers but not sure if that's what you want: http://www.django-rest-framework.org/api-guide/renderers/#custom-renderers
Reply all
Reply to author
Forward
0 new messages