我正在尝试创建类别,同时创建类别时,我想显示类似“类别创建”的消息,或者如果它无法创建类别,我想为此显示一些错误消息以及状态代码。该代码仅显示状态代码,但是如何抛出错误消息以及状态代码?
serializers.py
class CategorySerializer(serializers. HyperlinkedModelSerializer):
name = serializers.CharField(
required=True,
validators=[UniqueValidator(queryset=Category.objects.all())]
)
class Meta:
model = Category
fields = (
'id',
'name',
'description',
'parent_id',
'start',
'end',
'is_service',
'display_home',
'is_achievement_option',
)
read_only_fields = ('id',)
views.py
@api_view(['POST'])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((permissions.IsAdminUser,))
def add(request):
if request.method == 'POST':
serializer = CategorySerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
try...except
@api_view(['POST'])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((permissions.IsAdminUser,))
def add(request):
try:
if request.method == 'POST':
serializer = CategorySerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
return Response({'status': 500, 'error': str(e)})
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is not None:
response.data['status_code'] = response.status_code
# ... write your logic here ...
# response.data['message'] = str(exc)
return response
REST_FRAMEWORK = {
# ...
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
# ...
}