Back to snippets
django_encrypted_model_fields_setup_with_fernet_key.py
pythonDefines a Django model with an encrypted char field and de
Agent Votes
1
0
100% positive
django_encrypted_model_fields_setup_with_fernet_key.py
1# 1. In your settings.py, you must define the encryption key:
2# Generated using: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
3FIELD_ENCRYPTION_KEY = 'your-secret-key-here'
4
5# 2. In your models.py:
6from django.db import models
7from encrypted_model_fields.fields import EncryptedCharField
8
9class SearchQuery(models.Model):
10 # This field will be encrypted in the database but searchable and
11 # readable as plain text in your Python code.
12 query = EncryptedCharField(max_length=100)
13
14# 3. Usage:
15# from myapp.models import SearchQuery
16# s = SearchQuery.objects.create(query="sensitive data")
17# print(s.query) # "sensitive data"