0001-api_views-provide-a-default-slug-for-ous-22250.patch
src/authentic2/api_views.py | ||
---|---|---|
25 | 25 |
from django.contrib.auth.hashers import identify_hasher |
26 | 26 |
from django.core.exceptions import MultipleObjectsReturned |
27 | 27 |
from django.utils.translation import ugettext as _ |
28 |
from django.utils.text import slugify |
|
28 | 29 |
from django.utils.encoding import force_text |
29 | 30 |
from django.utils.dateparse import parse_datetime |
30 | 31 |
from django.views.decorators.vary import vary_on_headers |
... | ... | |
887 | 888 |
role_memberships = RoleMembershipsAPI.as_view() |
888 | 889 | |
889 | 890 | |
891 |
class SlugFromNameDefault: |
|
892 |
requires_context = False |
|
893 |
serializer_instance = None |
|
894 | ||
895 |
def set_context(self, instance): |
|
896 |
self.serializer_instance = instance |
|
897 | ||
898 |
def __call__(self): |
|
899 |
name = self.serializer_instance.context['request'].data.get('name', '') |
|
900 |
return slugify(name) |
|
901 | ||
902 | ||
890 | 903 |
class BaseOrganizationalUnitSerializer(serializers.ModelSerializer): |
904 |
slug = serializers.SlugField( |
|
905 |
required=False, |
|
906 |
allow_blank=False, |
|
907 |
max_length=127, |
|
908 |
default=SlugFromNameDefault(), |
|
909 |
) |
|
891 | 910 |
class Meta: |
892 | 911 |
model = get_ou_model() |
893 | 912 |
fields = '__all__' |
tests/test_api.py | ||
---|---|---|
30 | 30 |
from django.core import mail |
31 | 31 |
from django.urls import reverse |
32 | 32 |
from django.utils.encoding import force_text |
33 |
from django.utils.text import slugify |
|
33 | 34 |
from django.utils.timezone import now |
34 | 35 |
from django.utils.http import urlencode |
35 | 36 | |
... | ... | |
1254 | 1255 |
assert role.ou == get_default_ou() |
1255 | 1256 | |
1256 | 1257 | |
1258 |
def test_api_post_ou_no_slug(app, superuser): |
|
1259 |
app.authorization = ('Basic', (superuser.username, superuser.username)) |
|
1260 |
OU = get_ou_model() |
|
1261 | ||
1262 |
ou_data = { |
|
1263 |
'name': 'Some Organization Unit', |
|
1264 |
} |
|
1265 |
resp = app.post_json('/api/ous/', params=ou_data) |
|
1266 |
uuid = resp.json['uuid'] |
|
1267 |
ou = OU.objects.get(uuid=uuid) |
|
1268 |
assert ou.id != get_default_ou().id |
|
1269 |
assert ou.slug == slugify(ou.name) |
|
1270 |
# no slug no name |
|
1271 |
ou_data = { |
|
1272 |
'id': 42, |
|
1273 |
} |
|
1274 |
resp = app.post_json('/api/ous/', params=ou_data, status=400) |
|
1275 |
assert resp.json['errors']['name'] == ['This field is required.'] |
|
1276 | ||
1277 | ||
1257 | 1278 |
def test_api_post_role_unauthorized(app, simple_user, ou1): |
1258 | 1279 |
app.authorization = ('Basic', (simple_user.username, simple_user.username)) |
1259 | 1280 |
Role = get_role_model() |
1260 |
- |