Skip to main content

Django rule-engine - Field, Widget & API

A powerful Django field and widget that brings rule-engine to your Django projects with a beautiful visual editor, real-time validation, and a clean API.

Perfect for building flexible business rules, access control policies, discount conditions, validation rules, and any scenario where you need dynamic, user-configurable logic.

✨ Key Features

🎨 Visual Rule Editor

  • Syntax highlighting for better readability
  • Real-time validation with immediate feedback
  • Auto-formatting for JSON example data
  • Keyboard shortcuts (Ctrl+Enter to validate)
  • Dark mode support with modern UI

🔌 Easy Integration

from django_rule_engine.fields import RuleField

class MyModel(models.Model):
    access_rule = RuleField(
        verbose_name="Access Rule",
        example_data={
            "age": 25,
            "status": "active",
            "role": "admin"
        }
    )

⚡ REST API

Built-in validation endpoint for frontend validation:

POST /api/validate-rule/   # {"rule", "data", "explain": true} also returns "explanation"
POST /api/explain-rule/    # {"rule", "data"} -> {"valid": true, "explanation": {...}}

🔍 Rule Explanation

Find out why a rule matches or not. explain() splits the rule on its top-level and/or, splits each piece into field / operator / expected value and evaluates everything with rule_engine itself:

from django_rule_engine.explain import explain

explain("age >= 18 and status == 'active'", {"age": 16, "status": "active"})
# {"atendido": False, "operador": "and", "condicoes": [
#    {"condicao": "age >= 18", "atendido": False,
#     "detalhes": {"tipo": "simples", "linhas": [
#        {"campo": "age", "operador": ">=", "esperado": "18", "valor": 16, "atendido": False, ...}]}},
#    {"condicao": "status == 'active'", "atendido": True, ...}]}
  • $any([... for x in LIST]) / $all(...) comprehensions (any list, optional if filter) are detailed per item (valores/resultados lists);
  • atendido is True/False, or None when evaluation fails (message in erro);
  • values of sensitive fields (CPF, e-mail, phone, password...) are hidden by default; change the regex with explain(..., sensitive=r"...") or the RULE_ENGINE_EXPLAIN_SENSITIVE_FIELDS setting (None shows everything).

The widget uses it when you test the rule with the example data: each piece of the rule is colored (green = matched, red = not matched, yellow = error) and a "Campo | Esperado | Valor" table is shown, with one column per item in $any/$all.

🧩 Rule Explanation as Blocks

explain_tree() explains any rule node by node — mixed and/or, not, nested comprehensions, ternaries, functions — from the rule_engine AST itself, and the result can be drawn as nested, Scratch-like blocks (green = matched, red = not matched, gray = undefined):

Rules drawn as nested blocks

from django_rule_engine.explain_tree import explain_tree

explanation = explain_tree(rule, data)  # {"atendido": False, "raiz": {"tipo": "logico", ...}}
{% load static rule_blocks %}
<link rel="stylesheet" href="{% static 'rule_widget/rule_blocks.css' %}">
{% regra_em_blocos explanation %}

or in the browser: RuleBlocks.render(element, explanation) (rule_widget/rule_blocks.js). Both draw the same HTML; sensitive fields stay hidden; colors are CSS variables. The API accepts "tree": true (/api/explain-rule/) or "explain_tree": true (/api/validate-rule/), and the widget draws the blocks when you test a rule. Full reference (node types, options, theming): Explicação em árvore e desenho em blocos.

🎯 Django Admin Integration

Seamlessly integrates with Django Admin - just add the field and the editor appears automatically!

📦 Installation

pip install django-rule-engine

Add to your INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    'django_rule_engine',
]

Include URLs:

urlpatterns = [
    path('', include('django_rule_engine.urls')),
]

💡 Use Cases

  • ✅ Access Control: Define who can access resources
  • ✅ Business Rules: Implement complex discount/pricing logic
  • ✅ Validation: Create dynamic validation rules
  • ✅ Eligibility: Determine program/service eligibility
  • ✅ Classification: Classify entities based on criteria
  • ✅ Filtering: Advanced data filtering and queries

