Repository navigation
Expand file tree
/
Copy pathrenderer.py
More file actions
76 lines (58 loc) · 2.53 KB
/
Copy pathrenderer.py
File metadata and controls
76 lines (58 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from functools import reduce
from hashlib import sha1
from operator import add, or_
from django import forms
from feincms3_forms.models import FormFieldBase
def short_prefix(obj, part=""):
"""
Stupid, stable prefix for the form
May be used to support more than one form on a single page and also to
discourage styling based on element IDs :-)
"""
identifier = f"{obj._meta.label}:{obj.pk}:{part}".encode()
return "form-" + sha1(identifier).hexdigest()[:5]
class FormMixin:
def get_form_fields(self, plugin, *, strip_name_prefix=False):
"""
Return the form fields generated by the passed plugin instance.
Args:
plugin: The plugin instance to get fields for
strip_name_prefix: If True, strip the plugin's name prefix from field names.
Useful for cleaner template access when using compound fields.
Returns:
Dict mapping field names to BoundField instances.
Example:
If a plugin with name="address" generates fields like "address_first_name"
and "address_last_name", calling get_form_fields(plugin, strip_name_prefix=True)
will return: {"first_name": <BoundField>, "last_name": <BoundField>}
"""
fields = self._f3f_plugin_fields[plugin]
if strip_name_prefix:
prefix = f"{plugin.name}_"
return {name.removeprefix(prefix): field for name, field in fields.items()}
return fields
def clean(self):
data = super().clean()
for hook in self._f3f_cleaners:
data = hook(self, data)
return data
def create_form(plugins, *, form_class=forms.Form, form_kwargs):
field_plugins = [plugin for plugin in plugins if isinstance(plugin, FormFieldBase)]
plugin_fields = {plugin: plugin.get_fields() for plugin in field_plugins}
all_fields = reduce(or_, plugin_fields.values(), {})
all_names = set(all_fields)
initial = reduce(
or_,
(plugin.get_initial() for plugin in field_plugins),
{},
)
form_kwargs["initial"] = initial | form_kwargs.get("initial", {})
form = type("Form", (FormMixin, form_class), all_fields)(**form_kwargs)
form._f3f_plugin_fields = {
plugin: {name: form[name] for name in fields}
for plugin, fields in plugin_fields.items()
} | {None: {name: form[name] for name in form.fields if name not in all_names}}
form._f3f_cleaners = reduce(
add, (plugin.get_cleaners() for plugin in field_plugins), []
)
return form