django - 以 json 格式获取 django_rest_framework 中的错误消息
问题描述
我想收到一条错误消息
{
"phone": [
"user with this phone already exists."
]
}
采用 JSON 格式,例如{"error": "user with this phone already exists."}
来自响应
HTTP 400 Bad Request
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"phone": [
"user with this phone already exists."
]
}
但我得到的只是VM8:1 POST http://127.0.0.1:8000/users/ 400 (Bad Request)
我的代码:
序列化程序.py
class UserCreateSerializer(UserCreateSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'email', 'phone', 'stream', 'school', "password", )
模型.py
class User(AbstractBaseUser, PermissionsMixin):
id = models.AutoField(primary_key=True)
first_name = models.CharField(_('first name'), max_length=30)
last_name = models.CharField(_('last name'), max_length=30, null=True)
email = models.EmailField(_('email address'), unique=True)
phone = models.CharField(_('phone'), max_length=15, unique=True)
stream = models.CharField(_('stream'), max_length=25)
school = models.CharField(_('school'), max_length=40)
tests_given = ArrayField(models.IntegerField(), null=True, blank=True)
messages = ArrayField(models.CharField(max_length=100), null=True, blank=True)
is_active = models.BooleanField(_('active'), default=True)
is_staff =models.BooleanField(_('staff'), default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'phone']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def __str__(self) :
return f"{self.first_name}"
解决方案
在您的视图中的 serializer.is_valid() 中添加 raise_exception=True
def post(self, request):
serializer = UserCreateSerializer(request.data, many=False)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
推荐阅读
- python - pdfminer中的dumppdf.py提取pdf轮廓
- amazon-web-services - Elastic Beanstalk 在内存不足后停止
- amazon-web-services - AWS IAM 角色 - 最佳实践
- javascript - 如何在 Highcharts 的 x 轴标签上的整数前面添加撇号?
- r - R中的主题内串行调解
- javascript - MVC 在初始加载时显示初始屏幕的最佳方式
- c - 如何使用指向二维数组C的指针
- c# - 如何在 xUnit 中为类构造函数创建单元测试?
- c++ - 找不到#define 的函数定义
- python - 如何从另一列中减去熊猫中的一列?