🎓 Quick Example

from django.db import models
from django_rule_engine.fields import RuleField

class DiscountCampaign(models.Model):
    name = models.CharField(max_length=200)
    
    rule = RuleField(
        verbose_name="Discount Rule",
        example_data={
            "price": 150.00,
            "quantity": 3,
            "customer_type": "premium",
            "first_purchase": False
        },
        help_text="Example: price > 100 and quantity >= 2"
    )
    
    discount_percentage = models.DecimalField(max_digits=5, decimal_places=2)

    def calculate_discount(self, order_data):
        """Calculate discount based on the rule."""
        if not self.rule:
            return 0
        
        import rule_engine
        rule = rule_engine.Rule(self.rule)
        
        if rule.matches(order_data):
            return float(self.discount_percentage)
        return 0

📚 Documentation

Comprehensive documentation is included in the package:

🔧 Requirements

  • Python >= 3.10
  • Django >= 4.2
  • rule-engine >= 4.5.3
  • django-json-widget >= 2.0

🎯 Tested On

  • Python: 3.10, 3.11, 3.12, 3.13, 3.14
  • Django: 4.2, 5.0, 5.1, 5.2
  • Modern browsers (Chrome, Firefox, Safari, Edge)

Validation API

REST endpoint for dynamically validating rule-engine rules.

🚀 Quick Start

1. Import and Use

from django_rule_engine.fields import RuleField

class MyModel(models.Model):
    rule = RuleField(
        example_data={"age": 25, "status": "active"}
    )

📚 Documentation

  1. INDEX.md - Complete documentation index
  2. INSTALL.md - Installation guide
  3. QUICKSTART.md - Quick start (5 min)
  4. MIGRATION_GUIDE.md - Migration guide
  5. EXAMPLES.md - Code examples
  6. VISUAL_DEMO.py - Demonstração Visual

🎯 Implementation Example

The field is already being used in the Cohort model in coorte/models.py:

class Cohort(Model):
    name = CharField("cohort name", max_length=256, unique=True)
    rule = RuleField(
        "validation rule",
        blank=True,
        null=True,
        example_data={
            "login": "user123",
            "user": {"email": "user@example.com"},
            "name": "Zé da Silva",
            "active": True
        },
        default="login == 'user123' and user.email != 'user123@example.com'",
    )

    class Meta:
        verbose_name = _("cohort")
        verbose_name_plural = _("cohorts")
        ordering = ["name"]

    def __str__(self):
        return self.name

Metadata

Release files for django-rule-engine 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-rule-engine 1.2.0
File Size Uploaded Provenance Actions
django_rule_engine-1.2.0.tar.gz 60.5 kB With provenance Details for django_rule_engine-1.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-rule-engine 1.2.0
File Interpreter ABI Platform Actions
django_rule_engine-1.2.0-py3-none-any.whl Python 3 none any Details for django_rule_engine-1.2.0-py3-none-any.whl

Total release size: 107.6 kB

Release files / django_rule_engine-1.2.0.tar.gz

Download URL django_rule_engine-1.2.0.tar.gz
Size 60.5 kB
Tags Source
SHA-256 checksum
How to use checksums
977f7f9d8ad7a0df85febcb75fcb25bb4e46a58db824db999df16c9e54b79d21
BLAKE2b-256 checksum
How to use checksums
ec62d661eb536ff71224132ecc49b9468ff67193d50a2ea09104e6c125b2bb47
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Release files / django_rule_engine-1.2.0-py3-none-any.whl

Download URL django_rule_engine-1.2.0-py3-none-any.whl
Size 47.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c254ad492dc79a07f87e0d40bc671a28b7d23d809f759066280706fa158b5033
BLAKE2b-256 checksum
How to use checksums
5f57717e477235d60f7c284aea0ef5c910ed3c368dc1f96a61d623357170460e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Security for django-rule-engine 1.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_rule_engine-1.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page