Django Rest Framework - 带有“.”、“-”、“_”字符的字段用户名

Django Rest Framework - Field username with ".", "-", "_" character

我想允许我的后端 API 允许使用 .-_ñ 等字符创建任何用户username 字段中的其他字符 primary_key=True,.

我以这种方式定义我的自定义用户 (AbstractBaseUser),与我感兴趣的 username 字段相关:

class User(AbstractBaseUser, PermissionsMixin):

    username = models.CharField(
        _('username'),
        max_length=30,
        primary_key=True,
        unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[
            RegexValidator(
                r'^[\w.@+-]+$',
                _('Enter a valid username. This value may contain only '
                  'letters, numbers ' 'and @/./+/-/_ characters.')
            ),
        ],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    email = models.EmailField(max_length=254, unique=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()

我的UserSerializer是这样的:

class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all(), message='Lo sentimos, existe un fichaje con este nombre de usuario')])
    email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all(), message='Lo sentimos, alguien ya ha sido fichado con este correo electrónico')])

    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'first_name','last_name',
                  'age','other fields ...',)

我的 UserViewSet 如下:

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', )

路由器是这样定义的 urls.py

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

当我在 username 字段中创建具有 . 字符的用户,例如 bacalao.cevichica 时,该用户已创建,但是当我转到 localhost:8000/api/users/

我收到这条消息:

File "/home/bgarcial/.virtualenvs/fuupbol2/lib/python3.5/site-packages/django/urls/resolvers.py", line 392, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with arguments '()' and keyword arguments '{'pk': 'bacalao.cevichica'}' not found. 2 pattern(s) tried: ['api/users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$', 'api/users/(?P<pk>[^/.]+)/$']

我对正则表达式不是很熟悉,可能 RegexValidator 格式不正确?

此外,我的问题可能出在 UserSerializerUserViewSet

目前我还没有弄清楚这个话题,非常感谢任何方向。 :)

如果您查看该错误,您会发现它试图匹配某些 url,但失败了。这是因为默认正则表达式 ([^./]) 排除了 ./ 字符

您可以将 lookup_value_regex 添加到您的 ViewSet,以便 URL 知道您的主键应该采用哪种格式:

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    lookup_value_regex = '[\w.@+-]+'
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', )