From 22f6cb7237ebe6c0416ebe217472b4281c8cbd34 Mon Sep 17 00:00:00 2001
From: Jean-Baptiste <bleme@pm.me>
Date: Tue, 17 Sep 2019 15:23:21 +0200
Subject: [PATCH] update: auto set slug with pk if not specified

---
 djangoldp/models.py                       | 15 +++++++++------
 djangoldp/serializers.py                  | 10 ++++++----
 djangoldp/tests/models.py                 |  2 +-
 djangoldp/tests/tests_save.py             | 13 ++++++++-----
 djangoldp/tests/tests_update.py           |  2 +-
 djangoldp/tests/tests_user_permissions.py | 12 ++++++------
 6 files changed, 31 insertions(+), 23 deletions(-)

diff --git a/djangoldp/models.py b/djangoldp/models.py
index 22410de0..0d89db5b 100644
--- a/djangoldp/models.py
+++ b/djangoldp/models.py
@@ -1,7 +1,7 @@
 from django.conf import settings
 from django.db import models
 from django.db.models.base import ModelBase
-from django.db.models.signals import pre_save, post_save
+from django.db.models.signals import post_save
 from django.dispatch import receiver
 from django.urls import get_resolver
 from django.utils.datastructures import MultiValueDictKeyError
@@ -34,7 +34,7 @@ class Model(models.Model):
         return cls.__clean_path(path)
 
     def get_absolute_url(self):
-        if self.urlid is  None or self.urlid != '':
+        if self.urlid is None or self.urlid != '':
             return '{}{}'.format(settings.BASE_URL, Model.resource_id(self))
         else:
             return self.urlid
@@ -167,7 +167,10 @@ class LDPSource(Model):
 
 @receiver([post_save])
 def auto_urlid(sender, instance, **kwargs):
-    if isinstance(instance, Model) and (instance.urlid is None or instance.urlid == '' or 'None' in instance.urlid):
-        instance.urlid = instance.get_absolute_url()
-        instance.save()
-
+    if isinstance(instance, Model):
+        if getattr(instance, Model.slug_field(instance), None) is None:
+            setattr(instance, Model.slug_field(instance), instance.pk)
+            instance.save()
+        if (instance.urlid is None or instance.urlid == '' or 'None' in instance.urlid):
+            instance.urlid = instance.get_absolute_url()
+            instance.save()
diff --git a/djangoldp/serializers.py b/djangoldp/serializers.py
index 1af1ca6f..1d7a2720 100644
--- a/djangoldp/serializers.py
+++ b/djangoldp/serializers.py
@@ -390,8 +390,6 @@ class LDPSerializer(HyperlinkedModelSerializer):
                     fields = '__all__'
 
             def to_internal_value(self, data):
-                if self.url_field_name in data and not 'urlid' in data and data[self.url_field_name].startswith('http'):
-                    data['urlid'] = data[self.url_field_name]
                 if data is '':
                     return ''
                 if self.url_field_name in data:
@@ -444,9 +442,13 @@ class LDPSerializer(HyperlinkedModelSerializer):
                         if 'urlid' in data:
                             ret['urlid'] = data['urlid']
 
-                    return ret
                 else:
-                    return super().to_internal_value(data)
+                    ret = super().to_internal_value(data)
+
+                if self.url_field_name in data and not 'urlid' in data and data[self.url_field_name].startswith('http'):
+                    ret['urlid'] = data[self.url_field_name]
+
+                return ret
 
         kwargs = get_nested_relation_kwargs(relation_info)
         kwargs['read_only'] = False
diff --git a/djangoldp/tests/models.py b/djangoldp/tests/models.py
index f70c1319..761b5388 100644
--- a/djangoldp/tests/models.py
+++ b/djangoldp/tests/models.py
@@ -21,7 +21,7 @@ class Skill(Model):
         anonymous_perms = ['view']
         authenticated_perms = ['inherit', 'add']
         owner_perms = ['inherit', 'change', 'delete', 'control']
-        serializer_fields = ["@id", "title", "recent_jobs"]
+        serializer_fields = ["@id", "title", "recent_jobs", "slug"]
         lookup_field = 'slug'
 
 
