我正在研究django rest框架并使用基于函数的视图。我使用2个函数,一个用于渲染html,另一个用于json响应。我如何结合功能以获得更有效的代码
我的代码
def register(request):
return render(request, 'register.html')
@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
if request.method == 'POST':
serializer = SignupSerializer(data=request.data)
print 'ser'
print serializer
if not serializer.is_valid():
return Response(serializer.errors,\
status=status.HTTP_400_BAD_REQUEST)
else:
serializer.save()
return Response({
'status': 'Created',
'message': 'Verification email has been sent to your email. Please verify your account.'
}, status=status.HTTP_201_CREATED)
答案 0 :(得分:0)
这可以由序列化程序处理,如drf教程的part2中所述。
它的工作原理如下:
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from your_app import views
urlpatterns = [
url(r'^blahblah/$', views.create_user),
]
urlpatterns = format_suffix_patterns(urlpatterns)
def create_user(request, format=None): # add this format argument
...
根据format参数,您可以决定是否要呈现请求。