Skip to main content

Adds attributes to Django models.

Project description

pypi coverage PyPI - Python Version PyPI - Django Versions from Framework Classifiers PyPI - django CMS Versions from Framework Classifiers

This project is an opinionated implementation of JSONField for arbitrary HTML element attributes.

It aims to provide a sensible means of storing and managing arbitrary HTML element attributes for later emitting them into templates.

There are a wide variety of types of attributes and using the “normal” Django method of adding ModelFields for each on a business model is cumbersome at best and moreover may require related tables to allow cases where any number of the same type of attribute should be supported (i.e., data-attributes). This can contribute to performance problems.

To avoid these pitfalls, this package allows all of these attributes to be stored together in a single text field in the database as a JSON blob, but provides a nice widget to provide an intuitive, key/value pair interface and provide sensible validation of the keys used.

preview.gif

Contribute to this project and win rewards

Because this is a an open-source project, we welcome everyone to get involved in the project and receive a reward for their contribution. Become part of a fantastic community and help us make django CMS the best CMS in the world.

We’ll be delighted to receive your feedback in the form of issues and pull requests. Before submitting your pull request, please review our contribution guidelines.

We’re grateful to all contributors who have helped create and maintain this package. Contributors are listed at the contributors section.

Documentation

See REQUIREMENTS in the setup.py file for additional dependencies:

Installation

For a manual install:

  • run pip install djangocms-attributes-field

  • add djangocms_attributes_field to your INSTALLED_APPS (at least for CSP support)

  • run python manage.py migrate djangocms_attributes_field

Configuration

AttributeField

To use this field in your Models.model:

# models.py
...
from django.db import models
from djangocms_attributes_field.fields import AttributesField
...
MyCoolModel(models.Model):
    ...
    attributes = AttributesField()

That’s it!

There is an optional parameter that can be used when declaring the field:

``excluded_keys`` : This is a list of strings that will not be accepted as
                    valid keys

Since version 4, the following keys are always excluded (see djangocms_attributes_fields.fields.default_excluded_keys) to avoid unwanted execution of javascript:

["src", "href", "data", "action", "on*"]

'on*' represents any key that starts with 'on'.

property: [field_name]_str

AttributeField will also provide a handy property [field_name]_str that will emit the stored key/value pairs as a string suitable for inclusion in your template for the target HTML element in question. You can use it like this:

# models.py
...
MyCoolModel(models.Model):
    ...
    html_attributes = AttributesField()


# templates/my_cool_project/template.html
...
<a href="..." {{ object.html_attributes_str }}>click me</a>
...

(Assuming that object is a context variable containing a MyCoolModel instance.)

In addition to nicely encapsulating the boring task of converting key/value pairs into a string with proper escaping and marking-safe, this property also ensures that existing key/value pairs with keys that have since been added to the field’s excluded_keys are also not included in the output string.

AttributeWidget

The AttributesWidget is already used by default by the AttributesField, but there may be cases where you’d like to override its usage.

The widget supports two additional parameters:

``key_attrs`` : A dict of HTML attributes to apply to the key input field
``val_attrs`` : A dict of HTML attributes to apply to the value input field

These can be useful, for example, if it is necessary to alter the appearance of the widget’s rendered appearance. Again, for example, let’s say we needed to make the key and value inputs have specific widths. We could do this like so in our ModelForm:

# forms.py

from django import forms
from djangocms_attributes_field.widgets import AttributesWidget

MyCoolForm(forms.ModelForm):
    class Meta:
        fields = ['attributes', ...]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['attributes'].widget = AttributesWidget(key_attrs={'style': 'width:250px'},
                                                            val_attrs={'style': 'width:500px'})

Running Tests

You can run tests by executing:

virtualenv env
source env/bin/activate
pip install -r tests/requirements.txt
python tests/settings.py

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

djangocms_attributes_field-4.1.2.tar.gz (18.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

djangocms_attributes_field-4.1.2-py3-none-any.whl (19.8 kB view details)

Uploaded Python 3

File details

Details for the file djangocms_attributes_field-4.1.2.tar.gz.

File metadata

File hashes

Hashes for djangocms_attributes_field-4.1.2.tar.gz
Algorithm Hash digest
SHA256 ed7e9d78a47b30801fe6b411e1cb8aff3434ac594c2b6bb86c859d98aff59838
MD5 f26847d6c6cb4c3dda1edbb636a00b7e
BLAKE2b-256 8e53422c7da4759653c847ef59c9736d618e7e3b3abf47da75652ca23703ffa4

See more details on using hashes here.

Provenance

The following attestation bundles were made for djangocms_attributes_field-4.1.2.tar.gz:

Publisher: publish-to-live-pypi.yml on django-cms/djangocms-attributes-field

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file djangocms_attributes_field-4.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for djangocms_attributes_field-4.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d7b9df5cb34f4072fd8da390e79bed715637032772bad3bf4e9847e3c7216cdb
MD5 47bb41a9de65c0ef0a69da3c002608d4
BLAKE2b-256 6e8dcc648409da83c370352670ed98bd41a5c39d06a9b99de99ad6f6f5741b44

See more details on using hashes here.

Provenance

The following attestation bundles were made for djangocms_attributes_field-4.1.2-py3-none-any.whl:

Publisher: publish-to-live-pypi.yml on django-cms/djangocms-attributes-field

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page