2017-03-16 49 views
1

我希望從我的後端API允許任何用戶創建字符,例如.,-,_, ñ其他字符他們的username字段是primary_key=True,Django Rest Framework - 字段用戶名帶有「。」,「 - 」,「_」字符

我定義的這種方式我自定義的用戶(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'^[\[email protected]+-]+$', 
       _('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',) 

該路線R在urls.py

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

OG這樣定義。當我創建.字符,例如像在TE 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>[^/.]+)/$'] 

enter image description here

我不是很熟悉與正常表達,並有可能是RegexValidator不正常形成?

此外,有可能我的問題是在UserSerializerUserViewSet

到目前爲止我還沒有清楚這個話題,任何方向是高度讚賞。 :)

+1

它只是聽起來像URL模式不支持句點。你能用明文包含正在使用的正則表達式嗎? – TankorSmash

+0

@TankorSmash理論上我使用的正則表達式是'RegexValidator的代碼段( r'^ [\ w。@ + - ] + $', _('輸入一個有效的用戶名,該值可能只包含' '字母,數字'和@ /。/ +/-/_字符。') ),'在模型User ...中的用戶名字段中?我的道歉,我是新手正規表達 – bgarcial

回答

2

如果你看看這個錯誤,你會注意到它試圖匹配某個url,但失敗了。這是因爲默認的正則表達式([^./])排除./字符

您可以將lookup_value_regex添加到您的視圖集,以使URL知道應該是什麼格式的主鍵:

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