pull/26/head
parent
eb2c1903a2
commit
eaa6af5762
|
@ -0,0 +1,28 @@
|
||||||
|
"""
|
||||||
|
重写校验器返回字段
|
||||||
|
"""
|
||||||
|
from rest_framework.validators import UniqueValidator, qs_exists
|
||||||
|
|
||||||
|
from vadmin.utils.exceptions import APIException
|
||||||
|
|
||||||
|
|
||||||
|
class CustomUniqueValidator(UniqueValidator):
|
||||||
|
"""
|
||||||
|
继承,重写必填字段的验证器结果,防止字段暴露
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __call__(self, value, serializer_field):
|
||||||
|
# Determine the underlying model field name. This may not be the
|
||||||
|
# same as the serializer field name if `source=<>` is set.
|
||||||
|
field_name = serializer_field.source_attrs[-1]
|
||||||
|
# Determine the existing instance, if this is an update operation.
|
||||||
|
instance = getattr(serializer_field.parent, 'instance', None)
|
||||||
|
|
||||||
|
queryset = self.queryset
|
||||||
|
queryset = self.filter_queryset(value, queryset, field_name)
|
||||||
|
queryset = self.exclude_current_instance(queryset, instance)
|
||||||
|
if qs_exists(queryset):
|
||||||
|
raise APIException(message=self.message)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return super().__repr__()
|
|
@ -1,8 +1,8 @@
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
from rest_framework.validators import UniqueValidator
|
|
||||||
|
|
||||||
from ..op_drf.serializers import CustomModelSerializer
|
from ..op_drf.serializers import CustomModelSerializer
|
||||||
|
from ..op_drf.validator import CustomUniqueValidator
|
||||||
from ..permission.models import Menu, Dept, Post, Role
|
from ..permission.models import Menu, Dept, Post, Role
|
||||||
from ..system.models import MessagePush
|
from ..system.models import MessagePush
|
||||||
|
|
||||||
|
@ -260,7 +260,8 @@ class UserProfileCreateUpdateSerializer(CustomModelSerializer):
|
||||||
post = PostSerializer(many=True, read_only=True)
|
post = PostSerializer(many=True, read_only=True)
|
||||||
role = RoleSerializer(many=True, read_only=True)
|
role = RoleSerializer(many=True, read_only=True)
|
||||||
username = serializers.CharField(required=True, max_length=150,
|
username = serializers.CharField(required=True, max_length=150,
|
||||||
validators=[UniqueValidator(queryset=UserProfile.objects.all(), message="用戶已存在")],
|
validators=[
|
||||||
|
CustomUniqueValidator(queryset=UserProfile.objects.all(), message="用戶已存在")],
|
||||||
error_messages={
|
error_messages={
|
||||||
"blank": "请输入用户名称",
|
"blank": "请输入用户名称",
|
||||||
"required": "用户名称不能为空",
|
"required": "用户名称不能为空",
|
||||||
|
|
Loading…
Reference in New Issue