Skip to main content

Command Palette

Search for a command to run...

Django Admin Site

Updated
•17 min read•View as Markdown
H

Full Stack Blockchain Dev Affiliated with https://www.linkedin.com/in/mbaneshi/

Envisioning a reusable utility, a Django app (or ideally a Django package) that provides a comprehensive replacement for the Django admin using Svelte, with dynamic field mapping, reusable Svelte components, and all the standard admin functionalities. This is a significantly more ambitious and powerful concept!

Let's brainstorm and formulate a comprehensive, step-by-step plan to feed to an LLM (or to use for building the app manually).

I. Core Concept: Dynamic Field Mapping & Reusable Svelte Components

The central idea is a Django app that:

  1. Introspects Django Models: Reads your model definitions, fields, and relationships.

  2. Maps Fields to Svelte Components: Provides logic to determine the correct Svelte component based on the field type, like:

    • CharField -> <TextInput>

    • TextField -> <TextArea>

    • BooleanField -> <Checkbox>

    • IntegerField -> <NumberInput>

    • ForeignKey -> <DropdownSelect>

    • DateTimeField -> <DateTimeInput>

  3. Provides Reusable Svelte Components: A collection of pre-built Svelte components with proper styling and functionality (inputs, tables, pagination, sorting, forms, modals).

  4. Generates Svelte Pages: Generates SvelteKit routes for list, create, update, and delete views, dynamically populated with the mapped components.

  5. Provides API interaction: Provides helper functions or a client to interact with DRF endpoints.

  6. Customizable: Provides options for customization of component behavior, rendering, and styling

II. Package Structure (Django App & Related Files)

django-svelte-admin/
├── django_svelte_admin/        # Django app directory
│   ├── __init__.py
│   ├── apps.py
│   ├── models.py
│   ├── utils.py                 # Introspection, code generation logic
│   ├── components/          # Reusable Django Component Definitions
│   │    ├── base_component.py
│   │    ├── text_input.py
│   │    ├── number_input.py
│   │    ├── checkbox.py
│   │    ├── dropdown.py
│   │   ...
│   ├── management/
│   │   └── commands/
│   │       └── generate_svelte_admin.py
│   ├── signals.py
│   ├── templates/             # Jinja2 Svelte Component templates
│   │   ├── table.svelte
│   │   ├── form.svelte
│   │   ├── layout.svelte
│   │   ...
│   ├── urls.py
│   └── views.py
├── frontend/                   # Static frontend with svelte code
    ├── src/
        └── lib/
            └── components/    # Reusable Svelte Components (pre-built or generated)
            └── api.js         # API interaction logic.
└── setup.py                    # For packaging (optional, but highly recommended)

III. Prompt for LLM (or for manual building)

Here's a structured prompt, designed to be clear and comprehensive for an LLM:

Prompt Title: Create a Reusable Django Svelte Admin Replacement Package

Introduction:

We're aiming to develop a reusable Django app (or package) named django-svelte-admin that entirely replaces the Django admin with a modern Svelte-based UI. The primary goal is to dynamically generate Svelte components and routes based on Django model definitions, replicating the common functionalities of Django admin (list, create, update, delete, sorting, filtering, pagination). The outputted SvelteKit app will be in frontend/src.

