Package: sharing-configs
Sharing Configs for DjangoVersion:0.1.2Source:https://github.com/maykinmedia/sharing-configsKeywords:django,githubPythonVersion:3.7, 3.8, 3.9A reusable Django app to export and import resources usingSharing Configs API.Developed byMaykin Media B.V..Featuresprovides client to interact withSharing Configs APIeasy download and upload of resources in the Django adminInstallationInstall from PyPIpipinstallsharing-configsAddsharing_configsto theINSTALLED_APPSsetting.In the admin page ofSharingConfigsConfigconfigure access to the
Sharing Configs APIUsageThe Sharing Config Library provides two mixins to add into yourModelAdminclass to enable the import/export of objects through the Django admin:SharingConfigsImportMixin- to import objectsSharingConfigsExportMixin- to export objectsSharingConfigsMixin- to import and export objectsThe mixins provide custom admin views and request Sharing Configs API under the
hood. You will need to override theget_sharing_configs_import_dataandget_sharing_configs_export_datafunctions and implement your own
import/export behaviour.You can furthermore override the import/export forms that are used by
overriding the class variablessharing_configs_export_formandsharing_configs_import_form.fromsharing_configs.adminimportSharingConfigsMixinclassSomeObjectAdmin(SharingConfigsMixin,admin.ModelAdmin):sharing_configs_export_form=SomeObjectExportForm# Defaults to sharing_configs.forms.ExportToFormsharing_configs_import_form=SomeObjectImportForm# Defaults to sharing_configs.forms.ImportFormdefget_sharing_configs_export_data(self,obj:object)->bytes:"""
        Convert ``SomeObject`` to JSON or something.
        """# Your code...defget_sharing_configs_import_data(self,content:bytes)->object:"""
        Convert JSON (or whatever was exported by function above) to
        ``SomeObject``.
        """# Your code...ExampleWe 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:ConfigurationandTheme# models.pyfromdjango.dbimportmodelsfromsolo.modelsimportSingletonModelclassConfiguration(SingletonModel):"""Configuration that holds the current theme"""theme=models.ForeignKey("Theme",on_delete=models.SET_NULL,null=True,blank=True)classTheme(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 theThememodel 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_dataandget_sharing_configs_import_data# admin.pyimportjsonfromdjango.contribimportadminfromdjango.forms.modelsimportmodel_to_dictfromdjango.shortcutsimportget_object_or_404fromsharing_configs.adminimportSharingConfigsMixinfrom.modelsimportConfiguration,ThemeclassThemeAdmin(SharingConfigsMixin,admin.ModelAdmin):defget_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)returndump_json_theme.encode("utf-8")defget_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)returnColorTheme.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 acontext_processors.pyfile, to pass the
currently configured theme to the template context:deftheme(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 overridenbase_site.htmlin
the templates folder.{# admin/base_site.html #}{%extends"admin/base_site.html"%}{%blockextrastyle%}{%iftheme%}<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!