django CMS Attributes Field
raw JSON → 4.1.2 verified Fri May 01 auth: no python
A Django field that stores arbitrary HTML attributes as key-value pairs, commonly used with django CMS plugins to allow editors to add custom attributes. Version 4.1.2 supports Django 3.2-5.1 and Python 3.9+. Release cadence is irregular, roughly 1-2 minor versions per year.
pip install djangocms-attributes-field Common errors
error ImportError: cannot import name 'AttributesField' from 'djangocms_attributes_field' ↓
cause Incorrect import path; the class is in the 'fields' submodule.
fix
Use: from djangocms_attributes_field.fields import AttributesField
error django.core.exceptions.ImproperlyConfigured: 'djangocms_attributes_field' is not a valid Django app ↓
cause Missing 'djangocms_attributes_field' in INSTALLED_APPS.
fix
Add 'djangocms_attributes_field' to your INSTALLED_APPS setting.
Warnings
breaking Version 4.0.0 dropped support for Django 3.2, 4.0, 4.1 and Python 3.6, 3.7, 3.8. ↓
fix Upgrade to Django >=4.2 and Python >=3.9 before upgrading to 4.x.
breaking Version 4.0.0 added form field validation from the model field; existing forms may throw validation errors if attributes contain keys in default_excluded_keys. ↓
fix Review excluded keys in settings: DJANGOCMS_ATTRIBUTES_FIELD_EXCLUDED_KEYS.
gotcha AttributesField stores data as JSON; empty dict vs None can cause differences in DB querying. ↓
fix Always set default=dict on the field to avoid None values.
Imports
- AttributesField wrong
from djangocms_attributes_field import AttributesFieldcorrectfrom djangocms_attributes_field.fields import AttributesField - AttributesFormField wrong
from djangocms_attributes_field.forms import AttributesFormFieldcorrectfrom djangocms_attributes_field.fields import AttributesFormField
Quickstart
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_settings')
import django
from django.conf import settings
settings.configure(
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
INSTALLED_APPS=['djangocms_attributes_field'],
DEFAULT_AUTO_FIELD='django.db.models.BigAutoField',
)
django.setup()
from django.db import models
from djangocms_attributes_field.fields import AttributesField
class MyModel(models.Model):
attributes = AttributesField(blank=True, default=dict)
# Save and retrieve
instance = MyModel.objects.create(attributes={'class': 'my-class', 'data-id': '42'})
print(instance.attributes)