Detailed Instructions:

  1. Django App Setup:

    • Create a Django app named django_svelte_admin with all the necessary files (__init__.py, apps.py, models.py, admin.py, urls.py, views.py).

    • Inside django_svelte_admin/models.py we don't have any model, this is a reusable application for any other django application.

  2. Django Introspection Logic (django_svelte_admin/utils.py):

    • Create functions to:

      • Introspect all models in a given Django project. The function should return a JSON structure containing all model information, including:

        • Model name

        • Fields (name, type, nullability, verbose_name, relation type etc.)

        • Relationships (foreign key, many-to-many etc.)

      • Introspect Django REST framework viewsets and their endpoints for each model.

      • Map Django model fields to corresponding Svelte components, define component types. For example CharField to TextInput , TextField to TextArea etc.

  3. Reusable Component Definitions (django_svelte_admin/components/)

    • Create abstract base_component and some common components classes (eg. text_input.py, checkbox.py).

    • Each reusable component class is a python class with following definition

      • name

      • component_name (the name of svelte component)

      • type (input, select, checkbox, text ...)

      • get_svelte_component method that returns an svelte code based on input field type.

  4. Code Generation (Jinja2) (django_svelte_admin/templates/)

    • Create Jinja2 templates for Svelte components and routes:

      • table.svelte: For displaying lists of model instances.

      • form.svelte: For creating and updating model instances.

      • layout.svelte: For common app layout.

      • components.svelte: Export reusable Svelte component definitions.

    • api.js : For common api calls.

  5. Svelte Components (frontend/src/lib/components/)

    • You need to create pre-built svelte reusable component in frontend/src/lib/components/ folder .

    • Some example component are below:

      • TextInput.svelte

      • TextArea.svelte

      • Checkbox.svelte

      • DropdownSelect.svelte

      • DateTimeInput.svelte

  6. API Interaction frontend/src/lib/api.js:

    • Create API interaction function to be used by the frontend.
  7. Django Management Command (django_svelte_admin/management/commands/generate_svelte_admin.py):

    • Create a Django management command named generate_svelte_admin that triggers the full code generation process using the following steps:

      • Call introspection logic and generate the model data with its field and relationship definitions, and API endpoint information.

      • Render Jinja2 templates with model data to generate Svelte components and route files.

      • Output the Svelte code and necessary files to frontend/src/ folder.

  8. Django Signal (django_svelte_admin/signals.py):

    • Hook a signal (e.g. post_migrate) to trigger the code generation when migrations happen (or on app startup).
  9. Usage

    • Provide simple instruction for how to add django-svelte-admin application in INSTALLED_APP.

    • Explain how the users can run generate_svelte_admin command, after adding all their models into other application.

    • Provide instructions for how to run frontend application.

Detailed Requirements:

  • Dynamic Field Rendering: The generated Svelte UI should dynamically display the correct UI component (e.g. text input, checkbox, select, date picker) based on the Django model field type.

  • CRUD Operations: Generate the logic for Create, Retrieve, Update and Delete operations.

  • List View Features: List view should include pagination, sorting, filtering based on each field, with proper API integration.

  • Forms: Generated forms should use Svelte components and interact with the API (create and update).

  • Error Handling: Implement basic error handling for API requests on the Svelte side.

  • Styling: Provide basic styling for all the components, that can be improved by developer latter on.

  • Customization: Add option for customization in the generated Svelte components (like adding css classes).

Output:

  • The generated Svelte components and pages should be in frontend/src/.

  • The django-svelte-admin should be a reusable Django app (or package) that can be installed in any Django project.

  • The frontend should be a complete SvelteKit application that can be run by npm run dev.

Example Svelte Code (frontend/src/lib/components/TextInput.svelte):

  <script>
        export let name;
        export let value = '';
        export let label;
  </script>

    <div class="mb-4">
    <label for="{name}" class="block text-gray-700 text-sm font-bold mb-2">{label}</label>
        <input type="text"
               id="{name}"
               name={name}
               bind:value={value}
               class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
        />
    </div>

Example Python (inside reusable component):

# django_svelte_admin/components/text_input.py
from django_svelte_admin.components.base_component import BaseComponent

class TextInput(BaseComponent):
    name = 'TextInput'
    component_name = 'TextInput'
    type = 'input'
    def get_svelte_component(self, field_name, field_label):
      return f'<TextInput name="{field_name}" label="{field_label}"/>'

End Prompt:

Please provide the implementation details for this Django app (or package). Include all required files and code to make it function. The goal is to create a reusable, dynamic admin replacement.

IV. Brainstorming Notes & Key Decisions

  • Data Structure:

    • How will you represent fields, relationships, and component mappings? JSON structure will be helpful.
  • Template Complexity:

    • How complex should templates be? How much logic will be in them?

    • How will customization be handled?

  • Reusable Component Logic:

    • What's the abstraction level? Will they map directly to HTML inputs, or something more complex?
  • API Handling:

    • Will you use a single API helper, or auto-generate per model?
  • Frontend Structure:

    • Will all the Svelte components be bundled into a single package?
  • Package Creation:

    • Should it be made a distributable package?

This prompt provides a good starting point. Each step might require further refinement and more details.

By using this prompt as a base, you can iteratively request smaller pieces of the puzzle, which is the best way to approach such a large task.


Summarize our project and then outline how to set up a Jira project with a Kanban template to manage its development.

I. Project Summary: Django Svelte Admin Replacement Package

Goal: To develop a reusable Django package named django-svelte-admin that dynamically generates a complete SvelteKit-based admin UI, replacing the default Django admin panel. This package should streamline the creation of modern, interactive admin interfaces by automating the mapping of Django model fields to Svelte components.