diff --git a/djangoldp/tests/tests_save.py b/djangoldp/tests/tests_save.py
index 0c97d5c3..52e8bf4b 100644
--- a/djangoldp/tests/tests_save.py
+++ b/djangoldp/tests/tests_save.py
@@ -60,6 +60,7 @@ class Save(TestCase):
         skill2 = Skill.objects.create(title="skill2", obligatoire="obligatoire", slug="slug2")
 
         job = {"title": "job test",
+               "slug": "slug1",
                "skills": {
                    "ldp:contains": [
                        {"@id": "https://happy-dev.fr/skills/{}/".format(skill1.slug)},
@@ -84,11 +85,11 @@ class Save(TestCase):
 
     def test_save_m2m_graph_simple(self):
         job = {"@graph": [
-            {"title": "job test",
+            {"title": "job test", "slug": "slugjob",
              },
         ]}
 
-        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills")}
+        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills", "slug")}
 
         meta_class = type('Meta', (), meta_args)
         serializer_class = type(LDPSerializer)('JobOfferSerializer', (LDPSerializer,), {'Meta': meta_class})
@@ -105,12 +106,13 @@ class Save(TestCase):
 
         job = {"@graph": [
             {"title": "job test",
+             "slug": "slugj",
              "skills": {"@id": "_.123"}
              },
-            {"@id": "_.123", "title": "skill3 NEW", "obligatoire": "obligatoire"},
+            {"@id": "_.123", "title": "skill3 NEW", "obligatoire": "obligatoire", "slug": "skill3"},
         ]}
 
-        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills")}
+        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills", "slug")}
 
         meta_class = type('Meta', (), meta_args)
         serializer_class = type(LDPSerializer)('JobOfferSerializer', (LDPSerializer,), {'Meta': meta_class})
@@ -127,7 +129,7 @@ class Save(TestCase):
         skill2 = Skill.objects.create(title="skill2", obligatoire="obligatoire", slug="b")
         job = {"title": "job test", "slug": "c"}
 
-        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills")}
+        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills", "slug")}
 
         meta_class = type('Meta', (), meta_args)
         serializer_class = type(LDPSerializer)('JobOfferSerializer', (LDPSerializer,), {'Meta': meta_class})
@@ -271,6 +273,7 @@ class Save(TestCase):
         resource = Resource.objects.create()
         body = {
             'http://happy-dev.fr/owl/#title': "new job",
+            'http://happy-dev.fr/owl/#slug': "job1",
         }
 
         response = self.client.post('/resources/{}/joboffers/'.format(resource.pk),
diff --git a/djangoldp/tests/tests_update.py b/djangoldp/tests/tests_update.py
index a9a7dca2..9ba9a525 100644
--- a/djangoldp/tests/tests_update.py
+++ b/djangoldp/tests/tests_update.py
@@ -138,7 +138,7 @@ class Update(TestCase):
             ]
         }
 
-        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills")}
+        meta_args = {'model': JobOffer, 'depth': 2, 'fields': ("@id", "title", "skills", "slug")}
 
         meta_class = type('Meta', (), meta_args)
         serializer_class = type(LDPSerializer)('JobOfferSerializer', (LDPSerializer,), {'Meta': meta_class})
diff --git a/djangoldp/tests/tests_user_permissions.py b/djangoldp/tests/tests_user_permissions.py
index cd66a481..0b310acf 100644
--- a/djangoldp/tests/tests_user_permissions.py
+++ b/djangoldp/tests/tests_user_permissions.py
@@ -13,28 +13,28 @@ class TestUserPermissions(APITestCase):
         user = User.objects.create_user(username='john', email='jlennon@beatles.com', password='glass onion')
         self.client = APIClient(enforce_csrf_checks=True)
         self.client.force_authenticate(user=user)
-        self.job = JobOffer.objects.create(title="job", slug=1)
+        self.job = JobOffer.objects.create(title="job", slug="slug1")
 
     def test_get_for_authenticated_user(self):
         response = self.client.get('/job-offers/')
         self.assertEqual(response.status_code, 200)
 
     def test_get_1_for_authenticated_user(self):
-        response = self.client.get('/job-offers/1/')
+        response = self.client.get('/job-offers/{}/'.format(self.job.slug))
         self.assertEqual(response.status_code, 200)
 
     def test_post_request_for_authenticated_user(self):
-        post = {'title': "job_created"}
+        post = {'title': "job_created", "slug": 'slug1'}
         response = self.client.post('/job-offers/', data=json.dumps(post), content_type='application/ld+json')
         self.assertEqual(response.status_code, 201)
 
     def test_put_request_for_authenticated_user(self):
         body = {'title':"job_updated"}
-        response = self.client.put('/job-offers/{}/'.format(self.job.pk), data=json.dumps(body),
+        response = self.client.put('/job-offers/{}/'.format(self.job.slug), data=json.dumps(body),
                                    content_type='application/ld+json')
         self.assertEqual(response.status_code, 200)
-    
+
     def test_request_patch_for_authenticated_user(self):
-        response = self.client.patch('/job-offers/' + str(self.job.pk) + "/",
+        response = self.client.patch('/job-offers/' + str(self.job.slug) + "/",
                                    content_type='application/ld+json')
         self.assertEqual(response.status_code, 200)
-- 
GitLab