Publishing collections.
authorRadek Czajka <rczajka@rczajka.pl>
Fri, 7 Oct 2022 13:05:57 +0000 (15:05 +0200)
committerRadek Czajka <rczajka@rczajka.pl>
Fri, 7 Oct 2022 13:05:57 +0000 (15:05 +0200)
src/apiclient/__init__.py
src/catalogue/admin.py
src/catalogue/migrations/0040_collection_description.py [new file with mode: 0644]
src/catalogue/models.py
src/catalogue/urls.py
src/catalogue/views.py

index 36cd7ec..44546d3 100644 (file)
@@ -21,7 +21,7 @@ class NotAuthorizedError(BaseException):
     pass
 
 
     pass
 
 
-def api_call(user, path, data=None, beta=False):
+def api_call(user, path, data=None, beta=False, method=None, as_json=False):
     from .models import OAuthConnection
     api_url = BETA_API_URL if beta else WL_API_URL
     conn = OAuthConnection.get(user=user, beta=beta)
     from .models import OAuthConnection
     api_url = BETA_API_URL if beta else WL_API_URL
     conn = OAuthConnection.get(user=user, beta=beta)
@@ -31,21 +31,30 @@ def api_call(user, path, data=None, beta=False):
     client = oauth2.Client(wl_consumer, token)
     if data is not None:
         data = json.dumps(data)
     client = oauth2.Client(wl_consumer, token)
     if data is not None:
         data = json.dumps(data)
-        data = urlencode({"data": data})
+        headers = {}
+        if as_json:
+            headers["Content-Type"] = 'application/json'
+        else:
+            data = urlencode({"data": data})
+        data = data.encode('utf-8')
+
         resp, content = client.request(
             "%s%s" % (api_url, path),
         resp, content = client.request(
             "%s%s" % (api_url, path),
-            method="POST",
+            method=method or 'POST',
+            headers=headers,
             body=data)
     else:
         resp, content = client.request(
             body=data)
     else:
         resp, content = client.request(
-            "%s%s" % (api_url, path))
+            "%s%s" % (api_url, path),
+            method=method or 'GET'
+        )
     status = resp['status']
 
     status = resp['status']
 
-    if status == '200':
+    if status in ('200', '201'):
         return json.loads(content)
     elif status.startswith('2'):
         return
     elif status == '401':
         raise ApiError('User not authorized for publishing.')
     else:
         return json.loads(content)
     elif status.startswith('2'):
         return
     elif status == '401':
         raise ApiError('User not authorized for publishing.')
     else:
-        raise ApiError("WL API call error %s, path: %s" % (status, path))
+        raise ApiError("WL API call error %s, path: %s, body: %s" % (status, path, content))
index f00e7fc..958230b 100644 (file)
@@ -312,7 +312,7 @@ class CollectionAdmin(admin.ModelAdmin):
     autocomplete_fields = []
     prepopulated_fields = {"slug": ("name",)}
     search_fields = ["name"]
     autocomplete_fields = []
     prepopulated_fields = {"slug": ("name",)}
     search_fields = ["name"]
-    fields = ['name', 'slug', 'category', 'notes', 'estimated_costs']
+    fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
     readonly_fields = ['estimated_costs']
     inlines = [AuthorInline, BookInline]
 
     readonly_fields = ['estimated_costs']
     inlines = [AuthorInline, BookInline]
 
diff --git a/src/catalogue/migrations/0040_collection_description.py b/src/catalogue/migrations/0040_collection_description.py
new file mode 100644 (file)
index 0000000..ba8f3bf
--- /dev/null
@@ -0,0 +1,18 @@
+# Generated by Django 4.0.6 on 2022-10-07 12:37
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('catalogue', '0039_author_photo_author_photo_attribution_and_more'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='collection',
+            name='description',
+            field=models.TextField(blank=True, verbose_name='description'),
+        ),
+    ]
index db840da..4544fc6 100644 (file)
@@ -265,6 +265,7 @@ class Collection(models.Model):
     slug = models.SlugField(max_length=255, unique=True)
     category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
     notes = models.TextField(_("notes"), blank=True)
     slug = models.SlugField(max_length=255, unique=True)
     category = models.ForeignKey(CollectionCategory, models.SET_NULL, null=True, blank=True, verbose_name=_("category"))
     notes = models.TextField(_("notes"), blank=True)
+    description = models.TextField(_("description"), blank=True)
 
     class Meta:
         ordering = ('category', 'name')
 
     class Meta:
         ordering = ('category', 'name')
index 4eaf7b0..065c4f9 100644 (file)
@@ -23,4 +23,5 @@ urlpatterns = [
     path('wikidata/<slug:model>/<qid>', views.WikidataView.as_view()),
 
     path('publish/author/<int:pk>/', views.publish_author, name='catalogue_publish_author'),
     path('wikidata/<slug:model>/<qid>', views.WikidataView.as_view()),
 
     path('publish/author/<int:pk>/', views.publish_author, name='catalogue_publish_author'),
+    path('publish/collection/<int:pk>/', views.publish_collection, name='catalogue_publish_collection'),
 ]
 ]
index 376d328..95f33fd 100644 (file)
@@ -206,5 +206,27 @@ def publish_author(request, pk):
     }
     apiclient.api_call(request.user, f"authors/{author.slug}/", data)
     return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
     }
     apiclient.api_call(request.user, f"authors/{author.slug}/", data)
     return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
-        
-    
+
+
+@require_POST
+@login_required
+def publish_collection(request, pk):
+    collection = get_object_or_404(models.Collection, pk=pk)
+    data = {
+        "title": collection.name,
+        "description": collection.description,
+        "book_slugs": "\n".join(
+            book.slug
+            for book in collection.book_set.exclude(slug=None).exclude(slug='')
+        )
+    }
+    apiclient.api_call(
+        request.user,
+        f"collections/{collection.slug}/",
+        data,
+        method='PUT',
+        as_json=True,
+    )
+    return redirect(reverse(
+        'admin:catalogue_collection_change', args=[collection.pk]
+    ))