Key Features:

  1. Dynamic Model Introspection: The package will introspect Django models, their fields (including types, nullability, verbose names, relations), and Django REST Framework (DRF) viewset endpoints.

  2. Field Mapping: It will map Django model fields to corresponding pre-built, reusable Svelte UI components (text inputs, checkboxes, selects, etc.).

  3. Reusable Svelte Components: The package will include a collection of pre-built Svelte components, properly styled and functional, available in /frontend/src/lib/components/ folder.

  4. Dynamic Route Generation: The package will generate SvelteKit routes for list (table), create, and update views based on Django models.

  5. CRUD Operations: The generated Svelte UI will provide full CRUD functionality for the Django models.

  6. List View Features: The list views will support pagination, sorting, and filtering based on model fields.

  7. API Interaction: The generated frontend will include API helper functions for seamless communication with DRF endpoints.

  8. Customization: Users will be able to customize certain aspects of the generated UI by extending the components and options.

  9. Deep Integration: The package will integrate with Django via a custom management command, and by using post_migrate signal, to automatically trigger code generation when models are created or modified.

  10. Usability: A simple and reusable system, installable in any Django project using pip and configurable via settings.py.

High-Level Technical Components:

  • Django App (django_svelte_admin):

    • utils.py: Contains introspection and code generation logic.

    • components/: Contains Django component definitions.

    • management/commands/: Contains generate_svelte_admin Django command.

    • signals.py: Catches Django signals to trigger the admin generation.

    • templates/: Contains Jinja2 templates for Svelte components and routes.

  • Svelte Frontend (frontend/src/):

    • lib/components/: Contains pre-built reusable Svelte components.

    • lib/api.js: API interaction functions.

    • SvelteKit routes and pages generated dynamically.

  • Packaging (setup.py): Used to create a pip-installable package (optional but highly recommended).

II. Jira Project Setup (Kanban Template)

Here’s how to set up a Jira project using a Kanban template, tailored for our project:

  1. Create a New Jira Project:

    • Go to your Jira instance.

    • Click on "Create project".

    • Select the "Kanban" template (This is most suitable for a continuous development effort like this).

    • Give your project a name like: django-svelte-admin or Svelte Admin Generator.

    • Click "Create Project".

  2. Configure the Kanban Board:

    • Columns: Kanban boards use columns to visualize the workflow. Use these initial columns:

      • Backlog: For all unstarted features and tasks.

      • To Do: Tasks that are ready to be worked on.

      • In Progress: Tasks being actively worked on.

      • Review: Tasks that are completed and awaiting peer review.

      • Testing: Tasks that are being tested.

      • Done: Completed tasks.

    • WIP Limits: Optionally set WIP (Work In Progress) limits for each column to avoid having too many tasks in progress at once.

  3. Create Issues (Tasks):

    • Each feature or task becomes a Jira "issue" on the Kanban board. Here's a breakdown of issue types:

      • Epic:

        • Use Epics for high-level themes or goals that encompass many features.

        • Examples:

          • "Core Django App Functionality"

          • "Svelte Component Creation"

          • "Code Generation Automation"

          • "Svelte Admin Frontend"

      • Story:

        • Use Stories for user-centric tasks that deliver a specific value.

        • Examples:

          • "As a developer, I want to be able to see a list of my django models"

          • "As a developer, I want to see editable forms based on my model fields."

          • "As a developer, I want to configure a Svelte components for CharField."

      • Task:

        • Use Tasks for smaller technical actions that help you achieve the user stories or Epics.

        • Examples:

          • "Implement the Django model introspection logic in utils.py."

          • "Implement the reusable component definition logic for CharField."

          • "Create Jinja2 template for form component."

          • "Create Svelte Text input component."

          • "Implement the generate_svelte_admin command."

          • "Create post_migrate signal handler."

      • Bug:

        • Use Bugs to track bugs or issues.

        • Examples:

          • "Generated form not rendering properly."

          • "Error on Django introspection"

  4. Prioritize the Backlog:

    • Drag and drop issues in the Backlog to arrange them by priority.

    • Use labels, or custom fields to add more classification to your issues.

  5. Assign and Move Issues:

    • Assign issues to team members.

    • As work progresses, move issues to the appropriate columns.

    • Use time estimation to track the time spent in each issue.

  6. Set up workflow:

    • Configure workflows for different issue types.

    • You can use status and transitions to control workflow.

  7. Use Sprints:

    • While Kanban is more about continuous workflow, you can break tasks into sprints for better focus and planning.
  8. Regular Board Checkups:

    • Hold regular stand-up meetings to discuss progress and obstacles.

    • Keep the board updated.

