2019-12-09 20:00:45 +00:00
|
|
|
"""passbook form helpers"""
|
2019-10-12 12:23:03 +00:00
|
|
|
from django import forms
|
|
|
|
|
|
|
|
from passbook.admin.fields import YAMLField
|
|
|
|
|
|
|
|
|
|
|
|
class TagModelForm(forms.ModelForm):
|
|
|
|
"""Base form for models that have attributes"""
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
# Check if we have an instance, load tags otherwise use an empty dict
|
2019-12-31 11:51:16 +00:00
|
|
|
instance = kwargs.get("instance", None)
|
2019-10-12 12:23:03 +00:00
|
|
|
tags = instance.tags if instance else {}
|
|
|
|
# Make sure all predefined tags exist in tags, and set default if they don't
|
2019-12-31 11:51:16 +00:00
|
|
|
predefined_tags = (
|
|
|
|
self._meta.model().get_predefined_tags()
|
|
|
|
) # pylint: disable=no-member
|
2019-10-12 12:23:03 +00:00
|
|
|
for key, value in predefined_tags.items():
|
|
|
|
if key not in tags:
|
|
|
|
tags[key] = value
|
|
|
|
# Format JSON
|
2019-12-31 11:51:16 +00:00
|
|
|
kwargs["initial"]["tags"] = tags
|
2019-10-12 12:23:03 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def clean_tags(self):
|
|
|
|
"""Make sure all required tags are set"""
|
2019-12-31 11:51:16 +00:00
|
|
|
if hasattr(self.instance, "get_required_keys") and hasattr(
|
|
|
|
self.instance, "tags"
|
|
|
|
):
|
2019-10-12 12:23:03 +00:00
|
|
|
for key in self.instance.get_required_keys():
|
2019-12-31 11:51:16 +00:00
|
|
|
if key not in self.cleaned_data.get("tags"):
|
2019-10-12 12:23:03 +00:00
|
|
|
raise forms.ValidationError("Tag %s missing." % key)
|
2019-12-31 11:51:16 +00:00
|
|
|
return self.cleaned_data.get("tags")
|
|
|
|
|
2019-10-12 12:23:03 +00:00
|
|
|
|
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
class TagModelFormMeta:
|
|
|
|
"""Base Meta class that uses the YAMLField"""
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
field_classes = {"tags": YAMLField}
|