In Rails, I can use respond_to to define how the controller respond to according to the request format.
in routes.rb
map.connect '/profile/:action.:format', :controller => "profile_controller"
in profile_controller.rb
def profile
@profile = ...
respond_to do |format|
format.html { }
format.json { }
end
end
Currently, in Django, I have to use two urls and two actions: one to return html and one to return json.
url.py:
urlpatterns = [
url(r'^profile_html', views.profile_html),
url(r'^profile_json', views.profile_json),
]
view.py
def profile_html (request):
#some logic calculations
return render(request, 'profile.html', {'data': profile})
def profile_json(request):
#some logic calculations
serializer = ProfileSerializer(profile)
return Response(serializer.data)
With this approach, the code for the logic becomes duplicate. Of course I can define a method to do the logic calculations but the code is till verbose.
Is there anyway in Django, I can combine them together?