III. Example Issues (Stories and Tasks)

Here are a few examples of how you might create issues for this project:

  • Epic: "Core Django App Functionality"

    • Story: "As a developer, I want a Django command to automatically generate the frontend."

      • Task: "Implement Django generate_svelte_admin management command."

      • Task: "Write logic in utils.py to introspect models and APIs."

      • Task: "Create a Jinja2 template for Svelte list view."

      • Task: "Create a Jinja2 template for Svelte forms."

  • Story: "As a developer, I want automatic Svelte code generation after model migration."

    • Task: "Implement the post_migrate signal handler."
  • Epic: "Svelte Component Creation"

    • Story: "As a developer, I want reusable Svelte components."

      • Task: Create TextInput.svelte, TextArea.svelte, and Checkbox.svelte components."

      • Task: Create base_component class to be reusable.

      • Task: Create TextInput, TextArea, and Checkbox reusable component definition in python.

  • Epic: "Svelte Admin Frontend"

    • Story: "As a developer, I want a table view to show data"

      • Task: "Implement a logic to map model fields to table columns."
    • Story: "As a developer, I want form view to add or edit data"

      • Task: "Implement logic to generate Svelte form elements based on model definitions."

      • Task: "Create a Svelte component for DropdownSelect"

  • Bug: "Form view isn't working with boolean fields"

IV. Guidance for LLM (or when setting up tasks):

When providing these steps to an LLM or when planning the tasks yourself, consider the following guidance:

  • Small, Iterative Steps: Break down tasks into small, manageable pieces.

  • Clear Acceptance Criteria: Define clear acceptance criteria for each task or story (what does done look like?).

  • Focus on Core Functionality First: Prioritize the essential introspection and code generation logic before adding customization and advanced features.

  • Regular Testing: Test each component and feature thoroughly.

  • Documentation: Include detailed code comments and documentation as part of the process.

  • Team Communication: Stay in sync, hold regular meetings and update Jira tasks.

By using this framework, you'll have a structured approach to tackling the project, from planning to execution and testing. This should enable you to efficiently develop the django-svelte-admin package. Let me know if you want to break down a specific part of the Jira setup further.


Relying solely on Jinja2 for code generation, while functional, can be limiting and less flexible in the long run. Your suggestion to explore alternatives like automand and Node.js (or to draw inspiration from the Svelte CLI) opens up much more powerful and versatile possibilities. Let's brainstorm these alternative approaches and their benefits:

I. Limitations of Jinja2-Centric Approach:

  • String-Based Generation: Jinja2 primarily works with text templates, which can become complex and harder to maintain when dealing with complex code structures, especially with Svelte components.

  • Limited Logic: While Jinja2 supports basic logic, complex code generation logic (e.g., loops, conditionals, nested components) can become messy within the templates themselves.

  • Tight Coupling: Jinja2 templates are tightly coupled with Python, making it harder to move code generation logic to other tools or services.

  • Less Control over Svelte Features: Jinja2 doesn't have the granular control over Svelte's specific features (e.g., reactive declarations, stores, actions) that a dedicated Svelte-aware tool might provide.

