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.

🎯 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.1.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.1.0
File Size Uploaded Provenance Actions
django_rule_engine-1.1.0.tar.gz 43.9 kB With provenance Details for django_rule_engine-1.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 75.3 kB

Release files / django_rule_engine-1.1.0.tar.gz

Download URL django_rule_engine-1.1.0.tar.gz
Size 43.9 kB
Tags Source
SHA-256 checksum
How to use checksums
1d767f0aa5b2e12b553c8542f49f3e002cbf407038c816c690adc1ccb0ff6a26
BLAKE2b-256 checksum
How to use checksums
0c3e797858568e986943aa9bf0ec2ffb9a8520123248ce2cfea6010d115e93e5
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.1.0-py3-none-any.whl

Download URL django_rule_engine-1.1.0-py3-none-any.whl
Size 31.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
234faaae97b0b9686659424d926b4e9fffcc0cf1ce62d54269aa9981f7df88df
BLAKE2b-256 checksum
How to use checksums
346b97f8180fe2a656a909f24438b1c54a000a0a7fbb0c5f8ad2e6ed917a0f5f
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.1.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.1.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