Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
valberg committed Sep 13, 2024
0 parents commit 6219c5e
Show file tree
Hide file tree
Showing 21 changed files with 561 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
__pycache__/
*.pyc
*.sw*
db.sqlite3
.pytest_cache
.idea/
*.mo
.env
venv/
.venv/


# collectstatic
src/static/
37 changes: 37 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
default_language_version:
python: python3
exclude: ^.*\b(migrations)\b.*$
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-ast
- id: check-merge-conflict
- id: check-case-conflict
- id: detect-private-key
- id: check-added-large-files
- id: check-json
- id: check-symlinks
- id: check-toml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 'v0.5.2'
hooks:
- id: ruff
args:
- --fix
- id: ruff-format
- repo: https://github.com/asottile/pyupgrade
rev: v3.16.0
hooks:
- id: pyupgrade
args:
- --py311-plus
exclude: migrations/
- repo: https://github.com/adamchainz/django-upgrade
rev: 1.19.0
hooks:
- id: django-upgrade
args:
- --target-version=5.0
9 changes: 9 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2023-present Víðir Valberg Guðmundsson <valberg@orn.li>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# django-admin-tui

[![PyPI - Version](https://img.shields.io/pypi/v/django-admin-tui.svg)](https://pypi.org/project/django-admin-tui)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-admin-tui.svg)](https://pypi.org/project/django-admin-tui)

-----

**Table of Contents**

- [About](#about)
- [Installation](#installation)
- [License](#license)

## About

`django-admin-tui` is a project aiming to render the Django admin in a text-based user interface (TUI)
using [Textual](https://textual.textualize.io/), bringing one of Djangos killer features to a terminal near you.

## Installation

```console
pip install django-admin-tui
```

## License

`django-admin-tui` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
6 changes: 6 additions & 0 deletions django_admin_tui/__about__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""About module for django_admin_tui."""

# SPDX-FileCopyrightText: 2023-present Víðir Valberg Guðmundsson <valberg@orn.li>
#
# SPDX-License-Identifier: MIT
__version__ = "0.0.1"
3 changes: 3 additions & 0 deletions django_admin_tui/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: 2023-present Víðir Valberg Guðmundsson <valberg@orn.li>
#
# SPDX-License-Identifier: MIT
Empty file.
Empty file.
18 changes: 18 additions & 0 deletions django_admin_tui/management/commands/admin_tui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Management command to run the Django Admin TUI."""

from typing import Any

from django.core.management import BaseCommand

from django_admin_tui.tui import DjangoAdminTUI


class Command(BaseCommand):
"""Management command to run the Django Admin TUI."""

help = """Run a TUI to browse django models."""

def handle(self, *args: Any, **options: Any) -> None: # noqa: ARG002, ANN401
"""Handle the management command."""
app = DjangoAdminTUI()
app.run()
189 changes: 189 additions & 0 deletions django_admin_tui/tui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""The core of the Django Admin TUI."""

from __future__ import annotations

from collections import defaultdict
from typing import TYPE_CHECKING

from asgiref.sync import sync_to_async
from django.apps import apps
from django.contrib import admin
from django.contrib.admin.utils import display_for_field
from django.contrib.admin.utils import display_for_value
from django.contrib.admin.utils import label_for_field
from django.contrib.admin.utils import lookup_field
from django.db import models
from textual import log
from textual import on
from textual.app import App
from textual.containers import Container
from textual.widget import Widget
from textual.widgets import Button
from textual.widgets import DataTable
from textual.widgets import Footer
from textual.widgets import Header
from textual.widgets import Label
from textual.widgets import Rule
from textual.widgets import Tree

if TYPE_CHECKING:
from django.contrib.admin import ModelAdmin
from django.db.models import Model
from textual.app import ComposeResult


class DjangoAdminTUI(App):
"""The main TUI application for the Django Admin TUI."""

def compose(self) -> ComposeResult:
"""Compose the main app."""
app_dict = defaultdict(list)

for model, model_admin in admin.site._registry.items():
app_label = model._meta.app_label

# get AppConfig instance for the app
app_config = apps.get_app_config(app_label)

if app_config.verbose_name:
app_label = str(app_config.verbose_name).upper()

model_dict = {
"model": model,
"model_admin": model_admin,
}
app_dict[app_label].append(model_dict)

yield RegistryTreeWidget(app_dict=app_dict)

yield Header(show_clock=True)

yield Container(id="main")

yield Footer()

@on(Tree.NodeSelected)
@on(Tree.NodeHighlighted)
async def on_node_selected(self, event: Tree.NodeSelected | Tree.NodeHighlighted) -> None:
"""Handle ."""
if not event.node.data:
return
model = event.node.data["model"]
model_admin = event.node.data["model_admin"]
container = self.query_one("#main")
container.styles.border = "solid", "white"
container.styles.border_title = model._meta.verbose_name
await container.remove_children()
await container.mount(ModelListView(model=model, model_admin=model_admin))


class RegistryTreeWidget(Widget):
"""A widget that displays the registry tree of Django ModelAdmins."""

DEFAULT_CSS = """
RegistryTreeWidget {
dock: left;
layout: vertical;
height: auto;
offset: 0 1;
}
"""

def __init__(self, app_dict: dict[str, list[dict[str, Model | ModelAdmin]]]) -> None:
self.app_dict = app_dict
super().__init__()

def compose(self) -> ComposeResult:
"""Compose the widget."""
tree = Tree("Django Admin")
tree.show_root = False

longest_app_label = max(len(app_label) for app_label in self.app_dict)

self.styles.width = longest_app_label + 5

# Each app has a label and a list of registered models
for app_label, model_dicts in self.app_dict.items():
app_node = tree.root.add(app_label)
for model_dict in model_dicts:
app_node.add_leaf(model_dict["model"]._meta.verbose_name_plural.capitalize(), data=model_dict)

tree.root.expand_all()
yield tree


class ModelListView(Widget):
"""A widget that displays a list of objects for a Django model.
This is the equivalent of the Django admins changelist view.
"""

DEFAULT_CSS = """
ListView {
layout: vertical;
height: auto;
border: solid white;
}
"""

model_admin: ModelAdmin
model: Model

def __init__(self, *, model_admin: ModelAdmin, model: Model) -> None:
self.model_admin = model_admin
self.model = model
super().__init__()

def compose(self) -> ComposeResult:
"""Compose the widget."""
self.border_title = self.model.__name__

yield Label(f"Select {self.model._meta.verbose_name} to change")

# Add button to add a new object
yield Button("Add", id="add_button")

yield Rule()

# Create a data table
yield DataTable(cursor_type="row")

async def on_mount(self) -> None:
"""Handle the mount event."""
table = self.query_one(DataTable)

columns = []

for field_name in self.model_admin.list_display:
text, attr = label_for_field(field_name, self.model, model_admin=self.model_admin, return_attr=True)
columns.append(str(text))

log(f"Columns: {columns}")

table.add_columns(*columns)

async for obj in self.model.objects.all():
empty_value_display = self.model_admin.get_empty_value_display()
row = []

for field_name in self.model_admin.list_display:
f, attr, value = await sync_to_async(
lookup_field,
)(field_name, obj, self.model_admin)
empty_value_display = getattr(attr, "empty_value_display", empty_value_display)
log(f"Field: {f}, Attr: {attr}, Value: {value}")
if f is None or f.auto_created:
boolean = getattr(attr, "boolean", False)
# Set boolean for attr that is a property, if defined.
if isinstance(attr, property) and hasattr(attr, "fget"):
boolean = getattr(attr.fget, "boolean", False)
result_repr = display_for_value(value, empty_value_display, boolean)
elif isinstance(f.remote_field, models.ManyToOneRel):
field_val = getattr(obj, f.name)
result_repr = empty_value_display if field_val is None else field_val
else:
result_repr = display_for_field(value, f, empty_value_display)

row.append(result_repr)
log(f"Row: {row}")
table.add_row(*row)
78 changes: 78 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "django-admin-tui"
dynamic = ["version"]
description = 'Django Admin in the terminal.'
readme = "README.md"
requires-python = ">=3.9"
license = "MIT"
keywords = []
authors = [
{ name = "Víðir Valberg Guðmundsson", email = "valberg@orn.li" },
]
classifiers = [
"Development Status :: 3 - Alpha",
"Programming Language :: Python",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
]
dependencies = [
"Django>=4.2",
"textual>=0.79"
]

[project.urls]
Documentation = "https://github.com/valberg/django-admin-tui#readme"
Issues = "https://github.com/valberg/django-admin-tui/issues"
Source = "https://github.com/valberg/django-admin-tui"

[tool.hatch.version]
path = "django_admin_tui/__about__.py"

[tool.ruff]
target-version = "py39"
extend-exclude = [
".git",
"__pycache__",
"manage.py",
"asgi.py",
"wsgi.py",
]
line-length = 120

[tool.ruff.lint]
select = ["ALL"]
ignore = [
"G004", # Logging statement uses f-string
"ANN101", # Missing type annotation for `self` in method
"ANN102", # Missing type annotation for `cls` in classmethod
"EM101", # Exception must not use a string literal, assign to variable first
"EM102", # Exception must not use a f-string literal, assign to variable first
"COM812", # missing-trailing-comma (https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules)
"ISC001", # single-line-implicit-string-concatenation (https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules)
"D105", # Missing docstring in magic method
"D106", # Missing docstring in public nested class
"FIX", # TODO, FIXME, XXX
"TD", # TODO, FIXME, XXX
"D104", # Missing docstring in public package
"D107", # Missing docstring in __init__
"ANN002", # Missing type annotation for `*args`
"ANN003", # Missing type annotation for `**kwargs`
"SLF001", # Access to a protected member
]

[tool.ruff.lint.isort]
force-single-line = true

[tool.ruff.lint.per-file-ignores]
"tests.py" = [
"S101", # Use of assert
"SLF001", # Private member access
"D100", # Docstrings
"D103", # Docstrings
]
3 changes: 3 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: 2023-present Víðir Valberg Guðmundsson <valberg@orn.li>
#
# SPDX-License-Identifier: MIT
Loading

0 comments on commit 6219c5e

Please sign in to comment.