djblets.forms.forms.key_value_form¶
A form for working with key/value stores.
- class KeyValueForm(data=None, files=None, instance=None, *args, **kwargs)[source]¶
A form for working with key/value stores.
Typical forms are built to work either with database models or with entirely custom objects, but are less useful when working with dictionaries, caches, generic object attributes, or other objects that work as key/value stores.
This form provides a standard way of loading fields from a key/value store and saving back out to one.
By default, it assumes it’s working with something that behaves like a dictionary (containing a
get()
method and a__getitem__
operator). This can be overridden by providing implementations ofget_key_value()
andset_key_value()
.Values for specific keys can be specially serialized/deserialized by providing
serialize_keyname_field()
anddeserialize_keyname_field()
functions. These take a value and are expected to return a serializable JSON value or a deserialized value, respectively.It’s also makes it easy to implement saving behavior for the object by overriding
save_instance()
.There’s support for dynamically marking fields as disabled and specifying the reason it’s disabled, for display in the form. This can be done by setting
disabled_fields
anddisabled_reasons
, and using the latter in a template.Fields can be blacklisted from loading or saving by setting
Meta.load_blacklist
andMeta.save_blacklist
, respectively to a list or tuple of field names. Unless specified otherwise, the loading blacklist will default to the same fields in the save blacklist.- Parameters
disabled_fields (dict) – A dictionary of field names to booleans indicating fields that should be disabled (if their values are set to
True
). Those fields will then be disabled in the HTML (by setting thedisabled
attribute on the field).disabled_reasons (dict) – A dictionary of field names to strings describing the reason a particular field is disabled. These are not required, and are not automatically outputted in any form, but may be useful to templates.
instance (object) – The instance being loaded and saved. This can be
None
(the default) when not yet working on an instance (but in that case,create_instance()
must be defined).
Example
With custom field serialization:
class MyForm(KeyValueForm): book = forms.ModelChoiceField(queryset=Book.objects.all()) def serialize_book_field(self, value): return { 'id': book.pk, 'title': book.title, } def deserialize_book_field(self, value): return Book.objects.get(pk=value['id'])
- load()[source]¶
Load form fields from the instance.
If an instance was passed to the form, any values found in that instance will be set as the initial data for the form. If an instance was not passed, then the fields will be left as their default values.
This also updates the disabled status of any fields marked as disabled in the
disabled_fields
attribute.
- save(commit=True, extra_save_blacklist=[])[source]¶
Save form fields back to the instance.
This will save the values of any fields not in the blacklist out to the instance.
If the instance doesn’t yet exist, it will be created first through a call to
create_instance()
.- Parameters
commit (boolean, optional) – Whether to save the instance after setting all the fields. Defaults to
True
(though this will do nothing ifsave_instance()
is not overridden).extra_save_blacklist (list, optional) – Additional fields that should not be saved from the form.
- Raises
ValueError – The form couldn’t be saved due to errors.
- get_key_value(key, default=None)[source]¶
Return the value for a key in the instance.
This defaults to calling a
get()
method on the instance, passing in the values forkey
anddefault
as positional arguments.This can be overridden to change how values are loaded from the instance.
- set_key_value(key, value)[source]¶
Set a value in the instance.
This defaults to calling the
[]
operator (as ininstance[key]
) to set the value.This can be overridden to change how values are set in the instance.
- Parameters
key (unicode) – The key in the instance where the value should be stored.
value (object) – The value to store in the instance.
- create_instance()[source]¶
Create a new instance.
If an instance was not provided to the form, this will be called prior to saving. It must return an instance that can have new values set.
If not implemented, and no instance is passed to the form, this will raise a
NotImplementedError
when called.- Returns
The resulting instance to populate.
- Return type
- Raises
NotImplementedError – The method was not overridden by a subclass, but was called due to an instance not being passed to the form.
- save_instance()[source]¶
Save the instance.
By default, this doesn’t do anything. Subclasses can override it to provide saving functionality for the instance.
- get_load_blacklist()[source]¶
Return the field blacklist for loading.
Any field names returned from here will not be loaded from the instance.
If the subclass has a
Meta.load_blacklist
attribute, it will be returned. If not, but it has aMeta.save_blacklist
attribute, that will be returned. Otherwise, an empty list will be returned.This can be overridden to provide more specialized behavior.
- Returns
The field names to blacklist from loading from the instance.
- Return type
- get_save_blacklist()[source]¶
Return the field blacklist for saving.
Any field names returned from here will not be saved to the instance.
If the subclass has a
Meta.save_blacklist
attribute, it will be returned. Otherwise, an empty list will be returned.This can be overridden to provide more specialized behavior.
- Returns
The field names to blacklist from saving to the instance.
- Return type