Metadata-Version: 2.4
Name: audit-logger-jatin
Version: 0.1.2
Summary: A reusable Django package for automatic CREATE, UPDATE, and DELETE audit logging.
Author: Jatin Agrawal
License: MIT
Keywords: django,audit,audit-log,logging,tracking,django-package,history,admin
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.0
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=5.0
Dynamic: license-file

# 🔍 Django Audit Logger

A reusable Django package that automatically tracks **CREATE**, **UPDATE**, and **DELETE** operations across registered models using dynamic signal registration, decorators, JSON-based change tracking, admin filters, and CSV export.

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

---

## ✨ Features

- ✅ Tracks **CREATE**, **UPDATE**, and **DELETE** operations automatically
- ✅ Field-level change tracking with **old** and **new** values in JSON
- ✅ Simple `@audit_model` decorator for registering any model
- ✅ Works across **multiple apps** in the same Django project
- ✅ Built-in **Django Admin dashboard** with filters and search
- ✅ **CSV export** for audit logs
- ✅ Date-based navigation (year → month → day)
- ✅ Zero changes required to existing business logic

---

## Dependencies

- Python 3.9+
- Django 4.2+

All required dependencies are installed automatically when you install the package.

```bash
pip install audit-logger-jatin
```



## 📦 Installation

### Install from PyPI

```bash
pip install django-audit-logger
```

---

## ⚙️ Setup

### 1. Add to `INSTALLED_APPS`

```python
# settings.py

INSTALLED_APPS = [
    ...
    'audit_logger',
    ...
]
```

### 2. Run migrations

```bash
python manage.py makemigrations
python manage.py migrate
```

---

## 🚀 Usage

### Register a model for auditing

Simply apply the `@audit_model` decorator to any model you want to track:

```python
# models.py

from django.db import models
from audit_logger.decorators import audit_model

@audit_model
class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField()

    def __str__(self):
        return self.name
```

That's it — no signal wiring, no custom save methods. The decorator handles everything.

### Register models across multiple apps

```python
# inventory/models.py
@audit_model
class Product(models.Model):
    ...

# sales/models.py
@audit_model
class Order(models.Model):
    ...

# hr/models.py
@audit_model
class Employee(models.Model):
    ...
```

Logs will be stored with `app_name` and `model_name` so you can always tell them apart:

```
inventory | Product
sales     | Order
hr        | Employee
```

---

## 📋 How It Works

The package uses **Django Signals** under the hood:

| Signal | Purpose |
|--------|---------|
| `pre_save` | Captures old field values before an update |
| `post_save` | Logs CREATE or UPDATE after saving |
| `post_delete` | Logs DELETE after an object is removed |

Signals are connected **dynamically** inside `AppConfig.ready()` for every model registered via `@audit_model`.

---

## 📊 AuditLog Model

Each audit event is stored as a record with the following fields:

| Field | Description |
|-------|-------------|
| `action` | `CREATE`, `UPDATE`, or `DELETE` |
| `app_name` | The Django app the model belongs to |
| `model_name` | The model class name |
| `object_id` | Primary key of the affected object |
| `object_name` | String representation of the object |
| `changed_fields` | JSON diff of changed fields |
| `timestamp` | When the action occurred |

### Example — UPDATE log entry

```json
{
  "price": {
    "old": "10.00",
    "new": "20.00"
  },
  "stock": {
    "old": "100",
    "new": "85"
  }
}
```

---

## 🖥️ Django Admin

Access the audit dashboard at:

```
http://localhost:8000/admin/audit_logger/auditlog/
```

### Available filters

- **Action** — `CREATE` / `UPDATE` / `DELETE`
- **Model Name** — filter by specific model
- **App Name** — filter by Django app

### Search

Search logs by **object name** or **model name**.

### Date navigation

Browse logs by **year → month → day** using Django's built-in date hierarchy.

### CSV Export

Select any logs and use the **"Export selected logs as CSV"** admin action.  
The export includes: Action, App, Model, Object, Changes, Timestamp.

---

## 🗂️ Project Structure

```
audit_logger/
├── __init__.py
├── apps.py          # AppConfig — connects signals on startup
├── models.py        # AuditLog model
├── signals.py       # pre_save / post_save / post_delete handlers
├── decorators.py    # @audit_model decorator
├── registry.py      # Model registry
├── admin.py         # Admin dashboard, filters, CSV export
├── migrations/
README.md
LICENSE
setup.py
pyproject.toml
MANIFEST.in
```

---

## 🛠️ Technologies Used

| Technology | Purpose |
|------------|---------|
| Python | Core language |
| Django | Web framework |
| Django Signals | Automatic change detection |
| Django Admin | Audit dashboard |
| JSONField | Storing field-level diffs |
| SQLite | Default development database |
| CSV Export | Log download functionality |
| Git & GitHub | Version control |
| PyPI Packaging | Open-source distribution |

---

## 📝 Example — Full Workflow

```python
# 1. Register your model
@audit_model
class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)

# 2. Create a product — automatically logged as CREATE
p = Product.objects.create(name="Widget", price=10.00)

# 3. Update the product — automatically logged as UPDATE
p.price = 20.00
p.save()

# 4. Delete the product — automatically logged as DELETE
p.delete()

# 5. Query the audit trail
from audit_logger.models import AuditLog

logs = AuditLog.objects.filter(model_name="Product")
for log in logs:
    print(log.action, log.object_name, log.changed_fields)
```

---

## 📄 License

This project is licensed under the **MIT License** — see the [LICENSE](LICENSE) file for details.

---

## 🤝 Contributing

Contributions, issues, and feature requests are welcome!  
Feel free to open an issue or submit a pull request on [GitHub](https://github.com/jatin-agrawal17/django-audit-logger/).

---

## 👤 Author

**Your Name**  
[GitHub](https://github.com/jatin-agrawal17/django-audit-logger/) · [LinkedIn](https://www.linkedin.com/in/jatin-agrawal-b80092367/)

---

> Developed a reusable Django Audit Logger package that automatically tracks CREATE, UPDATE, and DELETE operations across registered models using dynamic signal registration, decorators, JSON-based change tracking, admin filters, and CSV export functionality.
