adapters\adapters_python.md
Adapters Python
We will get started creating the adapter definition.
Adapters can be defined anywhere; we recommend a separate adapters.py
file.
Adapter instances also have access to the following variables:
self.object
- The model instance.self.field_name
- The field name.self.meta_field
- The models.Field instance.self.field_value
- The field value (Retrieved withgetattr(self.object, self.field_name)
).self.request
- The django HTTP request object.self.kwargs
- Any shared context / keyword arguments for this adapter.
1# myapp/adapters.py
2
3from wagtail_fedit.adapters import (
4 BaseFieldFuncAdapter,
5 VARIABLES,
6)
7
8class ColorizerAdapter(BaseFieldFuncAdapter):
9 # Keywords for the adapter can easily be defined.
10 # These will be used to inform the templatetag on what is nescessary, required and counts as a flag.
11 keywords = (
12 Keyword(
13 "target",
14 help_text="The target element to apply the background-image to - this should be a css selector.",
15 type_hint="str", # Type hint for the `adapter_help` command.
16 # optional=False, # Required is the default.
17 # absolute=False, # Counts as a keyword argument key=value instead of a boolean flag.
18 # default=None, # Default value if not provided, only for optional keyword arguments.
19 ),
20 )
21
22 # How the adapter will be adressed inside of the template tag.
23 identifier = "colorizer"
24
25 # The function to call in javascript.
26 js_function = "myColorizerJavascriptFunction"
27
28 # A simple description of what this adapter does.
29 usage_description = "Change the color of the text for the given target element."
30
31 def render_content(self, parent_context=None):
32 # This is not required; we will replace a CSS variable; thus we are not returning any actual content.
33 return ""
34
35 def get_response_data(self, parent_context=None):
36 """
37 Return the data to be sent to the frontend adapter.
38 """
39 data = super().get_response_data(parent_context)
40 return data | {
41 "color": self.field_value,
42 }
43
44 def get_form_attrs(self) -> dict:
45 """
46 Return form attributes for the form inside of the edit modal.
47 This can be used to control editor size.
48 """
49 attrs = super().get_form_attrs()
50 attrs[VARIABLES.FORM_SIZE_VAR] = "full" # Fullscreen, there is also `large`.
51 return attrs
We must then register the adapter to make sure it is available for templates.
This should be done in a wagtail_hooks.py
file.
1# myapp/wagtail_hooks.py
2
3from wagtail_fedit.adapters import adapter_registry
4from myapp.adapters import ColorizerAdapter
5
6adapter_registry.register(ColorizerAdapter)
View the custom Javascript adapter in the Adapters Javascript page.