II. Alternative Approaches (Brainstorming):

  1. automand - Django Code Generation:

    • Concept: automand is a Django project intended for automating different tasks by utilizing pydantic, by creating classes which describes configuration with pydantic.

    • Benefit: We could define pydantic classes that describe the desired output, and let automand handle the code generation. This is more structured compared to plain Jinja.

    • How it helps: We could provide configuration as pydantic classes, and describe each Svelte component, its type and code.

    • Potential Issues: Would need to learn and configure automand to work with our desired outcome. We also need to define our class structures to describe our Svelte output, which could be a burden at the first try.

    • LLM Guidance: We can feed this idea to LLM.

  2. Node.js-Based Code Generation:

    • Concept: Move the code generation logic to a Node.js-based tool that can:

      • Use libraries like fs to interact with file systems and read/write code.

      • Use template libraries like EJS, Handlebars, or Nunjucks (or even more sophisticated options) for text templating.

      • Leverage more advanced Svelte-specific tools for component manipulation (if needed).

    • Benefits:

      • Access to the vast Node.js ecosystem.

      • More powerful templating features.

      • Better separation of concerns (Django for the backend, Node.js for code generation).

      • Easier to incorporate other code-generation libraries or services (e.g., TypeScript generation).

    • How it helps: More freedom in generating code, better control over javascript environment, and better libraries for generating different files.

    • Potential Issues: Needs to set up a Node.js environment, and create a different logic for our code generation.

    • LLM Guidance: LLM could help in creating a node.js package which can read the data from Django, and use template engines to render the code.

  3. Svelte CLI-Inspired Approach:

    • Concept: Mimic the behavior of the Svelte CLI (create-svelte), which provides a command-line interface for generating Svelte projects, by creating a custom CLI for generating admin UIs.

    • Benefits:

      • Leverages the Svelte team's expertise in code generation and project structure.

      • Can provide a more user-friendly CLI for developers using your package.

      • Can generate more complex structures, not just component and route files.

    • How it helps: Can provide pre-built components with CLI which can be easily used by developers.

    • Potential Issues: Needs to spend more time in CLI development.

    • LLM Guidance: We can feed this idea to LLM.

  4. Abstract Syntax Tree (AST) Manipulation:

  • Concept: Instead of string-based templating, use ASTs to represent the code structure, and manipulate these ASTs with libraries or tools.

  • Benefits:

    • Type Safety: Can provide better type safety and error checking during the generation.

    • Flexibility: Easier to generate more complex code structures by manipulating the AST representation.

    • Code Transformations: Easy to refactor, rename or apply transformations over generated code.

  • How it helps: Better control over generated code structure, easier refactoring, less error-prone, type safe code.

  • Potential Issues: Need to learn how to use AST manipulation libraries (like esprima, recast , babel).

  • LLM Guidance: LLM can generate the AST and also can transform it to different needs.

III. Steps to Make it More Versatile

To make the generated code more versatile (beyond just admin interfaces), we need to think about:

  1. Model-Driven Generation: Move away from just thinking "admin" to thinking "any UI driven by a model." The generated Svelte code should display the correct output depending on model and field type.

  2. Component Abstraction:

    • Provide more configurable UI components in the Svelte library.

    • Make components composable.

    • Abstract different input types and display types to be reusable across the application.

    • Provide API for easily creating new reusable components.

  3. Customization Flexibility:

    • Allow developers to provide custom Svelte components that override the defaults.

    • Allow customization of the code generation process using plugins or configurations.

  4. Extendability

    • Allow user to add new configuration based on custom needs.

    • Provide an extensible core, so users can inject their own code and components as needed.

    • We can define a plugin mechanism, where users can use their plugins to modify the behaviour of the code generator.

IV. Brainstorming Example: Using Node.js

  1. Django Introspection: The Django app can expose the model/API data as a JSON endpoint.

  2. Node.js CLI:

    • A CLI tool (e.g., built with yargs or commander) that users invoke to trigger code generation.

    • The tool fetches the model/API data from the Django endpoint.

    • The tool uses templating libraries or AST manipulation to create Svelte code.

    • The tool outputs the code to the SvelteKit project.

  3. Configurable Templates: The templating logic is structured using JavaScript, allowing for more complex logic and reusable template pieces.

  4. Plugin Mechanism: Users can provide plugins to modify template rendering or add custom functionality.

V. LLM Guidance:

When guiding an LLM, you would phrase your requests like this:

  • "Instead of using Jinja2, let's generate the Svelte code from a Node.js tool. Create a Node.js package that can fetch Django model data, use the ejs library to create Svelte code, and output the Svelte files. Please create a simple cli command using yargs for the node.js project"

  • "How can we create a CLI similar to create-svelte to help build the basic structure of the project ?"

  • "Can you generate the necessary code for python automand package to generate Svelte code based on model schema"

  • "Help me create esprima, recast and babel codes that can help generate Svelte code from a AST transformation."

  • "How can I add a plugin architecture to this Node.js tool? Can you provide some example of plugins that modify the output of the generated Svelte code?"

  • "Instead of generating simple table and form, we should use composable components, how can i build a system that generates more complex interfaces"

VI. Summary of Benefits

  • Versatility: Generate code for more than just admin interfaces.

  • Power and Flexibility: Take advantage of Node.js, CLI, AST, and other advanced techniques for better code generation and maintainability.

  • Extensibility: Make the project highly customizable and pluggable for specific needs.

  • Developer-Friendly: Provide a better developer experience by using standard tooling, and creating an easy to use CLI.

  • Long-Term Scalability: Position the project for future growth and new use cases.

By exploring these alternatives, you'll create a much more robust, adaptable, and user-friendly solution for your goal. Let me know if you want to delve deeper into any of these specific approaches.