Skip to main content

Sharing Configs for Django

Version:

0.1.2

Source:

https://github.com/maykinmedia/sharing-configs

Keywords:

django, github

PythonVersion:

3.7, 3.8, 3.9

Build status Coverage status black

python-versions django-versions pypi-version

A reusable Django app to export and import resources using Sharing Configs API.

Developed by Maykin Media B.V..

Features

  • provides client to interact with Sharing Configs API

  • easy download and upload of resources in the Django admin

Installation

  1. Install from PyPI

pip install sharing-configs
  1. Add sharing_configs to the INSTALLED_APPS setting.

  2. In the admin page of SharingConfigsConfig configure access to the Sharing Configs API

Usage

The Sharing Config Library provides two mixins to add into your ModelAdmin class to enable the import/export of objects through the Django admin:

  • SharingConfigsImportMixin - to import objects

  • SharingConfigsExportMixin - to export objects

  • SharingConfigsMixin - to import and export objects

The mixins provide custom admin views and request Sharing Configs API under the hood. You will need to override the get_sharing_configs_import_data and get_sharing_configs_export_data functions and implement your own import/export behaviour.

You can furthermore override the import/export forms that are used by overriding the class variables sharing_configs_export_form and sharing_configs_import_form.

from sharing_configs.admin import SharingConfigsMixin

class SomeObjectAdmin(SharingConfigsMixin, admin.ModelAdmin):

    sharing_configs_export_form = SomeObjectExportForm  # Defaults to sharing_configs.forms.ExportToForm
    sharing_configs_import_form = SomeObjectImportForm  # Defaults to sharing_configs.forms.ImportForm

    def get_sharing_configs_export_data(self, obj: object) -> bytes:
        """
        Convert ``SomeObject`` to JSON or something.
        """
        # Your code...

    def get_sharing_configs_import_data(self, content: bytes) -> object:
        """
        Convert JSON (or whatever was exported by function above) to
        ``SomeObject``.
        """
        # Your code...

Example

We can use the Sharing Configs library to exchange color-themes for the Django admin with other users. For this, we need a model that stores the color-theme, and use the Sharing Configs mixins to import and export the color-theme.

Create two models: Configuration and Theme

# models.py

from django.db import models
from solo.models import SingletonModel


class Configuration(SingletonModel):
    """Configuration that holds the current theme"""

    theme = models.ForeignKey("Theme", on_delete=models.SET_NULL, null=True, blank=True)


class Theme(models.Model):
    """All attributes used for theming."""

    name = models.CharField("name", max_length=100)
    primary = models.CharField("primary color", max_length=7)
    secondary = models.CharField("secondary color", max_length=7)
    accent = models.CharField("accent color", max_length=7)
    primary_fg = models.CharField("primary foreground color", max_length=7)

Register the Theme model in the admin and include our two mixins to introduce the UI to import and export objects, in this case, themes. Sharing Configs does not know how to import or export your model, so you will need to write this yourself. You can override the methods introduced by the mixins: get_sharing_configs_export_data and get_sharing_configs_import_data

# admin.py

import json

from django.contrib import admin
from django.forms.models import model_to_dict
from django.shortcuts import get_object_or_404

from sharing_configs.admin import SharingConfigsMixin

from .models import Configuration, Theme


class ThemeAdmin(SharingConfigsMixin, admin.ModelAdmin):

    def get_sharing_configs_export_data(self, obj: object) -> bytes:
        """Convert the theme to JSON."""
        theme = get_object_or_404(Theme, id=obj.id)
        theme_dict = model_to_dict(theme)
        theme_dict.pop("id", None)
        dump_json_theme = json.dumps(cleaned_theme_dict, sort_keys=True, default=str)
        return dump_json_theme.encode("utf-8")

    def get_sharing_configs_import_data(self, content: bytes) -> object:
        """
        Convert JSON to a new theme instance. Typically, the JSON that is
        read here is the same as that the JSON generated by the above
        function.
        """
        decoded_content = content.decode("utf-8")
        theme_dict = json.loads(decoded_content)
        return ColorTheme.objects.create(**theme_dict)

That takes care of the import and export functionality for exchaning color-themes. To make it actually working, we complete this example with some additional code. Create a context_processors.py file, to pass the currently configured theme to the template context:

def theme(request:object)->dict:
    """
    Create a dictionary of color variables to pass to the base_site.html Django admin page
    """
    conf = Configuration.get_solo()

    return {
        "theme": conf.theme
    }

Finally, pass the theme context variables to an overriden base_site.html in the templates folder.

{# admin/base_site.html #}
{% extends "admin/base_site.html" %}

{% block extrastyle %}
    {% if theme %}
        <style type="text/css">
            :root {
                --primary: {{ theme.primary }};
                --secondary:{{ theme.secondary }};
                --accent:{{ theme.accent }};
                --primary_fg:{{ theme.primary_fg }};
            }
        </style>
    {% endif %}
{% endblock %}

Now you can choose an available color-theme via the configuration inside the Django admin. Ofcourse, this will really shine when you configure a proper Sharing Configs API to exchange themes with eachother!

Metadata

Release files for sharing-configs 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sharing-configs 0.1.2
File Size Uploaded Provenance
sharing-configs-0.1.2.tar.gz 26.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for sharing-configs 0.1.2
File Interpreter ABI Platform
sharing_configs-0.1.2-py3-none-any.whl Python 3 none any Details

Total release size: 54.9 kB

Release files / sharing-configs-0.1.2.tar.gz

Download URL sharing-configs-0.1.2.tar.gz
Size 26.6 kB
Tags Source
SHA-256 checksum
How to use checksums
d71da6cfcf9f1905a84bd32a77222d6421049da644b047580bc340b4b1b4cde2
BLAKE2b-256 checksum
How to use checksums
87ab6c103d03f435d927cab7f436632925b3da0402247f32d25c160ebad40d0f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.8.13

Release files / sharing_configs-0.1.2-py3-none-any.whl

Download URL sharing_configs-0.1.2-py3-none-any.whl
Size 28.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
24a1cfad98bd015c428fe438f7ee3dc33c53e092e07b9e448fe491f550b57c2e
BLAKE2b-256 checksum
How to use checksums
b829c970a5eaad2f5b6f87f275bb238320d40b2e06e6b669d6ab07820ccb8bb7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.8.13

Security for sharing-configs 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page