serialization - Django REST Framework show multiple forms on HTML view -


i have viewset using django rest framework has both standard , custom routes. serializer each route different.

example:

class userviewset(viewset):      model = user     serializer_class = userserializer      @decorators.detail_route(methods=['put'])     def change_password(self, request, pk, *args, **kwargs):         serializer = userchangepasswordserializer(data=request.data)         ...      @decorators.detail_route(methods=['put'])     def update_prefs(self, request, *args, **kwargs):         serializer = userpreferencesserializer(data=request.data)         ... 

i have working such can perform standard get, post, put, delete actions on user object , 2 routes work. however, can't figure out how make html forms custom routes display when using browsableapirenderer. handy developers able see forms demonstrating fields expected on above put methods, example.

i tried adding methods 2 routes, non-sensical first one. regardless, don't see right serializer displayed when go url route, see serializer specified in serializer_class.

about thing haven't tried overriding get_serializer_class() because involves putting knowledge of every serializer every route in single place rather being able specify serializer within route method itself... way should trying desired effect?

it turns out need not use serializer_class , instead override get_serializer_class. since takes action, can if..elif..else on return right serializer. clever use of dictionary makes easy:

serializers = {     'default': userserializer,     'password_update': passwordupdateserializer,     'register': userregisterserializer, }  def get_serializer_class(self, *args, **kwargs):     return self.serializers.get(self.action, self.serializers['default']) 

this return userserializer actions unless specify different serializer in serializers dictionary. easier thought be.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -