Fernet-encrypted model fields for Django

0.9 · active · verified Sun Apr 12

django-fernet-fields-v2 provides Fernet symmetric encryption for Django model fields, leveraging the `cryptography` library. It is a fork of `django-fernet-fields`, specifically updated to support Django 4 and later versions, as well as Python 3.8+. The current version is 0.9, released in August 2023, with releases typically occurring on an as-needed basis to maintain compatibility.

Warnings

Install

Imports

Quickstart

To use `django-fernet-fields-v2`, define encrypted fields in your Django models by importing them from `fernet_fields`. Ensure your `settings.py` includes a `SECRET_KEY` (which it uses by default) or `FERNET_KEYS` for explicit key management. Then, create and apply migrations as usual. Data assigned to these fields will be automatically encrypted before saving to the database and decrypted upon retrieval.

import os
from django.db import models
from django.conf import settings
from fernet_fields import FernetTextField

# Minimum Django settings for model use
settings.configure(
    SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-testing-only-do-not-use-in-prod'),
    DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
    INSTALLED_APPS=['fernet_fields'],
)

# Define a model with an encrypted text field
class MyEncryptedModel(models.Model):
    secret_data = FernetTextField()

    def __str__(self):
        return f"Encrypted ID: {self.id}"

# Example usage (after migrations, typically via manage.py)
# In a real application, you would run makemigrations and migrate.
# For this quickstart, we'll simulate it for demonstration.
if not settings.configured:
    settings.configure(DEBUG=True, SECRET_KEY='dummy-key', INSTALLED_APPS=['fernet_fields'])

# Note: In a real Django project, you would create and apply migrations.
# For a standalone runnable example, we bypass direct model setup.
# from django.apps import apps; apps.populate(settings.INSTALLED_APPS)

# This part requires a proper Django setup with migrations applied.
# For demonstration, assume model and database are ready.
# from django.db import connection
# with connection.schema_editor() as schema_editor:
#     schema_editor.create_model(MyEncryptedModel)

# Demonstrate field usage (conceptually)
# If MyEncryptedModel was properly migrated:
# instance = MyEncryptedModel.objects.create(secret_data='This is highly sensitive information.')
# print(f"Saved encrypted data. Retrieved: {instance.secret_data}")
# print(f"Data in DB (would be encrypted): {MyEncryptedModel.objects.get(id=instance.id).secret_data}")

print("To run this, integrate into a Django project, define FERNET_KEYS or SECRET_KEY, and apply migrations.")
print("Example model `MyEncryptedModel` defined with `secret_data = FernetTextField()`")

view raw JSON →