• Get Review Board
  • What's New
  • Products
  • Review Board Code review, image review, and document review
  • Documentation
  • Release Notes
  • Power Pack Enterprise integrations, reports, and enhanced document review
  • Try for 60 Days
  • Purchase
  • RBCommons Review Board as a Service, hosted by us
  • Pricing
  • RBTools Command line tools and Python API for Review Board
  • Documentation
  • Release Notes
  • Review Bot Automated code review, connecting tools you already use
  • Documentation
  • Release Notes
  • RB Gateway Manage Git and Mercurial repositories in your network
  • Documentation
  • Release Notes
  • Learn and Explore
  • What is Code Review?
  • Documentation
  • Frequently Asked Questions
  • Support Options
  • Third-Party Integrations
  • Demo
  • Review Board RBTools Power Pack Review Bot Djblets RB Gateway
    1. Djblets 5.x
    2. Version 5.x
    3. Version 4.x
    4. Version 3.x
    5. Version 2.x
    6. Version 2.0
    7. Version 1.0
    8. Version 0.9
    9. Djblets Documentation
    10. Module and Class References
    11. djblets.forms.forms.key_value_form
  • Home
  • Guides
  • Avatar Services Guides
  • Writing Avatar Services
  • Extension Guides
  • Writing Extensions
  • Testing Extensions
  • Feature Checks Guides
  • Introduction to Feature Checks
  • Writing Features
  • Writing Feature Checkers
  • Testing with Feature Checks
  • Integration Guides
  • Supporting Integrations
  • Writing Integrations
  • Privacy Compliance Guides
  • Getting and Checking Consent
  • Working with Personally Identifiable Information
  • Service Integrations
  • reCAPTCHA Guides
  • Using reCAPTCHA
  • Registries Guides
  • Writing Registries
  • Web API Guides
  • Writing Web API Resources
  • Adding OAuth2 Support
  • Module and Class References
  • djblets
  • djblets.deprecation
  • djblets.auth.forms
  • djblets.auth.ratelimit
  • djblets.auth.signals
  • djblets.auth.util
  • djblets.auth.views
  • djblets.avatars.errors
  • djblets.avatars.forms
  • djblets.avatars.registry
  • djblets.avatars.services
  • djblets.avatars.services.base
  • djblets.avatars.services.fallback
  • djblets.avatars.services.file_upload
  • djblets.avatars.services.gravatar
  • djblets.avatars.services.url
  • djblets.avatars.settings
  • djblets.cache.backend
  • djblets.cache.backend_compat
  • djblets.cache.context_processors
  • djblets.cache.errors
  • djblets.cache.forwarding_backend
  • djblets.cache.serials
  • djblets.cache.synchronizer
  • djblets.conditions
  • djblets.conditions.choices
  • djblets.conditions.conditions
  • djblets.conditions.errors
  • djblets.conditions.operators
  • djblets.conditions.values
  • djblets.configforms.forms
  • djblets.configforms.mixins
  • djblets.configforms.pages
  • djblets.configforms.registry
  • djblets.configforms.views
  • djblets.datagrid.grids
  • djblets.db.backends.mysql.base
  • djblets.db.fields
  • djblets.db.fields.base64_field
  • djblets.db.fields.comma_separated_values_field
  • djblets.db.fields.counter_field
  • djblets.db.fields.json_field
  • djblets.db.fields.modification_timestamp_field
  • djblets.db.fields.relation_counter_field
  • djblets.db.managers
  • djblets.db.query
  • djblets.db.query_catcher
  • djblets.db.query_comparator
  • djblets.db.validators
  • djblets.extensions.admin
  • djblets.extensions.errors
  • djblets.extensions.extension
  • djblets.extensions.forms
  • djblets.extensions.hooks
  • djblets.extensions.loaders
  • djblets.extensions.manager
  • djblets.extensions.middleware
  • djblets.extensions.models
  • djblets.extensions.packaging
  • djblets.extensions.resources
  • djblets.extensions.settings
  • djblets.extensions.signals
  • djblets.extensions.staticfiles
  • djblets.extensions.testing
  • djblets.extensions.testing.testcases
  • djblets.extensions.urls
  • djblets.extensions.views
  • djblets.extensions.templatetags.djblets_extensions
  • djblets.features
  • djblets.features.checkers
  • djblets.features.decorators
  • djblets.features.errors
  • djblets.features.feature
  • djblets.features.level
  • djblets.features.registry
  • djblets.features.testing
  • djblets.features.templatetags.features
  • djblets.forms.fields
  • djblets.forms.fieldsets
  • djblets.forms.forms
  • djblets.forms.forms.key_value_form
  • djblets.forms.widgets
  • djblets.gravatars
  • djblets.gravatars.templatetags.gravatars
  • djblets.http.middleware
  • djblets.http.responses
  • djblets.integrations.errors
  • djblets.integrations.forms
  • djblets.integrations.hooks
  • djblets.integrations.integration
  • djblets.integrations.manager
  • djblets.integrations.mixins
  • djblets.integrations.models
  • djblets.integrations.urls
  • djblets.integrations.views
  • djblets.log
  • djblets.log.middleware
  • djblets.log.siteconfig
  • djblets.log.urls
  • djblets.log.views
  • djblets.mail.dmarc
  • djblets.mail.message
  • djblets.mail.testing
  • djblets.mail.utils
  • djblets.markdown
  • djblets.markdown.extensions.escape_html
  • djblets.markdown.extensions.wysiwyg
  • djblets.markdown.extensions.wysiwyg_email
  • djblets.pipeline.compilers.es6
  • djblets.pipeline.compilers.less
  • djblets.pipeline.compilers.mixins
  • djblets.pipeline.compilers.rollup
  • djblets.pipeline.compilers.typescript
  • djblets.pipeline.settings
  • djblets.privacy.consent
  • djblets.privacy.consent.base
  • djblets.privacy.consent.common
  • djblets.privacy.consent.errors
  • djblets.privacy.consent.forms
  • djblets.privacy.consent.hooks
  • djblets.privacy.consent.registry
  • djblets.privacy.consent.tracker
  • djblets.privacy.models
  • djblets.privacy.pii
  • djblets.privacy.templatetags.djblets_privacy
  • djblets.recaptcha.mixins
  • djblets.recaptcha.siteconfig
  • djblets.recaptcha.templatetags.djblets_recaptcha
  • djblets.recaptcha.widgets
  • djblets.registries
  • djblets.registries.errors
  • djblets.registries.importer
  • djblets.registries.mixins
  • djblets.registries.registry
  • djblets.registries.signals
  • djblets.secrets
  • djblets.secrets.crypto
  • djblets.secrets.token_generators
  • djblets.secrets.token_generators.base
  • djblets.secrets.token_generators.legacy_sha1
  • djblets.secrets.token_generators.registry
  • djblets.secrets.token_generators.vendor_checksum
  • djblets.siteconfig
  • djblets.siteconfig.admin
  • djblets.siteconfig.context_processors
  • djblets.siteconfig.django_settings
  • djblets.siteconfig.forms
  • djblets.siteconfig.managers
  • djblets.siteconfig.middleware
  • djblets.siteconfig.models
  • djblets.siteconfig.signals
  • djblets.siteconfig.views
  • djblets.template.caches
  • djblets.template.context
  • djblets.template.loaders.conditional_cached
  • djblets.template.loaders.namespaced_app_dirs
  • djblets.testing.decorators
  • djblets.testing.testcases
  • djblets.testing.testrunners
  • djblets.urls.context_processors
  • djblets.urls.decorators
  • djblets.urls.patterns
  • djblets.urls.resolvers
  • djblets.urls.root
  • djblets.urls.staticfiles
  • djblets.util.compat.django.core.cache
  • djblets.util.compat.python.past
  • djblets.util.contextmanagers
  • djblets.util.dates
  • djblets.util.decorators
  • djblets.util.filesystem
  • djblets.util.functional
  • djblets.util.html
  • djblets.util.http
  • djblets.util.humanize
  • djblets.util.json_utils
  • djblets.util.properties
  • djblets.util.serializers
  • djblets.util.symbols
  • djblets.util.templatetags.djblets_deco
  • djblets.util.templatetags.djblets_email
  • djblets.util.templatetags.djblets_forms
  • djblets.util.templatetags.djblets_images
  • djblets.util.templatetags.djblets_js
  • djblets.util.templatetags.djblets_utils
  • djblets.util.typing
  • djblets.util.views
  • djblets.views.generic.base
  • djblets.views.generic.etag
  • djblets.webapi.auth
  • djblets.webapi.auth.backends
  • djblets.webapi.auth.backends.api_tokens
  • djblets.webapi.auth.backends.base
  • djblets.webapi.auth.backends.basic
  • djblets.webapi.auth.backends.oauth2_tokens
  • djblets.webapi.auth.views
  • djblets.webapi.decorators
  • djblets.webapi.encoders
  • djblets.webapi.errors
  • djblets.webapi.fields
  • djblets.webapi.managers
  • djblets.webapi.models
  • djblets.webapi.oauth2_scopes
  • djblets.webapi.resources
  • djblets.webapi.resources.base
  • djblets.webapi.resources.group
  • djblets.webapi.resources.registry
  • djblets.webapi.resources.root
  • djblets.webapi.resources.user
  • djblets.webapi.resources.mixins.api_tokens
  • djblets.webapi.resources.mixins.forms
  • djblets.webapi.resources.mixins.oauth2_tokens
  • djblets.webapi.resources.mixins.queries
  • djblets.webapi.responses
  • djblets.webapi.signals
  • djblets.webapi.testing
  • djblets.webapi.testing.decorators
  • djblets.webapi.testing.testcases
  • General Index
  • Python Module Index
  • Release Notes
  • 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]¶

    Bases: Form

    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 of get_key_value() and set_key_value().

    Values for specific keys can be specially serialized/deserialized by providing serialize_keyname_field() and deserialize_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 and disabled_reasons, and using the latter in a template.

    Fields can be blacklisted from loading or saving by setting Meta.load_blacklist and Meta.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 the disabled 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'])
    
    css_bundle_names = [][source]¶

    The list of CSS bundle names to include on the page.

    js_bundle_names = [][source]¶

    The list of JavaScript bundle names to include on the page.

    __init__(data=None, files=None, instance=None, *args, **kwargs)[source]¶

    Initialize the form.

    Parameters:
    • data (dict, optional) – Data for the form.

    • files (dict, optional) – File uploads for the form.

    • instance (object, optional) – The existing instance being loaded from, if any.

    • *args (tuple) – Positional arguments for the form.

    • **kwargs (dict) – Keyword arguments for the form.

    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 if save_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 for key and default as positional arguments.

    This can be overridden to change how values are loaded from the instance.

    Parameters:
    • key (unicode) – The key to fetch from the instance. This will be a field name in the form.

    • default (object, optional) – The default value, from the field’s initial value.

    Returns:

    The value from the instance.

    Return type:

    object

    set_key_value(key, value)[source]¶

    Set a value in the instance.

    This defaults to calling the [] operator (as in instance[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:

    object

    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 a Meta.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:

    list

    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:

    list

    __annotations__ = {}¶
    declared_fields = {}¶

    Keep up with the latest Review Board releases, security updates, and helpful information.

    About
    News
    Demo
    RBCommons Hosting
    Integrations
    Happy Users
    Support Options
    Documentation
    FAQ
    User Manual
    RBTools
    Administration Guide
    Power Pack
    Release Notes
    Downloads
    Review Board
    RBTools
    Djblets
    Power Pack
    Package Store
    PGP Signatures
    Contributing
    Bug Tracker
    Submit Patches
    Development Setup
    Wiki
    Follow Us
    Mailing Lists
    Reddit
    Twitter
    Mastodon
    Facebook
    YouTube

    Copyright © 2006-2025 Beanbag, Inc. All rights reserved.

    Terms of Service — Privacy Policy — AI Ethics Policy — Branding

    On this page

    • [Top]
    • KeyValueForm
      • KeyValueForm.css_bundle_names
      • KeyValueForm.js_bundle_names
      • KeyValueForm.__init__()
      • KeyValueForm.load()
      • KeyValueForm.save()
      • KeyValueForm.get_key_value()
      • KeyValueForm.set_key_value()
      • KeyValueForm.create_instance()
      • KeyValueForm.save_instance()
      • KeyValueForm.get_load_blacklist()
      • KeyValueForm.get_save_blacklist()
      • KeyValueForm.__annotations__
      • KeyValueForm.declared_fields