首页 > 解决方案 > 以 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}"

这是我从邮递员那里得到的, 也是我从反应应用程序调用 API 时从浏览器得到的

标签: djangodjango-rest-frameworkdjango-custom-user

解决方案


在您的视图中的 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)

推荐阅读