Django Rest Framework - Allowing blanks in a CharField

0

I have the following model, which in its attribute name I want to allow compound names or blank spaces, for example Real Madrid

class Team(models.Model):
    name = models.CharField(
        _('name'),
        max_length=30,
        primary_key=True,
        # unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and ./+/-/_ only.'),
        validators=[
            RegexValidator(
                # r'^[\w.ñ@+-]+$',
                r'^[\d\/. ()\-+ ]+$',
                _('Enter a valid name team. This value may contain only '
                  'letters, numbers ' 'and ./+/-/_ characters.')
            ),
        ],
        error_messages={
            'unique': _("A team with that name already exists."),
        },
    )

My urls.py file, in the url /api/teams I have a regular expression that includes the blank space in this way:

url(r'^api/teams/(?P<name>[-\w.]+(?:%20[-\w.]+)*)/?', include(router.urls,)),

router = routers.DefaultRouter()
router.register(r'teams', TeamViewSet)

urlpatterns = [

    # Wire up our API using automatic URL routing.
    url(r'^api/', include(router.urls,)),

    # url(r'^api/teams/(?P<name>[-\w. ]+)/?', include(router.urls,)),
    url(r'^api/teams/(?P<name>[-\w.]+(?:%20[-\w.]+)*)/?', include(router.urls,)),


    # If you're intending to use the browsable API you'll probably also want to add REST framework's
    # login and logout views.
    url(r'^api-auth/', include('rest_framework.urls',
        namespace='rest_framework'))

]

My serializer is:

class TeamSerializer(serializers.ModelSerializer):

    name = serializers.CharField(validators=[UniqueValidator(queryset=Team.objects.all(), message='Lo sentimos, ya existe un equipo con este nombre')])

    class Meta:
        model = Team
        fields = ('url', 'name',)

My viewset is:

class TeamViewSet(viewsets.ModelViewSet):

    lookup_value_regex = '[\w.ñ@+-]+'
    #lookup_value_regex = '[\d\/. ()\-+]+'
    queryset = Team.objects.all()
    serializer_class = TeamSerializer
    filter_fields = ('name',)

When I create a record of Team with a compound name or with blank spaces, it is not possible to render the record of that serialized equipment and on the contrary I get this message:

The idea is that you can allow /api/teams/ with characters such as ' . _ - ' and blank spaces for compound names as Real Madrid for example ...

So far I can create a URL / api / teams / con caracteres como ' . _ - ''

How can I allow blanks in that attribute name ?

    
asked by bgarcial 03.05.2017 в 05:13
source

0 answers